@codragraph/cli 2.1.5 → 2.2.0-rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -13
- package/dist/cli/analyze.d.ts +9 -4
- package/dist/cli/analyze.js +37 -13
- package/dist/cli/graphpack.d.ts +48 -0
- package/dist/cli/graphpack.js +217 -0
- package/dist/cli/index.js +81 -3
- package/dist/cli/status.d.ts +1 -1
- package/dist/cli/status.js +8 -0
- package/dist/cli/tool.d.ts +11 -2
- package/dist/cli/tool.js +138 -8
- package/dist/core/adaptive-profile.d.ts +52 -0
- package/dist/core/adaptive-profile.js +180 -0
- package/dist/core/cgdb/cgdb-adapter.d.ts +34 -5
- package/dist/core/cgdb/cgdb-adapter.js +418 -5
- package/dist/core/cgdb/pool-adapter.js +1 -1
- 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/ingestion/pipeline-phases/parse-impl.js +3 -1
- package/dist/core/ingestion/pipeline-phases/structure.js +19 -3
- package/dist/core/ingestion/pipeline.d.ts +10 -0
- package/dist/core/run-analyze.d.ts +27 -2
- package/dist/core/run-analyze.js +598 -27
- package/dist/core/search/bm25-index.d.ts +19 -0
- package/dist/core/search/bm25-index.js +68 -29
- package/dist/core/semantic/relationships.d.ts +36 -0
- package/dist/core/semantic/relationships.js +261 -0
- package/dist/mcp/local/local-backend.js +48 -3
- package/dist/mcp/resources.js +125 -0
- package/dist/mcp/tools.js +105 -0
- package/dist/server/api.js +112 -0
- package/dist/storage/repo-manager.d.ts +29 -0
- package/dist/web/assets/agent-CQNZQ-hg.js +1139 -0
- package/dist/web/assets/architectureDiagram-UL44E2DR-B5_goS_i.js +36 -0
- package/dist/web/assets/blockDiagram-7IZFK4PR-D7ZAlDyv.js +132 -0
- package/dist/web/assets/{c4Diagram-DFAF54RM-C4Hl3J2U.js → c4Diagram-Y2BXMSZH-Djcgm_54.js} +1 -1
- package/dist/web/assets/{chunk-7RZVMHOQ-BitYcNVR.js → chunk-3SSMPTDK-Cv2Zy2FO.js} +1 -1
- package/dist/web/assets/{chunk-TBF5ZNIQ-DL5stGM1.js → chunk-6764PJDD-Cppb-jH-.js} +1 -1
- package/dist/web/assets/{chunk-KSICW3F5-BYzvDLNI.js → chunk-AZZRMDJM-BHlLC7p3.js} +1 -1
- package/dist/web/assets/{chunk-AEOMTBSW-BgTIXPsY.js → chunk-JQRUD6KW-3F8Zg-1N.js} +1 -1
- package/dist/web/assets/chunk-KRXBNO2N-C0mbN9a7.js +1 -0
- package/dist/web/assets/chunk-LCXTWHL2-BoiuJpIF.js +231 -0
- package/dist/web/assets/{chunk-O5ABG6QK-dHwHzA6n.js → chunk-LII3EMHJ-Dqq0Qguw.js} +1 -1
- package/dist/web/assets/chunk-RG4AUYOV-Bl5F_gDs.js +206 -0
- package/dist/web/assets/{chunk-TU3PZOEN-RLyvLcv-.js → chunk-T5OCTHI4-B2tIcggA.js} +1 -1
- package/dist/web/assets/chunk-W44A43WB-BHe37iN7.js +13 -0
- package/dist/web/assets/{chunk-RWUO3TPN-BgRTY0_k.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-PNC4W37J-DVhePRYg.js → cose-bilkent-UX7MHV2Q-BWr7v0Wr.js} +1 -1
- package/dist/web/assets/dagre-ND4H6XIP-De5LIh1B.js +4 -0
- package/dist/web/assets/diagram-3NCE3AQN-Dd22FSHy.js +43 -0
- package/dist/web/assets/diagram-GF46GFSD-Cev3THY8.js +24 -0
- package/dist/web/assets/diagram-HNR7UZ2L-D8Z8RQGs.js +3 -0
- package/dist/web/assets/diagram-QXG6HAR7-B8VOJOiE.js +24 -0
- package/dist/web/assets/diagram-WEQXMOUZ-va1bLoMD.js +10 -0
- package/dist/web/assets/{erDiagram-GCSMX5X6-C3dhDFA8.js → erDiagram-L5TCEMPS-B3_9uAoP.js} +5 -5
- package/dist/web/assets/{flowDiagram-OTCZ4VVT-CWSFWmhr.js → flowDiagram-H6V6AXG4-98m6maI1.js} +9 -9
- package/dist/web/assets/ganttDiagram-JCBTUEKG-vE2nzETb.js +292 -0
- package/dist/web/assets/gitGraphDiagram-S2ZK5IYY-DKc8uUg_.js +106 -0
- package/dist/web/assets/index-BAhe1HSk.css +1 -0
- package/dist/web/assets/index-VTKdaklA.js +1415 -0
- package/dist/web/assets/infoDiagram-3YFTVSEB-DYP-Srzx.js +2 -0
- package/dist/web/assets/{ishikawaDiagram-YMYX4NHK-DUoJvNP2.js → ishikawaDiagram-BNXS4ZKH-QZnkpmmb.js} +3 -3
- package/dist/web/assets/{journeyDiagram-SO5T7YLQ-RMFPNNqz.js → journeyDiagram-M6C3CM3L-B5ojIuqu.js} +1 -1
- package/dist/web/assets/{kanban-definition-LJHFXRCJ-BzpDs1K9.js → kanban-definition-75IXJCU3-BJA8liRR.js} +4 -4
- package/dist/web/assets/{katex-GD7MH7QM-DBQvrix-.js → katex-K3KEBU37-DUqZiCRL.js} +1 -1
- package/dist/web/assets/mindmap-definition-2TDM6QVE-BQj5yylD.js +96 -0
- package/dist/web/assets/pieDiagram-CU6KROY3-4eSrPiQz.js +30 -0
- package/dist/web/assets/quadrantDiagram-VICAPDV7-PzxN8j55.js +7 -0
- package/dist/web/assets/{requirementDiagram-M5DCFWZL-DLHOVTSv.js → requirementDiagram-JXO7QTGE-CtplTc5y.js} +2 -2
- package/dist/web/assets/sankeyDiagram-URQDO5SZ-CoSgvkxv.js +40 -0
- package/dist/web/assets/sequenceDiagram-VS2MUI6T-D7ygyXvJ.js +162 -0
- package/dist/web/assets/stateDiagram-7D4R322I-v01gvwji.js +1 -0
- package/dist/web/assets/stateDiagram-v2-36443NZ5-DFD2b8_x.js +1 -0
- package/dist/web/assets/{timeline-definition-5SPVSISX-TRSDRgPw.js → timeline-definition-O6YCAMPW-CTI3M65J.js} +4 -4
- package/dist/web/assets/{vennDiagram-IE5QUKF5-DNy7HRBM.js → vennDiagram-MWXL3ELB-RnB0XMP7.js} +6 -6
- package/dist/web/assets/wardley-L42UT6IY-5TKZOOLJ-C-ZcgEBb.js +173 -0
- package/dist/web/assets/wardleyDiagram-CUQ6CDDI-EwRi4kwo.js +78 -0
- package/dist/web/assets/{xychartDiagram-ZHJ5623Y-Dr9r7a35.js → xychartDiagram-N2JHSOCM-DA38II6y.js} +4 -4
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
- package/vendor/node_modules/node-addon-api/node_addon_api_except.stamp +0 -0
- package/dist/web/assets/agent-D5lb0zXz.js +0 -1089
- package/dist/web/assets/architectureDiagram-EMZXCZ2Q-CZtc99v_.js +0 -36
- package/dist/web/assets/blockDiagram-IGV67L2C-BtoUp-6Y.js +0 -132
- package/dist/web/assets/chunk-3GS5O3IE-DkUjU0WD.js +0 -231
- package/dist/web/assets/chunk-3YCYZ6SJ-CQkVgT_z.js +0 -1
- package/dist/web/assets/chunk-H3VCZNTA-Cx5XV_aC.js +0 -13
- package/dist/web/assets/chunk-HN6EAY2L-BBnyTNdB.js +0 -1
- package/dist/web/assets/chunk-PK6DOVAG-CvsEnugt.js +0 -206
- package/dist/web/assets/classDiagram-PPOCWD7C-DTr8QIOf.js +0 -1
- package/dist/web/assets/classDiagram-v2-23LJLIIU-DTr8QIOf.js +0 -1
- package/dist/web/assets/dagre-E77IOHMT-Dzx0A6ZU.js +0 -4
- package/dist/web/assets/diagram-H7BISOXX-CC9pRew1.js +0 -43
- package/dist/web/assets/diagram-JC5VWROH-Bau_i9tf.js +0 -24
- package/dist/web/assets/diagram-LXUTUG65-D9_FM2Gt.js +0 -10
- package/dist/web/assets/diagram-WEHSV5V5-BMlayouL.js +0 -24
- package/dist/web/assets/ganttDiagram-MUNLMDZQ-D3a67Yol.js +0 -292
- package/dist/web/assets/gitGraphDiagram-3HKGZ4G3-7jmry-vM.js +0 -106
- package/dist/web/assets/index-BgeqpYgd.js +0 -1415
- package/dist/web/assets/index-CT0GtFLZ.css +0 -1
- package/dist/web/assets/infoDiagram-MN7RKWGX-G7lhP0Ib.js +0 -2
- package/dist/web/assets/mindmap-definition-2EUWGEK5-Bk0O4roa.js +0 -96
- package/dist/web/assets/pieDiagram-3IATQBI2-DKU7kpgS.js +0 -30
- package/dist/web/assets/quadrantDiagram-E256RVCF-BY0TGWCS.js +0 -7
- package/dist/web/assets/sankeyDiagram-L3NBLAOT-DVMj5rX2.js +0 -10
- package/dist/web/assets/sequenceDiagram-ZOUHS735-CJC73bV-.js +0 -157
- package/dist/web/assets/stateDiagram-MLPALWAM-BCFyESls.js +0 -1
- package/dist/web/assets/stateDiagram-v2-B5LQ5ZB2-DahzzIca.js +0 -1
- package/dist/web/assets/wardley-RL74JXVD-BCRCBASE-B-eZEzf9.js +0 -161
- package/dist/web/assets/wardleyDiagram-XU3VSMPF-BP-r1xzR.js +0 -20
|
@@ -0,0 +1,1139 @@
|
|
|
1
|
+
var kP=Object.defineProperty;var qb=n=>{throw TypeError(n)};var IP=(n,e,t)=>e in n?kP(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var p=(n,e,t)=>IP(n,typeof e!="symbol"?e+"":e,t),zp=(n,e,t)=>e.has(n)||qb("Cannot "+t);var re=(n,e,t)=>(zp(n,e,"read from private field"),t?t.call(n):e.get(n)),et=(n,e,t)=>e.has(n)?qb("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),_t=(n,e,t,r)=>(zp(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),Zi=(n,e,t)=>(zp(n,e,"access private method"),t);var nd=(n,e,t,r)=>({set _(s){_t(n,e,s,t)},get _(){return re(n,e,r)}});import{b0 as xP,b1 as OP}from"./index-VTKdaklA.js";import{buildDynamicSystemPrompt as CP}from"./context-builder-22jU3V56.js";const $P=["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"],JT=["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 Gb=Object.defineProperty,he=(n,e)=>{let t={};for(var r in n)Gb(t,r,{get:n[r],enumerable:!0});return Gb(t,Symbol.toStringTag,{value:"Module"}),t};function YT(n){const e=Symbol.for(n);return{brand(t,r){var a,o;const s=r?Symbol.for(`${n}.${r}`):e;class i extends(o=t,a=s,o){constructor(...l){super(...l);p(this,a,!0)}static isInstance(l){return typeof l=="object"&&l!==null&&s in l&&l[s]===!0}}return Object.defineProperty(i,"name",{value:t.name}),i},sub(t){return YT(`${n}.${t}`)},isInstance(t){return typeof t=="object"&&t!==null&&e in t&&t[e]===!0}}}const RP=YT("langchain");var PP=he({ContextOverflowError:()=>wy,LangChainError:()=>yy,ModelAbortError:()=>gg,addLangChainErrorFields:()=>Il,ns:()=>Uf});function Il(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
2
|
+
|
|
3
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
4
|
+
`,n}const Uf=RP.sub("error");var yy=class extends Uf.brand(Error){constructor(e){super(e);p(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},gg=class extends Uf.brand(yy,"model-abort"){constructor(e,t){super(e);p(this,"name","ModelAbortError");p(this,"partialOutput");this.partialOutput=t}},wy=class XT extends Uf.brand(yy,"context-overflow"){constructor(t){super(t??"Input exceeded the model's context window.");p(this,"name","ContextOverflowError");p(this,"cause")}static fromError(t){const r=new XT(t.message);return r.cause=t,r}};function Eu(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}function NP(n){return!!(n&&typeof n=="object"&&"toolCall"in n&&n.toolCall!=null&&typeof n.toolCall=="object"&&"id"in n.toolCall&&typeof n.toolCall.id=="string")}var $h=class extends Error{constructor(e,t){super(e);p(this,"output");this.output=t}};function Rh(n,e=Wo){n=n.trim();const t=n.indexOf("```");if(t===-1)return e(n);let r=n.substring(t+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 MP(n){try{return JSON.parse(n)}catch{}const e=n.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let t=0;function r(){for(;t<e.length&&/\s/.test(e[t]);)t+=1}function s(){if(e[t]!=='"')throw new Error(`Expected '"' at position ${t}, got '${e[t]}'`);t+=1;let l="",d=!1;for(;t<e.length;){const f=e[t];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(t+1,t+5);if(/^[0-9A-Fa-f]{0,4}$/.test(h))h.length===4?l+=String.fromCharCode(Number.parseInt(h,16)):l+=`u${h}`,t+=h.length;else throw new Error(`Invalid unicode escape sequence '\\u${h}' at position ${t}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${t}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return t+=1,l;l+=f}t+=1}return d&&(l+="\\"),l}function i(){const l=t;let d="";if(e[t]==="-"&&(d+="-",t+=1),t<e.length&&e[t]==="0"&&(d+="0",t+=1,e[t]>="0"&&e[t]<="9"))throw new Error(`Invalid number at position ${l}`);if(t<e.length&&e[t]>="1"&&e[t]<="9")for(;t<e.length&&e[t]>="0"&&e[t]<="9";)d+=e[t],t+=1;if(t<e.length&&e[t]===".")for(d+=".",t+=1;t<e.length&&e[t]>="0"&&e[t]<="9";)d+=e[t],t+=1;if(t<e.length&&(e[t]==="e"||e[t]==="E"))for(d+=e[t],t+=1,t<e.length&&(e[t]==="+"||e[t]==="-")&&(d+=e[t],t+=1);t<e.length&&e[t]>="0"&&e[t]<="9";)d+=e[t],t+=1;if(d==="-")return-0;const f=Number.parseFloat(d);if(Number.isNaN(f))throw t=l,new Error(`Invalid number '${d}' at position ${l}`);return f}function a(){if(r(),t>=e.length)throw new Error(`Unexpected end of input at position ${t}`);const l=e[t];if(l==="{")return c();if(l==="[")return o();if(l==='"')return s();if("null".startsWith(e.substring(t,t+4)))return t+=Math.min(4,e.length-t),null;if("true".startsWith(e.substring(t,t+4)))return t+=Math.min(4,e.length-t),!0;if("false".startsWith(e.substring(t,t+5)))return t+=Math.min(5,e.length-t),!1;if(l==="-"||l>="0"&&l<="9")return i();throw new Error(`Unexpected character '${l}' at position ${t}`)}function o(){if(e[t]!=="[")throw new Error(`Expected '[' at position ${t}, got '${e[t]}'`);const l=[];if(t+=1,r(),t>=e.length)return l;if(e[t]==="]")return t+=1,l;for(;t<e.length;){if(r(),t>=e.length||(l.push(a()),r(),t>=e.length))return l;if(e[t]==="]")return t+=1,l;if(e[t]===","){t+=1;continue}throw new Error(`Expected ',' or ']' at position ${t}, got '${e[t]}'`)}return l}function c(){if(e[t]!=="{")throw new Error(`Expected '{' at position ${t}, got '${e[t]}'`);const l={};if(t+=1,r(),t>=e.length)return l;if(e[t]==="}")return t+=1,l;for(;t<e.length;){if(r(),t>=e.length)return l;const d=s();if(r(),t>=e.length)return l;if(e[t]!==":")throw new Error(`Expected ':' at position ${t}, got '${e[t]}'`);if(t+=1,r(),t>=e.length||(l[d]=a(),r(),t>=e.length))return l;if(e[t]==="}")return t+=1,l;if(e[t]===","){t+=1;continue}throw new Error(`Expected ',' or '}' at position ${t}, got '${e[t]}'`)}return l}const u=a();if(r(),t<e.length)throw new Error(`Unexpected character '${e[t]}' at position ${t}`);return u}function Wo(n){try{return typeof n>"u"?null:MP(n)}catch{return null}}const jP=/([A-Z]+)([A-Z][a-z0-9]+)/g,LP=/([a-z0-9])([A-Z])/g,QT=/[-_\s]+/g;function DP(n){return n.replace(jP,"$1_$2").replace(LP,"$1_$2").replace(QT,"_").toLowerCase()}function UP(n){const e=n.trim();return/[-_\s]/.test(e)?e.replace(QT,"_").toLowerCase().replace(/_+([a-z0-9])/g,(t,r)=>r.toUpperCase()):e}function zP(n,e){return(e==null?void 0:e[n])||DP(n)}function FP(n,e){return(e==null?void 0:e[n])||UP(n)}function eE(n,e,t){const r={};for(const s in n)Object.hasOwn(n,s)&&(r[e(s,t)]=n[s]);return r}const tE="__lc_escaped__";function BP(n){return"lc"in n||Object.keys(n).length===1&&"__lc_escaped__"in n}function HP(n){return{[tE]:n}}function nE(n){return Object.keys(n).length===1&&"__lc_escaped__"in n}function VP(n){return n!==null&&typeof n=="object"&&"lc_serializable"in n&&typeof n.toJSON=="function"}function ZP(n){var t;let e;return n!==null&&typeof n=="object"?"lc_id"in n&&Array.isArray(n.lc_id)?e=n.lc_id:e=[((t=n.constructor)==null?void 0:t.name)??"Object"]:e=[typeof n],{lc:1,type:"not_implemented",id:e}}function _g(n,e=new WeakSet){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){if(e.has(n))return ZP(n);if(VP(n))return n;e.add(n);const t=n;if(BP(t))return e.delete(n),HP(t);const r={};for(const[s,i]of Object.entries(t))r[s]=_g(i,e);return e.delete(n),r}return Array.isArray(n)?n.map(t=>_g(t,e)):n}function yg(n){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){const e=n;if(nE(e))return e[tE];const t={};for(const[r,s]of Object.entries(e))t[r]=yg(s);return t}return Array.isArray(n)?n.map(e=>yg(e)):n}var KP=he({Serializable:()=>kr,get_lc_unique_name:()=>zf});function Jb(n){return Array.isArray(n)?[...n]:{...n}}function WP(n,e){const t=Jb(n);for(const[r,s]of Object.entries(e)){const[i,...a]=r.split(".").reverse();let o=t;for(const c of a.reverse()){if(o[c]===void 0)break;o[c]=Jb(o[c]),o=o[c]}o[i]!==void 0&&(o[i]={lc:1,type:"secret",id:[s]})}return t}function zf(n){const e=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof e.lc_name!="function"||n.lc_name()!==e.lc_name())?n.lc_name():n.name}var kr=class rE{constructor(e,...t){p(this,"lc_serializable",!1);p(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>{var s;return(s=this.lc_serializable_keys)==null?void 0:s.includes(r)})):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,zf(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 rE||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},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(t,Reflect.get(o,"lc_secrets",this)),Object.assign(r,Reflect.get(o,"lc_attributes",this));Object.keys(t).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]=_g(c,i);const a=eE(Object.keys(t).length?WP(s,t):s,zP,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Ir(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function by(n){return Ir(n)&&n.source_type==="url"&&"url"in n&&typeof n.url=="string"}function vy(n){return Ir(n)&&n.source_type==="base64"&&"data"in n&&typeof n.data=="string"}function qP(n){return Ir(n)&&n.source_type==="text"&&"text"in n&&typeof n.text=="string"}function sE(n){return Ir(n)&&n.source_type==="id"&&"id"in n&&typeof n.id=="string"}function iE(n){if(Ir(n)){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url}};if(n.source_type==="base64"){if(!n.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${n.mime_type};base64,${n.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function wg(n){const e=n.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${n}" - does not match type/subtype format.`);const t=e[0].trim(),r=e[1].trim();if(t===""||r==="")throw new Error(`Invalid mime type: "${n}" - type or subtype is empty.`);const s={};for(const i of n.split(";").slice(1)){const a=i.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${n}".`);const o=a[0].trim(),c=a[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${n}".`);s[o]=c}return{type:t,subtype:r,parameters:s}}function Gr({dataUrl:n,asTypedArray:e=!1}){const t=n.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(t){r=t[1].toLowerCase();const s=e?Uint8Array.from(atob(t[2]),i=>i.charCodeAt(0)):t[2];return{mime_type:r,data:s}}}function xl(n,e){if(n.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(n)}if(n.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(n)}if(n.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(n)}if(n.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(n)}throw new Error(`Unable to convert content block type '${n.type}' to provider-specific format: not recognized.`)}function pe(n,e){return Ie(n)&&n.type===e}function Ie(n){return typeof n=="object"&&n!==null}function Zn(n){return Array.isArray(n)}function V(n){return typeof n=="string"}function Br(n){return typeof n=="number"}function Sy(n){return n instanceof Uint8Array}function Yb(n){try{return JSON.parse(n)}catch{return}}const Ti=n=>n();function GP(n){if(n.type==="char_location"&&V(n.document_title)&&Br(n.start_char_index)&&Br(n.end_char_index)&&V(n.cited_text)){const{document_title:e,start_char_index:t,end_char_index:r,cited_text:s,...i}=n;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:t,endIndex:r,citedText:s}}if(n.type==="page_location"&&V(n.document_title)&&Br(n.start_page_number)&&Br(n.end_page_number)&&V(n.cited_text)){const{document_title:e,start_page_number:t,end_page_number:r,cited_text:s,...i}=n;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:t,endIndex:r,citedText:s}}if(n.type==="content_block_location"&&V(n.document_title)&&Br(n.start_block_index)&&Br(n.end_block_index)&&V(n.cited_text)){const{document_title:e,start_block_index:t,end_block_index:r,cited_text:s,...i}=n;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:t,endIndex:r,citedText:s}}if(n.type==="web_search_result_location"&&V(n.url)&&V(n.title)&&V(n.encrypted_index)&&V(n.cited_text)){const{url:e,title:t,encrypted_index:r,cited_text:s,...i}=n;return{...i,type:"citation",source:"url",url:e,title:t,startIndex:Number(r),endIndex:Number(r),citedText:s}}if(n.type==="search_result_location"&&V(n.source)&&V(n.title)&&Br(n.start_block_index)&&Br(n.end_block_index)&&V(n.cited_text)){const{source:e,title:t,start_block_index:r,end_block_index:s,cited_text:i,...a}=n;return{...a,type:"citation",source:"search",url:e,title:t??void 0,startIndex:r,endIndex:s,citedText:i}}}function aE(n){if(pe(n,"document")&&Ie(n.source)&&"type"in n.source){if(n.source.type==="base64"&&V(n.source.media_type)&&V(n.source.data))return{type:"file",mimeType:n.source.media_type,data:n.source.data};if(n.source.type==="url"&&V(n.source.url))return{type:"file",url:n.source.url};if(n.source.type==="file"&&V(n.source.file_id))return{type:"file",fileId:n.source.file_id};if(n.source.type==="text"&&V(n.source.data))return{type:"file",mimeType:String(n.source.media_type??"text/plain"),data:n.source.data}}else if(pe(n,"image")&&Ie(n.source)&&"type"in n.source){if(n.source.type==="base64"&&V(n.source.media_type)&&V(n.source.data))return{type:"image",mimeType:n.source.media_type,data:n.source.data};if(n.source.type==="url"&&V(n.source.url))return{type:"image",url:n.source.url};if(n.source.type==="file"&&V(n.source.file_id))return{type:"image",fileId:n.source.file_id}}}function JP(n){function*e(){for(const t of n){const r=aE(t);r?yield r:yield t}}return Array.from(e())}function Xb(n){function*e(){var r;const t=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(const s of t){if(pe(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=GP(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(pe(s,"thinking")&&V(s.thinking)){const{thinking:i,signature:a,...o}=s;yield{...o,type:"reasoning",reasoning:i,signature:a};continue}else if(pe(s,"redacted_thinking")){yield{type:"non_standard",value:s};continue}else if(pe(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(pe(s,"input_json_delta")){if(XP(n)&&((r=n.tool_call_chunks)!=null&&r.length)){const i=n.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(pe(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:Ti(()=>{if(typeof s.input=="string")return s.input;if(Ie(s.input)&&V(s.input.query))return s.input.query;if(V(s.partial_json)){const o=Yb(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:Ti(()=>{if(typeof s.input=="string")return s.input;if(Ie(s.input)&&V(s.input.code))return s.input.code;if(V(s.partial_json)){const o=Yb(s.partial_json);if(o!=null&&o.code)return o.code}return""})}};continue}}else if(pe(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)=>pe(c,"web_search_result")?[...o,c.url]:o,[])}};continue}else if(pe(s,"code_execution_tool_result")&&V(s.tool_use_id)&&Ie(s.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:s.tool_use_id,status:"success",output:s.content};continue}else if(pe(s,"mcp_tool_use")){yield{id:s.id,type:"server_tool_call",name:"mcp_tool_use",args:s.input};continue}else if(pe(s,"mcp_tool_result")&&V(s.tool_use_id)&&Ie(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(pe(s,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:s.input};continue}else if(pe(s,"search_result")){yield{id:s.id,type:"non_standard",value:s};continue}else if(pe(s,"tool_result")){yield{id:s.id,type:"non_standard",value:s};continue}else{const i=aE(s);if(i){yield i;continue}}yield{type:"non_standard",value:s}}}return Array.from(e())}const YP={translateContent:Xb,translateContentChunk:Xb};function XP(n){return typeof(n==null?void 0:n._getType)=="function"&&typeof n.concat=="function"&&n._getType()==="ai"}function QP(n){return by(n)?{type:n.type,mimeType:n.mime_type,url:n.url,metadata:n.metadata}:vy(n)?{type:n.type,mimeType:n.mime_type??"application/octet-stream",data:n.data,metadata:n.metadata}:sE(n)?{type:n.type,mimeType:n.mime_type,fileId:n.id,metadata:n.metadata}:n}function eN(n){return n.map(QP)}function tN(n){return!!(pe(n,"image_url")&&Ie(n.image_url)||pe(n,"input_audio")&&Ie(n.input_audio)||pe(n,"file")&&Ie(n.file))}function nN(n){if(pe(n,"image_url")&&Ie(n.image_url)&&V(n.image_url.url)){const e=Gr({dataUrl:n.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:n.image_url.url}}else{if(pe(n,"input_audio")&&Ie(n.input_audio)&&V(n.input_audio.data)&&V(n.input_audio.format))return{type:"audio",data:n.input_audio.data,mimeType:`audio/${n.input_audio.format}`};if(pe(n,"file")&&Ie(n.file)&&V(n.file.data)){const e=Gr({dataUrl:n.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(V(n.file.file_id))return{type:"file",fileId:n.file.file_id}}}return n}function rN(n){const e=[];typeof n.content=="string"?n.content.length>0&&e.push({type:"text",text:n.content}):e.push(...Ay(n.content));for(const t of n.tool_calls??[])e.push({type:"tool_call",id:t.id,name:t.name,args:t.args});return e}function sN(n){const e=[];typeof n.content=="string"?n.content.length>0&&e.push({type:"text",text:n.content}):e.push(...Ay(n.content));for(const t of n.tool_calls??[])e.push({type:"tool_call",id:t.id,name:t.name,args:t.args});return e}function Ay(n){const e=[];for(const t of n)tN(t)?e.push(nN(t)):e.push(t);return e}function iN(n){if(n.type==="url_citation"){const{url:e,title:t,start_index:r,end_index:s}=n;return{type:"citation",url:e,title:t,startIndex:r,endIndex:s}}if(n.type==="file_citation"){const{file_id:e,filename:t,index:r}=n;return{type:"citation",title:t,startIndex:r,endIndex:r,fileId:e}}return n}function oE(n){function*e(){var r;Ie((r=n.additional_kwargs)==null?void 0:r.reasoning)&&Zn(n.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:n.additional_kwargs.reasoning.summary.reduce((s,i)=>Ie(i)&&V(i.text)?`${s}${i.text}`:s,"")});const t=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(const s of t)if(pe(s,"text")){const{text:i,annotations:a,phase:o,extras:c,...u}=s,l=Ie(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(iN)}:yield{...u,...d,type:"text",text:String(i)}}for(const s of n.tool_calls??[])yield{type:"tool_call",id:s.id,name:s.name,args:s.args};if(Ie(n.additional_kwargs)&&Zn(n.additional_kwargs.tool_outputs))for(const s of n.additional_kwargs.tool_outputs){if(pe(s,"web_search_call")){const i={};if(Ie(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={};Ie(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(pe(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(pe(s,"computer_call")){yield{type:"non_standard",value:s};continue}else if(pe(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=Ti(()=>{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(pe(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(pe(s,"mcp_call")){yield{id:s.id,type:"server_tool_call",name:"mcp_call",args:s.input};continue}else if(pe(s,"mcp_list_tools")){yield{id:s.id,type:"server_tool_call",name:"mcp_list_tools",args:s.input};continue}else if(pe(s,"mcp_approval_request")){yield{type:"non_standard",value:s};continue}else if(pe(s,"tool_search_call")){const i={};Ie(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(pe(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(pe(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}Ie(s)&&(yield{type:"non_standard",value:s})}}return Array.from(e())}function aN(n){function*e(){yield*oE(n);for(const t of n.tool_call_chunks??[])yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}return Array.from(e())}const oN={translateContent:n=>typeof n.content=="string"?rN(n):oE(n),translateContentChunk:n=>typeof n.content=="string"?sN(n):aN(n)};function cE(n){return typeof n=="object"&&n!==null&&"type"in n&&"content"in n&&(typeof n.content=="string"||Array.isArray(n.content))}function cN(n,e="pretty"){return e==="pretty"?uN(n):JSON.stringify(n)}function uN(n){const e=[],t=` ${n.type.charAt(0).toUpperCase()+n.type.slice(1)} Message `,r=Math.floor((80-t.length)/2),s="=".repeat(r),i=t.length%2===0?s:`${s}=`;if(e.push(`${s}${t}${i}`),n.type==="ai"){const a=n;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(n.type==="tool"){const a=n;a.name&&e.push(`Name: ${a.name}`)}return typeof n.content=="string"&&n.content.trim()&&(e.length>1&&e.push(""),e.push(n.content)),e.join(`
|
|
8
|
+
`)}const Fp=Symbol.for("langchain.message");function Qb(n){return Array.isArray(n)?n:typeof n=="string"?n===""?[]:[{type:"text",text:n}]:n==null?[]:[n]}function Zs(n,e){if(typeof n=="string")return n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.length===0?n:Array.isArray(e)&&e.some(t=>Ir(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e];if(Array.isArray(e)){const t=Qb(n);return qo(t,e)??[...t,...e]}else return e===""?n:Array.isArray(n)&&n.some(t=>Ir(t))?[...n,{type:"file",source_type:"text",text:e}]:[...Qb(n),{type:"text",text:e}]}function uE(n,e){return n==="error"||e==="error"?"error":"success"}function lN(n,e){function t(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=>t(a,s+1));const i={};for(const a of Object.keys(r))i[a]=t(r[a],s+1);return i}return JSON.stringify(t(n,0),null,2)}var DT,Lt=class extends kr{constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={});super(t);p(this,"lc_namespace",["langchain_core","messages"]);p(this,"lc_serializable",!0);p(this,DT,!0);p(this,"id");p(this,"name");p(this,"content");p(this,"additional_kwargs");p(this,"response_metadata");this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.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[eN,Ay,JP].reduce((t,r)=>r(t),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&&Fp in e&&e[Fp]===!0&&cE(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(DT=Fp,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=lN(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return cN(this,e)}};function dN(n){return Array.isArray(n)&&n.every(e=>typeof e.index=="number")}const lE=["index","created","timestamp"];function En(n,e,t){const r=(t==null?void 0:t.ignoreKeys)??lE;if(n==null&&e==null)return;if(n==null||e==null)return n??e;const s={...n};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]=En(s[i],a,t);else if(Array.isArray(s[i]))s[i]=qo(s[i],a,t);else{if(s[i]===a)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return s}function hN(n){return typeof n=="number"||typeof n=="string"}function ev(n){return typeof n!="object"||n===null||!("index"in n)?!1:hN(n.index)}function tv(n){if(typeof n!="object"||n===null||!("id"in n))return!1;const e=n.id;return e!=null&&e!==""}function nv(n){return n.endsWith("_delta")?n.slice(0,-6):n}function fN(n,e){return typeof n!="object"||n===null||typeof e!="object"||e===null||!("type"in n)||!("type"in e)?!1:typeof n.type=="string"&&typeof e.type=="string"&&nv(n.type)!==nv(e.type)}function pN(n,e){const t=ev(e),r=tv(e);return!t&&!r?-1:n.findIndex(s=>{const i=ev(s),a=tv(s);return t&&i?s.index!==e.index||fN(s,e)?!1:a&&r?s.id===e.id:!0:!t&&!i&&r&&a?s.id===e.id:!1})}function qo(n,e,t){if(!(n==null&&e==null)){if(n==null||e==null)return n||e;{const r=[...n];for(const s of e){const i=pN(r,s);if(i!==-1)r[i]=En(r[i],s,t);else{if(typeof s=="object"&&s!==null&&"text"in s&&s.text==="")continue;r.push(s)}}return r}}}function dE(n,e,t){if(!(n==null&&e==null)){if(n==null||e==null)return n??e;if(typeof n!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
9
|
+
Left ${typeof n}
|
|
10
|
+
Right ${typeof e}`);if(typeof n=="string"&&typeof e=="string")return n+e;if(Array.isArray(n)&&Array.isArray(e))return qo(n,e,t);if(typeof n=="object"&&typeof e=="object")return En(n,e,t);if(n===e)return n;throw new Error(`Can not merge objects of different types.
|
|
11
|
+
Left ${n}
|
|
12
|
+
Right ${e}`)}}var As=class hE extends Lt{static isInstance(e){if(!super.isInstance(e))return!1;let t=Object.getPrototypeOf(e);for(;t!==null;){if(t===hE.prototype)return!0;t=Object.getPrototypeOf(t)}return!1}};function fE(n){return typeof n.role=="string"}function Rt(n){return typeof(n==null?void 0:n._getType)=="function"}function Go(n){return As.isInstance(n)}var mN=he({ToolMessage:()=>_n,ToolMessageChunk:()=>Ol,defaultToolCallParser:()=>Ey,isDirectToolOutput:()=>Ty,isToolMessage:()=>_a,isToolMessageChunk:()=>pE});function Ty(n){return n!=null&&typeof n=="object"&&"lc_direct_tool_output"in n&&n.lc_direct_tool_output===!0}var _n=class extends Lt{constructor(e,t,r){const s=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:t}:e;super(s);p(this,"lc_direct_tool_output",!0);p(this,"type","tool");p(this,"status");p(this,"tool_call_id");p(this,"metadata");p(this,"artifact");this.tool_call_id=s.tool_call_id,this.artifact=s.artifact,this.status=s.status,this.metadata=s.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Ol=class extends As{constructor(e){super(e);p(this,"type","tool");p(this,"tool_call_id");p(this,"status");p(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const t=this.constructor;return new t({content:Zs(this.content,e.content),additional_kwargs:En(this.additional_kwargs,e.additional_kwargs),response_metadata:En(this.response_metadata,e.response_metadata),artifact:dE(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:uE(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Ey(n){const e=[],t=[];for(const r of n)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{t.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,t]}function _a(n){return typeof n=="object"&&n!==null&&"getType"in n&&typeof n.getType=="function"&&n.getType()==="tool"}function pE(n){return n._getType()==="tool"}function ky(n){switch(n){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 gN(n){if(Ie(n.document)&&Ie(n.document.source)){const e=ky(Ie(n.document)&&V(n.document.format)?n.document.format:"");if(Ie(n.document.source)){if(Ie(n.document.source.s3Location)&&V(n.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:n.document.source.s3Location.uri};if(Sy(n.document.source.bytes))return{type:"file",mimeType:e,data:n.document.source.bytes};if(V(n.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(n.document.source.text).toString("base64")};if(Zn(n.document.source.content))return{type:"file",mimeType:e,data:n.document.source.content.reduce((t,r)=>Ie(r)&&V(r.text)?t+r.text:t,"")}}}return{type:"non_standard",value:n}}function _N(n){if(pe(n,"image")&&Ie(n.image)){const e=ky(Ie(n.image)&&V(n.image.format)?n.image.format:"");if(Ie(n.image.source)){if(Ie(n.image.source.s3Location)&&V(n.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:n.image.source.s3Location.uri};if(Sy(n.image.source.bytes))return{type:"image",mimeType:e,data:n.image.source.bytes}}}return{type:"non_standard",value:n}}function yN(n){if(pe(n,"video")&&Ie(n.video)){const e=ky(Ie(n.video)&&V(n.video.format)?n.video.format:"");if(Ie(n.video.source)){if(Ie(n.video.source.s3Location)&&V(n.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:n.video.source.s3Location.uri};if(Sy(n.video.source.bytes))return{type:"video",mimeType:e,data:n.video.source.bytes}}}return{type:"non_standard",value:n}}function rv(n){function*e(){const t=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(const r of t){if(pe(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(pe(r,"citations_content")&&Ie(r.citationsContent)){yield{type:"text",text:Zn(r.citationsContent.content)?r.citationsContent.content.reduce((s,i)=>Ie(i)&&V(i.text)?s+i.text:s,""):"",annotations:Zn(r.citationsContent.citations)?r.citationsContent.citations.reduce((s,i)=>{if(Ie(i)){const a=Zn(i.sourceContent)?i.sourceContent.reduce((c,u)=>Ie(u)&&V(u.text)?c+u.text:c,""):"",o=Ti(()=>{if(Ie(i.location)){const c=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(Ie(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(pe(r,"document")&&Ie(r.document)){yield gN(r);continue}else if(pe(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(pe(r,"image")&&Ie(r.image)){yield _N(r);continue}else if(pe(r,"reasoning_content")&&V(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(pe(r,"text")&&V(r.text)){yield{type:"text",text:r.text};continue}else if(pe(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(pe(r,"tool_call"))continue;if(pe(r,"video")&&Ie(r.video)){yield yN(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const wN={translateContent:rv,translateContentChunk:rv};function sv(n){var r;const e=[],t=(r=n.additional_kwargs)==null?void 0:r.reasoning_content;if(V(t)&&t.length>0&&e.push({type:"reasoning",reasoning:t}),typeof n.content=="string")n.content.length>0&&e.push({type:"text",text:n.content});else for(const s of n.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 n.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const bN={translateContent:sv,translateContentChunk:sv};function iv(n){function*e(){const t=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(const r of t){if(pe(r,"text")&&V(r.text)){yield{type:"text",text:r.text};continue}else if(pe(r,"thinking")&&V(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(pe(r,"inlineData")&&Ie(r.inlineData)&&V(r.inlineData.mimeType)&&V(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(pe(r,"functionCall")&&Ie(r.functionCall)&&V(r.functionCall.name)&&Ie(r.functionCall.args)){yield{type:"tool_call",id:n.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(pe(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(pe(r,"fileData")&&Ie(r.fileData)&&V(r.fileData.mimeType)&&V(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(pe(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(pe(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const vN={translateContent:iv,translateContentChunk:iv};function av(n){function*e(){const t=typeof n.content=="string"?[{type:"text",text:n.content}]:n.content;for(const r of t){if(pe(r,"reasoning")&&V(r.reasoning)){const s=Ti(()=>{var a;const i=t.indexOf(r);if(Zn((a=n.additional_kwargs)==null?void 0:a.signatures)&&i>=0)return n.additional_kwargs.signatures.at(i)});V(s)?yield{type:"reasoning",reasoning:r.reasoning,signature:s}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(pe(r,"thinking")&&V(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(pe(r,"text")&&V(r.text)){yield{type:"text",text:r.text};continue}else if(pe(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(pe(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 SN={translateContent:av,translateContentChunk:av};function ov(n){var r;const e=[],t=(r=n.additional_kwargs)==null?void 0:r.reasoning;if(V(t)&&t.length>0&&e.push({type:"reasoning",reasoning:t}),typeof n.content=="string"){let s=n.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 n.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 n.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const AN={translateContent:ov,translateContentChunk:ov};function cv(n){var r;const e=[],t=(r=n.additional_kwargs)==null?void 0:r.reasoning_content;if(V(t)&&t.length>0&&e.push({type:"reasoning",reasoning:t}),typeof n.content=="string")n.content.length>0&&e.push({type:"text",text:n.content});else for(const s of n.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 n.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const TN={translateContent:cv,translateContentChunk:cv};function uv(n){var s,i;const e=[],t=(s=n.additional_kwargs)==null?void 0:s.reasoning_details;let r=!1;if(Array.isArray(t)&&t.length>0)for(const a of t){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=n.additional_kwargs)==null?void 0:i.reasoning_content;V(a)&&a.length>0&&e.push({type:"reasoning",reasoning:a})}if(typeof n.content=="string")n.content.length>0&&e.push({type:"text",text:n.content});else for(const a of n.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 n.tool_calls??[])e.push({type:"tool_call",id:a.id,name:a.name,args:a.args});return e}const EN={translateContent:uv,translateContentChunk:uv};function lv(n){var r,s;const e=[];if(Ie((r=n.additional_kwargs)==null?void 0:r.reasoning)){const i=n.additional_kwargs.reasoning;if(Zn(i.summary)){const a=i.summary.reduce((o,c)=>Ie(c)&&V(c.text)?`${o}${c.text}`:o,"");a.length>0&&e.push({type:"reasoning",reasoning:a})}}const t=(s=n.additional_kwargs)==null?void 0:s.reasoning_content;if(V(t)&&t.length>0&&e.push({type:"reasoning",reasoning:t}),typeof n.content=="string")n.content.length>0&&e.push({type:"text",text:n.content});else for(const i of n.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 n.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}const kN={translateContent:lv,translateContentChunk:lv};function dv(n){function*e(){const t=Ti(()=>{var r;if(typeof n.content=="string")return n.additional_kwargs.originalTextContentBlock?[{...n.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:n.content}];{const s=(r=n.additional_kwargs)==null?void 0:r.originalTextContentBlock;if(s!=null&&s.thoughtSignature&&!n.content.some(i=>"thoughtSignature"in i)){const i=[...n.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 n.content}});for(const r of t){const s=Ti(()=>pe(r,"text")&&V(r.text)?{type:"text",text:r.text}:pe(r,"inlineData")&&Ie(r.inlineData)&&V(r.inlineData.mimeType)&&V(r.inlineData.data)?{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:pe(r,"functionCall")&&Ie(r.functionCall)&&V(r.functionCall.name)&&Ie(r.functionCall.args)?{type:"tool_call",id:n.id,name:r.functionCall.name,args:r.functionCall.args}:pe(r,"functionResponse")?{type:"non_standard",value:r}:pe(r,"fileData")&&Ie(r.fileData)&&V(r.fileData.mimeType)&&V(r.fileData.fileUri)?{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:pe(r,"executableCode")?{type:"non_standard",value:r}:pe(r,"codeExecutionResult")?{type:"non_standard",value:r}:{type:"non_standard",value:r}),i=Ti(()=>"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 IN={translateContent:dv,translateContentChunk:dv};globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",YP],["bedrock-converse",wN],["deepseek",bN],["google",IN],["google-genai",vN],["google-vertexai",SN],["groq",AN],["ollama",TN],["openai",oN],["openrouter",EN],["xai",kN]]));function mE(n){return globalThis.lc_block_translators_registry.get(n)}function gE(n,e){return En(n,e)??{}}function _E(n,e){const t={};return((n==null?void 0:n.audio)!==void 0||(e==null?void 0:e.audio)!==void 0)&&(t.audio=((n==null?void 0:n.audio)??0)+((e==null?void 0:e.audio)??0)),((n==null?void 0:n.image)!==void 0||(e==null?void 0:e.image)!==void 0)&&(t.image=((n==null?void 0:n.image)??0)+((e==null?void 0:e.image)??0)),((n==null?void 0:n.video)!==void 0||(e==null?void 0:e.video)!==void 0)&&(t.video=((n==null?void 0:n.video)??0)+((e==null?void 0:e.video)??0)),((n==null?void 0:n.document)!==void 0||(e==null?void 0:e.document)!==void 0)&&(t.document=((n==null?void 0:n.document)??0)+((e==null?void 0:e.document)??0)),((n==null?void 0:n.text)!==void 0||(e==null?void 0:e.text)!==void 0)&&(t.text=((n==null?void 0:n.text)??0)+((e==null?void 0:e.text)??0)),t}function xN(n,e){const t={..._E(n,e)};return((n==null?void 0:n.cache_read)!==void 0||(e==null?void 0:e.cache_read)!==void 0)&&(t.cache_read=((n==null?void 0:n.cache_read)??0)+((e==null?void 0:e.cache_read)??0)),((n==null?void 0:n.cache_creation)!==void 0||(e==null?void 0:e.cache_creation)!==void 0)&&(t.cache_creation=((n==null?void 0:n.cache_creation)??0)+((e==null?void 0:e.cache_creation)??0)),t}function ON(n,e){const t={..._E(n,e)};return((n==null?void 0:n.reasoning)!==void 0||(e==null?void 0:e.reasoning)!==void 0)&&(t.reasoning=((n==null?void 0:n.reasoning)??0)+((e==null?void 0:e.reasoning)??0)),t}function Iy(n,e){return{input_tokens:((n==null?void 0:n.input_tokens)??0)+((e==null?void 0:e.input_tokens)??0),output_tokens:((n==null?void 0:n.output_tokens)??0)+((e==null?void 0:e.output_tokens)??0),total_tokens:((n==null?void 0:n.total_tokens)??0)+((e==null?void 0:e.total_tokens)??0),input_token_details:xN(n==null?void 0:n.input_token_details,e==null?void 0:e.input_token_details),output_token_details:ON(n==null?void 0:n.output_token_details,e==null?void 0:e.output_token_details)}}var Ve=class extends Lt{constructor(e){var r;let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const s=(r=t.additional_kwargs)==null?void 0:r.tool_calls,i=t.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]=Ey(s);t.tool_calls=a??[],t.invalid_tool_calls=o??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){if(t.tool_calls){const o=t.tool_calls.filter(c=>{var u;return!((u=t.contentBlocks)!=null&&u.some(l=>l.type==="tool_call"&&l.id===c.id&&l.name===c.name))});t.contentBlocks.push(...o.map(c=>({type:"tool_call",id:c.id,name:c.name,args:c.args})))}const a=t.contentBlocks.filter(o=>o.type==="tool_call").filter(o=>{var c;return!((c=t.tool_calls)!=null&&c.some(u=>u.id===o.id&&u.name===o.name))});a.length>0&&(t.tool_calls=[...t.tool_calls??[],...a.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args}))])}}super(t);p(this,"type","ai");p(this,"tool_calls",[]);p(this,"invalid_tool_calls",[]);p(this,"usage_metadata");typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}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 t=mE(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(r=>!e.some(s=>s.id===r.id&&s.name===r.name));e.push(...t.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 xr(n){return n._getType()==="ai"}function Ph(n){return n._getType()==="ai"}var nt=class extends As{constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=bE(e.tool_call_chunks??[]);t={...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(t);p(this,"type","ai");p(this,"tool_calls",[]);p(this,"invalid_tool_calls",[]);p(this,"tool_call_chunks",[]);p(this,"usage_metadata");this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=mE(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const t=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!t.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 t={content:Zs(this.content,e.content),additional_kwargs:En(this.additional_kwargs,e.additional_kwargs),response_metadata:gE(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=qo(this.tool_call_chunks,e.tool_call_chunks);s!==void 0&&s.length>0&&(t.tool_call_chunks=s)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){const s=qo(this.tool_calls,e.tool_calls);s!==void 0&&s.length>0&&(t.tool_calls=s)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Iy(this.usage_metadata,e.usage_metadata));const r=this.constructor;return new r(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},ks=class yE extends Lt{constructor(t,r){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:r});super(t);p(this,"type","generic");p(this,"role");this.role=t.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return yE}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Cl=class extends As{constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t});super(e);p(this,"type","generic");p(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){const t=this.constructor;return new t({content:Zs(this.content,e.content),additional_kwargs:En(this.additional_kwargs,e.additional_kwargs),response_metadata:En(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 CN(n){return n._getType()==="generic"}function $N(n){return n._getType()==="generic"}var Ff=class extends Lt{constructor(e){super(e);p(this,"type","function");p(this,"name");this.name=e.name}static lc_name(){return"FunctionMessage"}},$l=class extends As{constructor(){super(...arguments);p(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){const t=this.constructor;return new t({content:Zs(this.content,e.content),additional_kwargs:En(this.additional_kwargs,e.additional_kwargs),response_metadata:En(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function RN(n){return n._getType()==="function"}function PN(n){return n._getType()==="function"}var Dn=class extends Lt{constructor(e){super(e);p(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Rl=class extends As{constructor(e){super(e);p(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){const t=this.constructor;return new t({content:Zs(this.content,e.content),additional_kwargs:En(this.additional_kwargs,e.additional_kwargs),response_metadata:En(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function NN(n){return n.getType()==="human"}function MN(n){return n.getType()==="human"}var ya=class extends Lt{constructor(e){super({...e,content:[]});p(this,"type","remove");p(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}},hr=class Xd extends Lt{constructor(t){super(t);p(this,"type","system")}static lc_name(){return"SystemMessage"}concat(t){if(typeof t=="string")return new Xd({content:Zs(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(Xd.isInstance(t))return new Xd({content:Zs(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw new Error("Unexpected chunk type for system message")}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},Pi=class extends As{constructor(e){super(e);p(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){const t=this.constructor;return new t({content:Zs(this.content,e.content),additional_kwargs:En(this.additional_kwargs,e.additional_kwargs),response_metadata:En(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function jN(n){return n._getType()==="system"}function LN(n){return n._getType()==="system"}function DN(n){return n.isCustomTool===!0}const wE=n=>n();function UN(n){return Eu(n)?n:typeof n.id=="string"&&n.type==="function"&&typeof n.function=="object"&&n.function!==null&&"arguments"in n.function&&typeof n.function.arguments=="string"&&"name"in n.function&&typeof n.function.name=="string"?{id:n.id,args:JSON.parse(n.function.arguments),name:n.function.name,type:"tool_call"}:n}function zN(n){return typeof n=="object"&&n!=null&&n.lc===1&&Array.isArray(n.id)&&n.kwargs!=null&&typeof n.kwargs=="object"}function Bp(n){let e,t;if(zN(n)){const r=n.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",t=n.kwargs}else{const{type:r,...s}=n;e=r,t=s}if(e==="human"||e==="user")return new Dn(t);if(e==="ai"||e==="assistant"){const{tool_calls:r,...s}=t;if(!Array.isArray(r))return new Ve(t);const i=r.map(UN);return new Ve({...s,tool_calls:i})}else{if(e==="system")return new hr(t);if(e==="developer")return new hr({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new _n({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new ya({...t,id:t.id});throw Il(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(n,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function ys(n){if(typeof n=="string")return new Dn(n);if(Rt(n))return n;if(Array.isArray(n)){const[e,t]=n;return Bp({type:e,content:t})}else if(fE(n)){const{role:e,...t}=n;return Bp({...t,type:e})}else return Bp(n)}function FN(n){if(typeof n=="string")return n;switch(n.type){case"text":return n.text??"";case"text-plain":return n.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 n.type?`[${n.type}]`:""}}function xy(n,e="Human",t="AI"){const r=[];for(const s of n){let i;if(s.type==="human")i=e;else if(s.type==="ai")i=t;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(FN).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 BN(n){if(n.data!==void 0)return n;{const e=n;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function Oy(n){const e=BN(n);switch(e.type){case"human":return new Dn(e.data);case"ai":return new Ve(e.data);case"system":return new hr(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Ff(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 _n(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new ks(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function HN(n){return n.map(Oy)}function VN(n){return n.map(e=>e.toDict())}function Nh(n){var t;const e=n._getType();if(e==="human")return new Rl({...n});if(e==="ai"){let r={...n};return"tool_calls"in r&&(r={...r,tool_call_chunks:(t=r.tool_calls)==null?void 0:t.map(s=>({...s,type:"tool_call_chunk",index:void 0,args:JSON.stringify(s.args)}))}),new nt({...r})}else{if(e==="system")return new Pi({...n});if(e==="function")return new $l({...n});if(ks.isInstance(n))return new Cl({...n});throw new Error("Unknown message type.")}}function bE(n){var s,i,a;const e=n.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},[]),t=[],r=[];for(const o of e){let c=null;const u=o.some(DN),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:"{}",m=((i=o.find(g=>g.id))==null?void 0:i.id)??((a=o[0])==null?void 0:a.id);if(u&&m){t.push({name:l,args:{input:f},id:m,type:"tool_call"});continue}try{if(c=Wo(h),!m||c===null||typeof c!="object"||Array.isArray(c))throw new Error("Malformed tool call chunk args.");t.push({name:l,args:c,id:m,type:"tool_call"})}catch{r.push({name:l,args:h,id:m,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:n,tool_calls:t,invalid_tool_calls:r}}var ZN="ffffffff-ffff-ffff-ffff-ffffffffffff",KN="00000000-0000-0000-0000-000000000000",WN=/^(?:[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(n){return typeof n=="string"&&WN.test(n)}function Mh(n){if(!Bf(n))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(n.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(n.slice(9,13),16))>>>8,e&255,(e=parseInt(n.slice(14,18),16))>>>8,e&255,(e=parseInt(n.slice(19,23),16))>>>8,e&255,(e=parseInt(n.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const cn=[];for(let n=0;n<256;++n)cn.push((n+256).toString(16).slice(1));function Da(n,e=0){return(cn[n[e+0]]+cn[n[e+1]]+cn[n[e+2]]+cn[n[e+3]]+"-"+cn[n[e+4]]+cn[n[e+5]]+"-"+cn[n[e+6]]+cn[n[e+7]]+"-"+cn[n[e+8]]+cn[n[e+9]]+"-"+cn[n[e+10]]+cn[n[e+11]]+cn[n[e+12]]+cn[n[e+13]]+cn[n[e+14]]+cn[n[e+15]]).toLowerCase()}function qN(n,e=0){const t=Da(n,e);if(!Bf(t))throw TypeError("Stringified UUID is invalid");return t}const GN=new Uint8Array(16);function Fu(){return crypto.getRandomValues(GN)}const $c={};function vE(n,e,t){var i;let r;const s=(n==null?void 0:n._v6)??!1;if(n){const a=Object.keys(n);a.length===1&&a[0]==="_v6"&&(n=void 0)}if(n)r=hv(n.random??((i=n.rng)==null?void 0:i.call(n))??Fu(),n.msecs,n.nsecs,n.clockseq,n.node,e,t);else{const a=Date.now(),o=Fu();JN($c,a,o),r=hv(o,$c.msecs,$c.nsecs,s?void 0:$c.clockseq,s?void 0:$c.node,e,t)}return e??Da(r)}function JN(n,e,t){return n.msecs??(n.msecs=-1/0),n.nsecs??(n.nsecs=0),e===n.msecs?(n.nsecs++,n.nsecs>=1e4&&(n.node=void 0,n.nsecs=0)):e>n.msecs?n.nsecs=0:e<n.msecs&&(n.node=void 0),n.node||(n.node=t.slice(10,16),n.node[0]|=1,n.clockseq=(t[8]<<8|t[9])&16383),n.msecs=e,n}function hv(n,e,t,r,s,i,a=0){if(n.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()),t??(t=0),r??(r=(n[8]<<8|n[9])&16383),s??(s=n.slice(10,16)),e+=122192928e5;const o=((e&268435455)*1e4+t)%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 YN(n,e,t){return!e&&!n&&crypto.randomUUID?crypto.randomUUID():XN(n,e,t)}function XN(n,e,t){var s;n=n||{};const r=n.random??((s=n.rng)==null?void 0:s.call(n))??Fu();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(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=r[i];return e}return Da(r)}function QN(n,e,t,r){switch(n){case 0:return e&t^~e&r;case 1:return e^t^r;case 2:return e&t^e&r^t&r;case 3:return e^t^r}}function Hp(n,e){return n<<e|n>>>32-e}function eM(n){const e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(n.length+1);r.set(n),r[n.length]=128,n=r;const s=n.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]=n[o*64+u*4]<<24|n[o*64+u*4+1]<<16|n[o*64+u*4+2]<<8|n[o*64+u*4+3];a[o]=c}a[i-1][14]=(n.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(n.length-1)*8&4294967295;for(let o=0;o<i;++o){const c=new Uint32Array(80);for(let m=0;m<16;++m)c[m]=a[o][m];for(let m=16;m<80;++m)c[m]=Hp(c[m-3]^c[m-8]^c[m-14]^c[m-16],1);let u=t[0],l=t[1],d=t[2],f=t[3],h=t[4];for(let m=0;m<80;++m){const g=Math.floor(m/20),y=Hp(u,5)+QN(g,l,d,f)+h+e[g]+c[m]>>>0;h=f,f=d,d=Hp(l,30)>>>0,l=u,u=y}t[0]=t[0]+u>>>0,t[1]=t[1]+l>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+f>>>0,t[4]=t[4]+h>>>0}return Uint8Array.of(t[0]>>24,t[0]>>16,t[0]>>8,t[0],t[1]>>24,t[1]>>16,t[1]>>8,t[1],t[2]>>24,t[2]>>16,t[2]>>8,t[2],t[3]>>24,t[3]>>16,t[3]>>8,t[3],t[4]>>24,t[4]>>16,t[4]>>8,t[4])}function tM(n){n=unescape(encodeURIComponent(n));const e=new Uint8Array(n.length);for(let t=0;t<n.length;++t)e[t]=n.charCodeAt(t);return e}const nM="6ba7b810-9dad-11d1-80b4-00c04fd430c8",rM="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function sM(n,e,t,r,s,i){const a=typeof t=="string"?tM(t):t,o=typeof r=="string"?Mh(r):r;if(typeof r=="string"&&(r=Mh(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|n,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 Da(c)}function Cy(n,e,t,r){return sM(80,eM,n,e,t,r)}Cy.DNS=nM;Cy.URL=rM;function iM(n){const e=aM(typeof n=="string"?Mh(n):n);return typeof n=="string"?Da(e):e}function aM(n){return Uint8Array.of((n[6]&15)<<4|n[7]>>4&15,(n[7]&15)<<4|(n[4]&240)>>4,(n[4]&15)<<4|(n[5]&240)>>4,(n[5]&15)<<4|(n[0]&240)>>4,(n[0]&15)<<4|(n[1]&240)>>4,(n[1]&15)<<4|(n[2]&240)>>4,96|n[2]&15,n[3],n[8],n[9],n[10],n[11],n[12],n[13],n[14],n[15])}function oM(n,e,t){n??(n={}),t??(t=0);let r=vE({...n,_v6:!0},new Uint8Array(16));if(r=iM(r),e){if(t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let s=0;s<16;s++)e[t+s]=r[s];return e}return Da(r)}const Vp={};function cM(n,e,t){var s;let r;if(n)r=fv(n.random??((s=n.rng)==null?void 0:s.call(n))??Fu(),n.msecs,n.seq,e,t);else{const i=Date.now(),a=Fu();uM(Vp,i,a),r=fv(a,Vp.msecs,Vp.seq,e,t)}return e??Da(r)}function uM(n,e,t){return n.msecs??(n.msecs=-1/0),n.seq??(n.seq=0),e>n.msecs?(n.seq=t[6]<<23|t[7]<<16|t[8]<<8|t[9],n.msecs=e):(n.seq=n.seq+1|0,n.seq===0&&n.msecs++),n}function fv(n,e,t,r,s=0){if(n.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()),t??(t=n[6]*127<<24|n[7]<<16|n[8]<<8|n[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|t>>>28&15,r[s++]=t>>>20&255,r[s++]=128|t>>>14&63,r[s++]=t>>>6&255,r[s++]=t<<2&255|n[10]&3,r[s++]=n[11],r[s++]=n[12],r[s++]=n[13],r[s++]=n[14],r[s++]=n[15],r}function lM(n){if(!Bf(n))throw TypeError("Invalid UUID");return parseInt(n.slice(14,15),16)}var dM=he({MAX:()=>hM,NIL:()=>fM,parse:()=>pM,stringify:()=>mM,v1:()=>gM,v4:()=>Ni,v5:()=>jh,v6:()=>SE,v7:()=>js,validate:()=>wa,version:()=>_M});const hM=ZN,fM=KN,pM=Mh,mM=qN,gM=vE,Ni=YN,jh=Cy,SE=oM,js=cM,wa=Bf,_M=lM;var Zp={},yM=he({getEnv:()=>$y,getEnvironmentVariable:()=>Bt,getRuntimeEnvironment:()=>IE,isBrowser:()=>AE,isDeno:()=>Hf,isJsDom:()=>EE,isNode:()=>kE,isWebWorker:()=>TE});const AE=()=>typeof window<"u"&&typeof window.document<"u",TE=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",EE=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Hf=()=>typeof Deno<"u",kE=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Hf(),$y=()=>{let n;return AE()?n="browser":kE()?n="node":TE()?n="webworker":EE()?n="jsdom":Hf()?n="deno":n="other",n};let Kp;function IE(){return Kp===void 0&&(Kp={library:"langchain-js",runtime:$y()}),Kp}function Bt(n){try{return typeof process<"u"?Zp==null?void 0:Zp[n]:Hf()?Deno==null?void 0:Deno.env.get(n):void 0}catch{return}}var wM=he({BaseCallbackHandler:()=>Qs,callbackHandlerPrefersChatModelStreamEvents:()=>xE,callbackHandlerPrefersStreaming:()=>Ry,isBaseCallbackHandler:()=>OE}),bM=class{};function Ry(n){return"lc_prefer_streaming"in n&&n.lc_prefer_streaming}function xE(n){return"lc_prefer_chat_model_stream_events"in n&&n.lc_prefer_chat_model_stream_events}var Qs=class extends bM{constructor(e){super();p(this,"lc_serializable",!1);p(this,"lc_kwargs");p(this,"ignoreLLM",!1);p(this,"ignoreChain",!1);p(this,"ignoreAgent",!1);p(this,"ignoreRetriever",!1);p(this,"ignoreCustomEvent",!1);p(this,"raiseError",!1);p(this,"awaitHandlers",Bt("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,zf(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return kr.prototype.toJSON.call(this)}toJSONNotImplemented(){return kr.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Qs{constructor(){super();p(this,"name",js());Object.assign(this,e)}}return new t}};const OE=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},vM=/^(?:[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 SM(n){return typeof n=="string"&&vM.test(n)}function pv(n){if(!SM(n))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(n.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(n.slice(9,13),16))>>>8,e&255,(e=parseInt(n.slice(14,18),16))>>>8,e&255,(e=parseInt(n.slice(19,23),16))>>>8,e&255,(e=parseInt(n.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const un=[];for(let n=0;n<256;++n)un.push((n+256).toString(16).slice(1));function Py(n,e=0){return(un[n[e+0]]+un[n[e+1]]+un[n[e+2]]+un[n[e+3]]+"-"+un[n[e+4]]+un[n[e+5]]+"-"+un[n[e+6]]+un[n[e+7]]+"-"+un[n[e+8]]+un[n[e+9]]+"-"+un[n[e+10]]+un[n[e+11]]+un[n[e+12]]+un[n[e+13]]+un[n[e+14]]+un[n[e+15]]).toLowerCase()}const AM=new Uint8Array(16);function bg(){return crypto.getRandomValues(AM)}function Rc(n,e,t){return crypto.randomUUID?crypto.randomUUID():TM(n)}function TM(n,e,t){var s;n=n||{};const r=n.random??((s=n.rng)==null?void 0:s.call(n))??bg();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,Py(r)}function EM(n,e,t,r){switch(n){case 0:return e&t^~e&r;case 1:return e^t^r;case 2:return e&t^e&r^t&r;case 3:return e^t^r}}function Wp(n,e){return n<<e|n>>>32-e}function kM(n){const e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(n.length+1);r.set(n),r[n.length]=128,n=r;const s=n.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]=n[o*64+u*4]<<24|n[o*64+u*4+1]<<16|n[o*64+u*4+2]<<8|n[o*64+u*4+3];a[o]=c}a[i-1][14]=(n.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(n.length-1)*8&4294967295;for(let o=0;o<i;++o){const c=new Uint32Array(80);for(let m=0;m<16;++m)c[m]=a[o][m];for(let m=16;m<80;++m)c[m]=Wp(c[m-3]^c[m-8]^c[m-14]^c[m-16],1);let u=t[0],l=t[1],d=t[2],f=t[3],h=t[4];for(let m=0;m<80;++m){const g=Math.floor(m/20),y=Wp(u,5)+EM(g,l,d,f)+h+e[g]+c[m]>>>0;h=f,f=d,d=Wp(l,30)>>>0,l=u,u=y}t[0]=t[0]+u>>>0,t[1]=t[1]+l>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+f>>>0,t[4]=t[4]+h>>>0}return Uint8Array.of(t[0]>>24,t[0]>>16,t[0]>>8,t[0],t[1]>>24,t[1]>>16,t[1]>>8,t[1],t[2]>>24,t[2]>>16,t[2]>>8,t[2],t[3]>>24,t[3]>>16,t[3]>>8,t[3],t[4]>>24,t[4]>>16,t[4]>>8,t[4])}function IM(n){n=unescape(encodeURIComponent(n));const e=new Uint8Array(n.length);for(let t=0;t<n.length;++t)e[t]=n.charCodeAt(t);return e}const xM="6ba7b810-9dad-11d1-80b4-00c04fd430c8",OM="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function CM(n,e,t,r,s,i){const a=typeof t=="string"?IM(t):t,o=typeof r=="string"?pv(r):r;if(typeof r=="string"&&(r=pv(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|n,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 Py(c)}function Ny(n,e,t,r){return CM(80,kM,n,e,t,r)}Ny.DNS=xM;Ny.URL=OM;const qp={};function CE(n,e,t){var s;let r;if(n)r=mv(n.random??((s=n.rng)==null?void 0:s.call(n))??bg(),n.msecs,n.seq,e,t);else{const i=Date.now(),a=bg();$M(qp,i,a),r=mv(a,qp.msecs,qp.seq,e,t)}return e??Py(r)}function $M(n,e,t){return n.msecs??(n.msecs=-1/0),n.seq??(n.seq=0),e>n.msecs?(n.seq=t[6]<<23|t[7]<<16|t[8]<<8|t[9],n.msecs=e):(n.seq=n.seq+1|0,n.seq===0&&n.msecs++),n}function mv(n,e,t,r,s=0){if(n.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()),t??(t=n[6]*127<<24|n[7]<<16|n[8]<<8|n[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|t>>>28&15,r[s++]=t>>>20&255,r[s++]=128|t>>>14&63,r[s++]=t>>>6&255,r[s++]=t<<2&255|n[10]&3,r[s++]=n[11],r[s++]=n[12],r[s++]=n[13],r[s++]=n[14],r[s++]=n[15],r}const RM="gen_ai.operation.name",PM="gen_ai.system",gv="gen_ai.request.model",NM="gen_ai.response.model",_v="gen_ai.usage.input_tokens",yv="gen_ai.usage.output_tokens",wv="gen_ai.usage.total_tokens",MM="gen_ai.request.max_tokens",jM="gen_ai.request.temperature",LM="gen_ai.request.top_p",DM="gen_ai.request.frequency_penalty",UM="gen_ai.request.presence_penalty",zM="gen_ai.response.finish_reasons",FM="gen_ai.prompt",BM="gen_ai.completion",HM="gen_ai.request.extra_query",VM="gen_ai.request.extra_body",ZM="gen_ai.serialized.name",KM="gen_ai.serialized.signature",WM="gen_ai.serialized.doc",qM="gen_ai.response.id",GM="gen_ai.response.service_tier",JM="gen_ai.response.system_fingerprint",YM="gen_ai.usage.input_token_details",XM="gen_ai.usage.output_token_details",QM="langsmith.trace.session_id",e2="langsmith.trace.session_name",t2="langsmith.span.kind",n2="langsmith.trace.name",r2="langsmith.metadata",bv="langsmith.span.tags",s2="langsmith.request.streaming",i2="langsmith.request.headers",vv="langsmith.usage_metadata",a2=(...n)=>fetch(...n),$E=Symbol.for("ls:fetch_implementation"),o2=()=>globalThis[$E]===void 0,c2=n=>async(...e)=>{if(n||Ut("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${(s==null?void 0:s.method)||"GET"} ${r}`)}const t=await(globalThis[$E]??a2)(...e);return(n||Ut("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},RE=()=>Ut("PROJECT")??lr("LANGCHAIN_SESSION")??"default",Sv={};function Qd(n){Sv[n]||(console.warn(n),Sv[n]=!0)}const H=n=>BigInt(n),PE=H("0x9E3779B1"),NE=H("0x85EBCA77"),u2=H("0xC2B2AE3D"),Mi=H("0x9E3779B185EBCA87"),ka=H("0xC2B2AE3D27D4EB4F"),ME=H("0x165667B19E3779F9"),My=H("0x85EBCA77C2B2AE63"),l2=H("0x27D4EB2F165667C5"),d2=H("0x165667919E3779F9"),h2=H("0x9FB21C651E98DF25");function f2(n){const e=new Uint8Array(n.length/2);for(let t=0;t<n.length;t+=2)e[t/2]=parseInt(n.substring(t,t+2),16);return e}const as=f2("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Io=(H(1)<<H(128))-H(1),Be=(H(1)<<H(64))-H(1),Lh=(H(1)<<H(32))-H(1),Ls=64,jE=Ls/8,p2=8,rd=4;function St(n,e=0){return new Uint8Array(n.buffer,n.byteOffset+e,n.length-e)}function kt(n,e=0){return new DataView(n.buffer,n.byteOffset+e).getBigUint64(0,!0)}function go(n,e=0){return new DataView(n.buffer,n.byteOffset+e).getUint32(0,!0)}function Gp(n,e=0){return n[e]}const m2=n=>(n&H(255))<<H(56)|(n&H(65280))<<H(40)|(n&H(16711680))<<H(24)|(n&H(4278190080))<<H(8)|(n&H(0xff00000000))>>H(8)|(n&H(0xff0000000000))>>H(24)|(n&H(0xff000000000000))>>H(40)|(n&H(0xff00000000000000))>>H(56),g2=n=>(n=(n&H(65535))<<H(16)|(n&H(4294901760))>>H(16),n=(n&H(16711935))<<H(8)|(n&H(4278255360))>>H(8),n),_2=(n,e)=>(n&Lh)*(e&Lh)&Be,Jo=n=>{if(!n)throw new Error("Assert failed")};function y2(n,e){return(n<<e|n>>H(32)-e)&Lh}function LE(n,e,t){for(let r=0;r<jE;r++){const s=kt(e,r*8),i=s^kt(t,r*8);n[r^1]+=s,n[r]+=_2(i,i>>H(32))}return n}function Av(n,e,t,r){for(let s=0;s<r;s++)LE(n,St(e,s*Ls),St(t,s*8));return n}function w2(n,e){for(let t=0;t<jE;t++){const r=kt(e,t*8);let s=n[t];s=vg(s,H(47)),s^=r,s*=PE,n[t]=s&Be}return n}function sd(n,e){return DE(n[0]^kt(e,0),n[1]^kt(e,p2))}function Tv(n,e,t){let r=t;return r+=sd(n.slice(0),St(e,0*rd)),r+=sd(n.slice(2),St(e,4*rd)),r+=sd(n.slice(4),St(e,8*rd)),r+=sd(n.slice(6),St(e,12*rd)),ps(r&Be)}function b2(n,e,t,r,s){const i=Math.floor((t.byteLength-Ls)/8),a=Ls*i,o=Math.floor((e.byteLength-1)/a);for(let c=0;c<o;c++)n=Av(n,St(e,c*a),t,i),n=s(n,St(t,t.byteLength-Ls));{const c=Math.floor((e.byteLength-1-a*o)/Ls);n=Av(n,St(e,o*a),t,c),n=r(n,St(e,e.byteLength-Ls),St(t,t.byteLength-Ls-7))}return n}function v2(n,e,t){let r=new BigUint64Array([u2,Mi,ka,ME,My,NE,l2,PE]);Jo(n.length>128),r=b2(r,n,e,LE,w2),Jo(r.length*8==64);{const s=Tv(r,St(e,11),H(n.byteLength)*Mi&Be);return Tv(r,St(e,e.byteLength-Ls-11),~(H(n.byteLength)*ka)&Be)<<H(64)|s}}function DE(n,e){const t=n*e&Io;return t&Be^t>>H(64)}function Ev(n,e,t){return DE((kt(n,0)^kt(e,0)+t)&Be,(kt(n,8)^kt(e,8)-t)&Be)}function eh(n,e,t,r,s){let i=n&Be,a=n>>H(64)&Be;return i+=Ev(e,r,s),i^=kt(t,0)+kt(t,8),i&=Be,a+=Ev(t,St(r,16),s),a^=kt(e,0)+kt(e,8),a&=Be,a<<H(64)|i}function ps(n){return n^=n>>H(37),n*=d2,n&=Be,n^=n>>H(32),n}function Dh(n){return n^=n>>H(33),n*=ka,n&=Be,n^=n>>H(29),n*=ME,n&=Be,n^=n>>H(32),n}function S2(n,e,t){const r=n.byteLength;Jo(r>0&&r<=3);const s=H(Gp(n,r-1))|H(r<<8)|H(Gp(n,0)<<16)|H(Gp(n,r>>1)<<24),i=(H(go(e,0))^H(go(e,4)))+t,a=(s^i)&Be,o=(H(go(e,8))^H(go(e,12)))-t,c=(y2(g2(s),H(13))^o)&Be;return(Dh(c)&Be)<<H(64)|Dh(a)}function vg(n,e){return n^n>>e}function A2(n,e,t){const r=n.byteLength;Jo(r>=4&&r<=8);{const s=go(n,0),i=go(n,r-4),a=H(s)|H(i)<<H(32),o=(kt(e,16)^kt(e,24))+t&Be;let u=(a^o)*(Mi+(H(r)<<H(2)))&Io;return u+=(u&Be)<<H(65),u&=Io,u^=u>>H(67),vg(vg(u&Be,H(35))*h2&Be,H(28))|ps(u>>H(64))<<H(64)}}function T2(n,e,t){const r=n.byteLength;Jo(r>=9&&r<=16);{const s=(kt(e,32)^kt(e,40))+t&Be,i=(kt(e,48)^kt(e,56))-t&Be,a=kt(n);let o=kt(n,r-8),c=(a^o^s)*Mi;const u=(c&Be)+(H(r-1)<<H(54));c=c&(Io^Be)|u,o^=i,c+=o+(o&Lh)*(NE-H(1))<<H(64),c&=Io,c^=m2(c>>H(64));let l=(c&Be)*ka;return l+=(c>>H(64))*ka<<H(64),l&=Io,ps(l&Be)|ps(l>>H(64))<<H(64)}}function E2(n,e){const t=n.byteLength;return Jo(t<=16),t>8?T2(n,as,e):t>=4?A2(n,as,e):t>0?S2(n,as,e):Dh(e^kt(as,64)^kt(as,72))|Dh(e^kt(as,80)^kt(as,88))<<H(64)}function Sg(n){return~n+H(1)&Be}function k2(n,e,t){let r=H(n.byteLength)*Mi&Be,s=H(n.byteLength-1)/H(32);for(;s>=0;){const o=Number(s);r=eh(r,St(n,16*o),St(n,n.byteLength-16*(o+1)),St(e,32*o),t),s--}let i=r+(r>>H(64))&Be;i=ps(i);let a=(r&Be)*Mi+(r>>H(64))*My+(H(n.byteLength)-t&Be)*ka;return a&=Be,a=Sg(ps(a)),i|a<<H(64)}function I2(n,e,t){let r=H(n.byteLength)*Mi&Be;for(let a=32;a<160;a+=32)r=eh(r,St(n,a-32),St(n,a-16),St(e,a-32),t);r=ps(r&Be)|ps(r>>H(64))<<H(64);for(let a=160;a<=n.byteLength;a+=32)r=eh(r,St(n,a-32),St(n,a-16),St(e,3+a-160),t);r=eh(r,St(n,n.byteLength-16),St(n,n.byteLength-32),St(e,103),Sg(t));let s=r+(r>>H(64))&Be;s=ps(s);let i=(r&Be)*Mi+(r>>H(64))*My+(H(n.byteLength)-t&Be)*ka;return i&=Be,i=Sg(ps(i)),s|i<<H(64)}function x2(n,e=H(0)){const t=n.byteLength;return t<=16?E2(n,e):t<=128?k2(n,as,e):t<=240?I2(n,as,e):v2(n,as)}function O2(n){const e=new Uint8Array(16),t=new DataView(e.buffer),r=n&Be,s=n>>H(64);return t.setBigUint64(0,s,!1),t.setBigUint64(8,r,!1),e}const UE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ze(n,e){if(!UE.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}function C2(n){const e=typeof n=="string"?Date.parse(n):n;return CE({msecs:e,seq:0})}function $2(n){if(!UE.test(n))return null;const e=n[14];return parseInt(e,16)}function R2(n){const e=n.replace(/-/g,""),t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function P2(n){const e=Array.from(n).map(t=>t.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 N2=new TextEncoder;function M2(n){const e=N2.encode(n),t=x2(e);return O2(t)}function id(n,e){const t=`${n}:${e}`,r=M2(t),s=new Uint8Array(16);if($2(n)===7){const a=R2(n);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),P2(s)}const Ia={join:(...n)=>n.join("/"),dirname:n=>n.split("/").slice(0,-1).join("/")};async function zE(n){}async function jy(n,e){}async function j2(n){return[]}async function L2(n){return{size:0}}function FE(n){return""}async function D2(n){}async function Ag(n){}function U2(n,e){return e===null?!1:Date.now()-n.createdAt>e*1e3}class z2{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,t){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:t}),this._metrics.hits+=1,r.value}set(e,t,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:t,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 t={};for(const[s,i]of this.cache.entries())t[s]=i.value;Ia.dirname(e);const r=`${e}.tmp`;try{JSON.stringify({entries:t},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[t,r]of this.cache.entries())U2(r,this.ttlSeconds)&&e.push([t,r]);return e}async refreshStaleEntries(){const e=this.getStaleEntries();if(e.length!==0){for(const[t,r]of e)if(r.refreshFunc!==void 0)try{const s=await r.refreshFunc();this.set(t,s,r.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??5*60}}const kv=new z2,BE="0.7.7";var ku={};let ns;const F2=()=>typeof window<"u"&&typeof window.document<"u",B2=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",H2=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),HE=()=>typeof Deno<"u",V2=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!HE(),Ly=()=>ns||(typeof Bun<"u"?ns="bun":F2()?ns="browser":V2()?ns="node":B2()?ns="webworker":H2()?ns="jsdom":HE()?ns="deno":ns="other",ns);let Jp;function VE(){if(Jp===void 0){const n=Ly(),e=K2();Jp={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:BE,...e}}return Jp}function ZE(){const n=Z2(),e={},t=["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(n))typeof s=="string"&&!t.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 Z2(){const n={};try{if(typeof process<"u"&&ku)for(const[e,t]of Object.entries(ku))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?n[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):n[e]=t)}catch{}return n}function lr(n){try{return typeof process<"u"?ku==null?void 0:ku[n]:void 0}catch{return}}function Ut(n){return lr(`LANGSMITH_${n}`)||lr(`LANGCHAIN_${n}`)}let Yp;function K2(){if(Yp!==void 0)return Yp;const n=["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 t of n){const r=lr(t);r!==void 0&&(e[t]=r)}return Yp=e,e}function Iv(){return lr("OTEL_ENABLED")==="true"||Ut("OTEL_ENABLED")==="true"}const xv=new Set(["langsmith","otel"]);function KE(n){if(n!==void 0)return n;const e=Ut("TRACING_MODE");if(e!==void 0&&e!==""){const t=e.toLowerCase();if(!xv.has(t))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...xv].sort().join(", ")}`);return Iv()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),t}return Iv()?"otel":"langsmith"}class W2{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&KE()==="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(t.length===1&&typeof t[0]=="function"?r=t[0]:t.length===2&&typeof t[1]=="function"?r=t[1]:t.length===3&&typeof t[2]=="function"&&(r=t[2]),typeof r=="function")return r()}}class q2{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new W2})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class G2{active(){return{}}with(e,t){return t()}}const Xp=Symbol.for("ls:otel_trace"),Qp=Symbol.for("ls:otel_context"),Ov=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),J2=new q2,Y2=new G2;class X2{getTraceInstance(){return globalThis[Xp]??J2}getContextInstance(){return globalThis[Qp]??Y2}initializeGlobalInstances(e){globalThis[Xp]===void 0&&(globalThis[Xp]=e.trace),globalThis[Qp]===void 0&&(globalThis[Qp]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Ov]=e}getDefaultOTLPTracerComponents(){return globalThis[Ov]??void 0}}const Dy=new X2;function WE(){return Dy.getTraceInstance()}function Q2(){return Dy.getContextInstance()}function ej(){return Dy.getDefaultOTLPTracerComponents()}const tj={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function nj(n){return tj[n]||n}function rj(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"}class sj{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,t.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,t,r){const s=r&&WE().getSpan(r);if(s)try{return this.finishSpanSetup(s,t,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){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,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const s=t.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 t;if((t=e.extra)!=null&&t.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,t,r){var o,c,u;if("run_type"in t&&t.run_type){e.setAttribute(t2,t.run_type);const l=nj(t.run_type||"chain");e.setAttribute(RM,l)}"name"in t&&t.name&&e.setAttribute(n2,t.name),"session_id"in t&&t.session_id&&e.setAttribute(QM,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(e2,t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(gv,s),(c=(o=t.extra)==null?void 0:o.metadata)!=null&&c.usage_metadata&&typeof t.extra.metadata.usage_metadata=="object"&&e.setAttribute(vv,JSON.stringify(t.extra.metadata.usage_metadata)),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(_v,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(yv,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(wv,t.total_tokens),this.setInvocationParameters(e,t);const i=((u=t.extra)==null?void 0:u.metadata)||{};for(const[l,d]of Object.entries(i))d!=null&&e.setAttribute(`${r2}.${l}`,rj(d)?String(d):JSON.stringify(d));const a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(bv,a.join(", ")):a&&e.setAttribute(bv,String(a)),"serialized"in t&&typeof t.serialized=="object"){const l=t.serialized;l.name&&e.setAttribute(ZM,String(l.name)),l.signature&&e.setAttribute(KM,String(l.signature)),l.doc&&e.setAttribute(WM,String(l.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const s=this.extractModelName(t);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(PM,r)}setInvocationParameters(e,t){var s,i;if(!((i=(s=t.extra)==null?void 0:s.metadata)!=null&&i.invocation_params))return;const r=t.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(MM,r.max_tokens),r.temperature!==void 0&&e.setAttribute(jM,r.temperature),r.top_p!==void 0&&e.setAttribute(LM,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(DM,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(UM,r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(gv,r.model),r.stream!==void 0&&e.setAttribute(s2,r.stream),r.extra_headers&&e.setAttribute(i2,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(HM,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(VM,JSON.stringify(r.extra_body))),e.setAttribute(FM,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${t.id}`,r)}if(t.run.outputs)try{const r=t.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(_v,s[0]),e.setAttribute(yv,s[1]),e.setAttribute(wv,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(NM,String(r.model)),r.id&&e.setAttribute(qM,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(zM,i.join(", "))}if(r.service_tier&&e.setAttribute(GM,r.service_tier),r.system_fingerprint&&e.setAttribute(JM,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const i=r.usage_metadata;e.setAttribute(vv,JSON.stringify(i)),i.input_token_details&&e.setAttribute(YM,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(XM,JSON.stringify(i.output_token_details))}}e.setAttribute(BM,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${t.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const a of r){const o=e[a];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}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"&&(t=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const ij=Object.prototype.toString,aj=n=>ij.call(n)==="[object Error]",oj=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 cj(n){if(!(n&&aj(n)&&n.name==="TypeError"&&typeof n.message=="string"))return!1;const{message:t,stack:r}=n;return t==="Load failed"?r===void 0||"__sentry_captured__"in n:t.startsWith("error sending request for url")?!0:oj.has(t)}function uj(n){if(typeof n=="number"){if(n<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(n))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(n!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function ad(n,e,{min:t=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${n}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${n}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${n}\` to be ≥ ${t}.`)}}let lj=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 dj(n,e){const t=Math.max(1,n+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function Cv(n,e){return Number.isFinite(e)?e-(performance.now()-n):e}async function hj({error:n,attemptNumber:e,retriesConsumed:t,startTime:r,options:s}){var h,m,g;const i=n instanceof Error?n:new TypeError(`Non-error was thrown: "${n}". You should only throw errors.`);if(i instanceof lj)throw i.originalError;const a=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:t});if(await s.onFailedAttempt(c),Cv(r,o)<=0)throw i;const u=await s.shouldConsumeRetry(c),l=Cv(r,o);if(l<=0||a<=0)throw i;if(i instanceof TypeError&&!cj(i)){if(u)throw i;return(h=s.signal)==null||h.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!u)return(m=s.signal)==null||m.throwIfAborted(),!1;const d=dj(t,s),f=Math.min(d,l);return f>0&&await new Promise((y,b)=>{var S,T;const _=()=>{var A;clearTimeout(w),(A=s.signal)==null||A.removeEventListener("abort",_),b(s.signal.reason)},w=setTimeout(()=>{var A;(A=s.signal)==null||A.removeEventListener("abort",_),y()},f);s.unref&&((S=w.unref)==null||S.call(w)),(T=s.signal)==null||T.addEventListener("abort",_,{once:!0})}),(g=s.signal)==null||g.throwIfAborted(),!0}async function fj(n,e={}){var i,a,o;if(e={...e},uj(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),ad("factor",e.factor,{min:0,allowInfinity:!1}),ad("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),ad("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),ad("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(i=e.signal)==null||i.throwIfAborted();let t=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){t++;try{(a=e.signal)==null||a.throwIfAborted();const c=await n(t);return(o=e.signal)==null||o.throwIfAborted(),c}catch(c){await hj({error:c,attemptNumber:t,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var qE={},GE={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!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),m=t?t+u:u;return c._events[m]?c._events[m].fn?c._events[m]=[c._events[m],h]:c._events[m].push(h):(c._events[m]=h,c._eventsCount++),c}function 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(t?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=t?t+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,m=new Array(h);f<h;f++)m[f]=d[f].fn;return m},o.prototype.listenerCount=function(u){var l=t?t+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,f,h,m){var g=t?t+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,m),!0}for(w=1,_=new Array(b-1);w<b;w++)_[w-1]=arguments[w];y.fn.apply(y.context,_)}else{var S=y.length,T;for(w=0;w<S;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(T=1,_=new Array(b-1);T<b;T++)_[T-1]=arguments[T];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=t?t+u:u;if(!this._events[h])return this;if(!l)return a(this,h),this;var m=this._events[h];if(m.fn)m.fn===l&&(!f||m.once)&&(!d||m.context===d)&&a(this,h);else{for(var g=0,y=[],b=m.length;g<b;g++)(m[g].fn!==l||f&&!m[g].once||d&&m[g].context!==d)&&y.push(m[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=t?t+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=t,o.EventEmitter=o,n.exports=o})(GE);var pj=GE.exports,Vf={exports:{}},mj=(n,e)=>(e=e||(()=>{}),n.then(t=>new Promise(r=>{r(e())}).then(()=>t),t=>new Promise(r=>{r(e())}).then(()=>{throw t})));const gj=mj;class JE extends Error{constructor(e){super(e),this.name="TimeoutError"}}const YE=(n,e,t)=>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(n);return}const i=setTimeout(()=>{if(typeof t=="function"){try{r(t())}catch(c){s(c)}return}const a=typeof t=="string"?t:`Promise timed out after ${e} milliseconds`,o=t instanceof Error?t:new JE(a);typeof n.cancel=="function"&&n.cancel(),s(o)},e);gj(n.then(r,s),()=>{clearTimeout(i)})});Vf.exports=YE;Vf.exports.default=YE;Vf.exports.TimeoutError=JE;var _j=Vf.exports,Uy={},zy={};Object.defineProperty(zy,"__esModule",{value:!0});function yj(n,e,t){let r=0,s=n.length;for(;s>0;){const i=s/2|0;let a=r+i;t(n[a],e)<=0?(r=++a,s-=i+1):s=i}return r}zy.default=yj;Object.defineProperty(Uy,"__esModule",{value:!0});const wj=zy;class bj{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);const r={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(r);return}const s=wj.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(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this._queue.length}}Uy.default=bj;Object.defineProperty(qE,"__esModule",{value:!0});const vj=pj,XE=_j,Sj=Uy,od=()=>{},Aj=new XE.TimeoutError;let Tj=class extends vj{constructor(e){var t,r,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=od,this._resolveIdle=od,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Sj.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(t=e.intervalCap)===null||t===void 0?void 0:t.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=od,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=od,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(this._intervalId===void 0){const t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return t?(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,s)=>{const i=async()=>{this._pendingCount++,this._intervalCount++;try{const a=this._timeout===void 0&&t.timeout===void 0?e():XE.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&s(Aj)});r(await a)}catch(a){s(a)}this._next()};this._queue.enqueue(i,t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async r=>this.add(r,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};var Hs=qE.default=Tj;const Ej="default"in Hs?Hs.default:Hs,kj=[408,425,429,500,502,503,504];let $v=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 Ej({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...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(()=>fj(()=>t(...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")&&!kj.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 Rv(n){return typeof(n==null?void 0:n._getType)=="function"}function Pv(n){const e={type:n._getType(),data:{content:n.content}};return n!=null&&n.additional_kwargs&&Object.keys(n.additional_kwargs).length>0&&(e.data.additional_kwargs={...n.additional_kwargs}),e}function em(n){return`Invalid prompt identifier format: "${n}". 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 Ij 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 xj 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 tm(n){return n!=null&&typeof n=="object"&&"name"in n&&(n==null?void 0:n.name)==="LangSmithNotFoundError"}function Oj(n){return n!=null&&typeof n=="object"&&"name"in n&&(n==null?void 0:n.name)==="LangSmithConflictError"}async function fe(n,e,t){let r;if(n.ok){t&&(r=await n.text());return}if(n.status===403)try{const a=await n.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(`${n.status} ${n.statusText}`);throw o.status=n==null?void 0:n.status,o}if(r===void 0)try{r=await n.text()}catch{r=""}const s=`Failed to ${e}. Received status [${n.status}]: ${n.statusText}. Message: ${r}`;if(n.status===404)throw new xj(s);if(n.status===409)throw new Ij(s);const i=new Error(s);throw i.status=n.status,i}const QE="ERR_CONFLICTING_ENDPOINTS";class Cj 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:QE}),this.name="ConflictingEndpointsError"}}function $j(n){return typeof n=="object"&&n!==null&&n.code===QE}function Cn(n){if(!n||n.split("/").length>2||n.startsWith("/")||n.endsWith("/")||n.split(":").length>2)throw new Error(em(n));const[e,t]=n.split(":"),r=t||"latest";if(e.includes("/")){const[s,i]=e.split("/",2);if(!s||!i)throw new Error(em(n));return[s,i,r]}else{if(!e)throw new Error(em(n));return["-",e,r]}}const Rj=10,Pj=1e4,ek="created_at";function Nj(n){return new Promise(e=>setTimeout(e,n))}function Mj(n){return typeof n=="object"&&n!==null&&n.code==="EEXIST"}function tk(n){try{return FE(Ia.join(n,ek)).split(`
|
|
22
|
+
`)}catch{return}}function jj(n){const e=tk(n);if(e&&e[0]&&e[0].trim()){const t=Date.parse(e[0].trim());if(!Number.isNaN(t))return t}return void 0}function Lj(n){const e=tk(n);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}async function Dj(n){const e=jj(n);return e===void 0||Date.now()-e<=Pj?!1:(await Ag(),!0)}async function Uj(n,e){const t=`${n}.oauth.lock.lock`;Ia.dirname(t)&&await zE();const s=globalThis.crypto.randomUUID();for(;;){try{await D2(t)}catch(i){if(!Mj(i))throw i;if(!await Dj(t)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await Nj(Math.min(Rj,Math.max(0,e-Date.now())))}continue}try{await jy(Ia.join(t,ek),`${new Date().toISOString()}
|
|
23
|
+
${s}
|
|
24
|
+
`)}catch(i){throw await Ag(),i}break}return{async release(){Lj(t)===s&&await Ag()}}}const Tg="https://api.smith.langchain.com",zj="langsmith-cli",Fj=6e4,Bj=1e4;function Hj(){const n=Ly();return n==="browser"||n==="webworker"}function Vj(){const n=lr("LANGSMITH_CONFIG_FILE");if(n)return n;const e=lr("HOME")??lr("USERPROFILE");if(e)return Ia.join(e,".langsmith","config.json")}function Zj(){Hj()||Vj()}function Nr(n){return n!=null&&n.trim()!==""}function Ei(n){return n==null?void 0:n.trim().replace(/^["']|["']$/g,"")}function Nv(n){const e=n.oauth;if(!(e!=null&&e.refresh_token))return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;const t=Date.parse(e.expires_at);return Number.isNaN(t)?!1:t<=Date.now()+Fj}function Kj(n){let e=n;for(;e.endsWith("/");)e=e.slice(0,-1);const t="/api/v1";return e.endsWith(t)?e.slice(0,-t.length):e}function Wj(n,e){n.oauth??(n.oauth={}),e.access_token&&(n.oauth.access_token=e.access_token),e.refresh_token&&(n.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(n.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}function Mv(n){return n.reason??new Error("The operation was aborted.")}async function qj(n,e){if(!e)return n;if(e.aborted)throw Mv(e);let t;const r=new Promise((s,i)=>{const a=()=>{i(Mv(e))};e.addEventListener("abort",a,{once:!0}),t=()=>{e.removeEventListener("abort",a)}});try{return await Promise.race([n,r])}finally{t==null||t()}}function Gj(){var i,a;const n=Zj(),e=n==null?void 0:n.profile;if(!n||!e)return{};const t=Ei(e.api_key),r=Ei((i=e.oauth)==null?void 0:i.access_token),s=Ei((a=e.oauth)==null?void 0:a.refresh_token);return{apiUrl:e.api_url,apiKey:t,workspaceId:e.workspace_id,oauthAccessToken:r,oauthRefreshToken:s,profileAuth:t||r||s?new Jj(n):void 0}}class Jj{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=Yj(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,t){Nv(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await qj(this.refreshPromise,t));const r=nk(this.state.profile);return this.rememberProfileAuthHeader(r),r}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){var e;try{const t=JSON.parse(FE(this.state.configPath)),r=(e=t.profiles)==null?void 0:e[this.state.profileName];return r?(this.state.config=t,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){var a,o,c;const t=(a=this.state.profile.oauth)==null?void 0:a.refresh_token;if(!t)return;const r=Ei(this.state.profile.api_url)??Tg,s=Date.now()+Bj;let i;try{if(i=await Uj(this.state.configPath,s),this.reloadProfile()&&!Nv(this.state.profile))return;const l=new URLSearchParams({grant_type:"refresh_token",client_id:zj,refresh_token:((o=this.state.profile.oauth)==null?void 0:o.refresh_token)??t}),d=await e(`${Kj(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;Wj(this.state.profile,f),(c=this.state.config).profiles??(c.profiles={}),this.state.config.profiles[this.state.profileName]=this.state.profile,await jy(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 Yj(n){var t,r;const e=Ei((t=n.oauth)==null?void 0:t.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!Ei((r=n.oauth)==null?void 0:r.refresh_token))return nk(n)}function nk(n){var r;const e=Ei((r=n.oauth)==null?void 0:r.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};const t=Ei(n.api_key);if(t)return{name:"x-api-key",value:t}}var jv="[...]",Xj={result:"[Circular]"},Uh=[],_o=[];const Qj=new TextEncoder;function eL(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function cd(n){return Qj.encode(n)}function rk(n){if(n&&typeof n=="object"&&n!==null){if(n instanceof Map)return Object.fromEntries(n);if(n instanceof Set)return Array.from(n);if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message}}else if(typeof n=="bigint")return n.toString();return n}function tL(n){return function(e,t){return rk(t)}}function nL(n){try{let s=function(l){const d=r(l);return d>t&&(t=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 m=f.name??"",g=f.message??"";return 22+r(m)+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 m=f.length??0,y=f instanceof Float32Array||f instanceof Float64Array?30:12;return 2+m*y}if(f instanceof ArrayBuffer)return 2;if(e.has(f))return 24;if(typeof f.toJSON=="function"){let m;try{m=f.toJSON("")}catch{return 16}e.add(f);const g=c(m);return e.delete(f),g}e.add(f);let h;if(Array.isArray(f)){h=2;const m=f.length;for(let g=0;g<m;g++)h+=o(f[g]),g<m-1&&(h+=1)}else if(f instanceof Map){h=2;let m=0;for(const[g,y]of f){if(a(y))continue;m>0&&(h+=1);const b=typeof g=="string"?g:String(g);h+=r(b)+3,h+=c(y),m++}}else if(f instanceof Set){h=2;let m=0;for(const g of f)m>0&&(h+=1),h+=o(g),m++}else{h=2;let m=0;const g=Object.keys(f);for(let y=0;y<g.length;y++){const b=g[y],_=f[b];a(_)||(m>0&&(h+=1),h+=r(b)+3,h+=c(_),m++)}}return e.delete(f),h};const e=new Set;let t=0;const r=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?l=>Buffer.byteLength(l,"utf8"):l=>l.length;return{size:c(n),maxStringLen:t}}catch{return{size:$n(n).length,maxStringLen:0}}}function $n(n,e,t,r,s){var i;try{const a=JSON.stringify(n,tL(t),r);return cd(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}`:""}`),cd("[Unserializable]");Ut("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=eL()),Eg(n,"",0,[],void 0,0,s);let o;try{_o.length===0?o=JSON.stringify(n,t,r):o=JSON.stringify(n,rL(t),r)}catch{return cd("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Uh.length!==0;){const c=Uh.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return cd(o)}}function nm(n,e,t,r){var s=Object.getOwnPropertyDescriptor(r,t);s.get!==void 0?s.configurable?(Object.defineProperty(r,t,{value:n}),Uh.push([r,t,e,s])):_o.push([e,t,n]):(r[t]=n,Uh.push([r,t,e]))}function Eg(n,e,t,r,s,i,a){i+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){nm(Xj,n,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){nm(jv,n,e,s);return}if(typeof a.edgesLimit<"u"&&t+1>a.edgesLimit){nm(jv,n,e,s);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)Eg(n[o],o,o,r,n,i,a);else{n=rk(n);var c=Object.keys(n);for(o=0;o<c.length;o++){var u=c[o];Eg(n[u],u,o,r,n,i,a)}}r.pop()}}function rL(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(_o.length>0)for(var r=0;r<_o.length;r++){var s=_o[r];if(s[1]===e&&s[0]===t){t=s[2],_o.splice(r,1);break}}return n.call(this,e,t)}}class sL{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 rm=null;function iL(){return rm===null&&(rm=new sL),rm}const aL=64*1024,oL=2048;function cL(n,e=aL,t=oL){if(n===null||typeof n!="object")return typeof n=="string"&&n.length>=e;const r=[n],s=new Set;let i=0;for(;r.length>0;){if(i++>=t)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 uL(n,e){const[t]=Cn(n);if(t!=="-"&&!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 Lv(n){return typeof n=="string"&&n.length>0&&!n.includes("Z")&&!n.includes("+")&&!n.includes("-",10)?n+"Z":n}function Fa(n){return{...n,start_time:Lv(n.start_time),end_time:Lv(n.end_time)}}function Dv(n,e,t){if(t)return n;const r=VE(),s=e??ZE(),i=n.extra??{},a=i.metadata;return n.extra={...i,runtime:{...r,...i==null?void 0:i.runtime},metadata:{...s,...s.revision_id||"revision_id"in n&&n.revision_id?{revision_id:("revision_id"in n?n.revision_id:void 0)??s.revision_id}:{},...a}},n}const lL=n=>{const e=(n==null?void 0:n.toString())??Ut("TRACING_SAMPLING_RATE");if(e===void 0)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},dL=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function hL(n){const e=[];for await(const t of n)e.push(t);return e}function ud(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const fL=async n=>{if((n==null?void 0:n.status)===429){const e=parseInt(n.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function Uv(n){return typeof n=="number"?Number(n.toFixed(4)):n}const pL=24*1024*1024,sk=1024*1024*1024,mL=1e4,gL=100;class _L{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??sk}peek(){return this.items[0]}push(e){let t;const r=new Promise(i=>{t=i}),s=nL(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.`),t(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:s}),this.sizeBytes+=s,r)}pop({upToSizeBytes:e,upToSize:t}){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<t;){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 ds{get tracingMode(){return this._tracingMode}get _fetch(){const e=this.fetchImplementation||c2(this.debug);return async(t,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(t,this.applyCurrentAuthHeaders(r,s,i))}}getProfileManagedAuthorizationHeader(e){if(!(e!=null&&e.headers)||!this.profileAuth)return;const t=new Headers(e.headers).get("Authorization");if(Nr(t))return this.profileAuth.isProfileAuthorizationHeader(t??"")?t??void 0:void 0}isProfileManagedAuthorizationHeader(e,t){var r;return e===t||((r=this.profileAuth)==null?void 0:r.isProfileAuthorizationHeader(e))===!0}hasExplicitAuthHeader(e,t){if(!(e!=null&&e.headers))return!1;const r=new Headers(e.headers);if(Nr(r.get("x-api-key")))return!0;const s=r.get("Authorization");return Nr(s)?!this.isProfileManagedAuthorizationHeader(s??"",t):!1}applyCurrentAuthHeaders(e,t,r){if(!t)return e;const s=d=>{if(this.apiKey!==void 0&&t.name==="x-api-key")return d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",t.value),d;if(t.name==="Authorization"){if(Nr(d.get("x-api-key")))return d;const h=d.get("Authorization");return Nr(h)&&!this.isProfileManagedAuthorizationHeader(h??"",r)||d.set("Authorization",t.value),d}const f=d.get("Authorization");return Nr(f)&&!this.isProfileManagedAuthorizationHeader(f??"",r)||(Nr(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",t.value)),d};if(!e)return{headers:{[t.name]:t.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=Nr(o("x-api-key")),u=o("authorization"),l=Nr(u)&&!this.isProfileManagedAuthorizationHeader(u??"",r);if(this.apiKey!==void 0&&t.name==="x-api-key"){const d=a("authorization");return d&&delete i[d],c||(i["x-api-key"]=t.value),{...e,headers:i}}if(t.name==="Authorization"){if(!c&&!l){const d=a("authorization");d&&d!=="Authorization"&&delete i[d],i.Authorization=t.value}return{...e,headers:i}}if(!l){const d=a("authorization");d&&delete i[d],c||(i["x-api-key"]=t.value)}return{...e,headers:i}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,t){if(this.manualFlushMode||!cL(e)||(this._serializeWorker===void 0&&(this._serializeWorker=iL()),this._serializeWorker===null))return $n(e,t);try{const r=await this._serializeWorker.serialize(e);return r===null?(this._serializeWorker=null,$n(e,t)):r}catch{return $n(e,t)}}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:lr("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:Ut("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:Ut("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:lr("LANGSMITH_DEBUG")==="true"});const t=ds.getDefaultClientConfig();this.tracingSampleRate=lL(e.tracingSamplingRate),this.apiUrl=ud(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));const r=ud(e.apiKey??t.apiKey);if(this.apiKey=Nr(r)?r:void 0,this.profileAuth=this.apiKey!==void 0?void 0:t.profileAuth,this.webUrl=ud(e.webUrl??t.webUrl),(a=this.webUrl)!=null&&a.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=ud(e.workspaceId??t.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new $v({...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=Ut("FAILED_TRACES_DIR")||void 0;const s=Ut("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??sk;this.batchIngestCaller=new $v({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:i,...e.callerOptions??{},onFailedResponseHook:fL,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.hideMetadata=e.hideMetadata??t.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new _L(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=KE(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new sj),this.cachedLSEnvVarsForMetadata=ZE(),e.cache!==void 0&&e.disablePromptCache&&Qd("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?(Qd("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=kv:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=kv),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){const e=Gj(),t=Ut("API_KEY"),r=Ut("ENDPOINT"),s=Ut("WORKSPACE_ID"),i=Nr(t),a=r??e.apiUrl??Tg,o=s??e.workspaceId,c=Ut("HIDE_INPUTS")==="true",u=Ut("HIDE_OUTPUTS")==="true",l=Ut("HIDE_METADATA")==="true";return{apiUrl:a,apiKey:t,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:dL(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 t;const e={"User-Agent":`langsmith-js/${BE}`,...this._customHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{const r=(t=this.profileAuth)==null?void 0:t.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(t=>{if(t.name==="new_token"){const{kwargs:r,...s}=t;return s}return t})}async prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t.extra!=null&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events!==void 0&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){const r=(t==null?void 0:t.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 fe(a,`fetch ${e}`),a})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let s=Number(t.get("offset"))||0;const i=Number(t.get("limit"))||100;for(;;){t.set("offset",String(s)),t.set("limit",String(i));const a=`${this.apiUrl}${e}?${t}`,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 fe(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,t=null,r="POST",s="runs"){const i=t?{...t}:{};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 fe(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,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){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 t;const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??((t=e==null?void 0:e.batch_ingest_config)==null?void 0:t.size_limit_bytes)??pL}async _getBatchSizeLimit(){var t;const e=await this._ensureServerInfo();return this.batchSizeLimit??((t=e==null?void 0:e.batch_ingest_config)==null?void 0:t.size_limit)??gL}async _getDatasetExamplesMultiPartSupport(){var t;return((t=(await this._ensureServerInfo()).instance_flags)==null?void 0:t.dataset_examples_multipart_enabled)??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!s.length){i();break}const a=s.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,f=l.apiKey??this.apiKey,m=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${f}`;return u[m]||(u[m]=[]),u[m].push(l),u},{}),o=[];for(const[u,l]of Object.entries(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,t,r,s,i){try{const a=typeof t=="string"?Buffer.from(t,"utf8"):Buffer.from(t),o=JSON.stringify({version:1,endpoint:s,headers:r,body_base64:a.toString("base64")}),c=`trace_${Date.now()}_${Rc().slice(0,8)}.json`,u=Ia.join(e,c);if(ds._fallbackDirsCreated.has(e)||(await zE(e),ds._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{const d=(await j2(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json"));let f=0;for(const h of d){const{size:m}=await L2(Ia.join(e,h));f+=m}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 jy(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,t){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,{...t,useGzip:u,sizeBytes:r})}catch(l){if(tm(l))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...t,sizeBytes:r});else throw l}}else await this.batchIngestRuns(a,{...t,sizeBytes:r})}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(t.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,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Dv(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;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)),t}async _getServerInfo(){const t=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(mL),...this.fetchOptions});return await fe(r,"get server info"),r})).json();return this.debug&&console.log(`
|
|
28
|
+
=== LangSmith Server Configuration ===
|
|
29
|
+
`+JSON.stringify(t,null,2)+`
|
|
30
|
+
`),t}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(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=WE(),t=Q2();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){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:t==null?void 0:t.apiKey,apiUrl:t==null?void 0:t.apiUrl}).catch(console.error);return}const a=Dv(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);(t==null?void 0:t.apiKey)!==void 0&&(r["x-api-key"]=t.apiKey),(t==null?void 0:t.workspaceId)!==void 0&&(r["x-tenant-id"]=t.workspaceId);const o=$n(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${(t==null?void 0:t.apiUrl)??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await fe(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;let s=await Promise.all((e==null?void 0:e.map(c=>this.prepareRunCreateOrUpdateInputs(c)))??[]),i=await Promise.all((t==null?void 0:t.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,t){const r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};(t==null?void 0:t.apiKey)!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t==null?void 0:t.sizeBytes},async()=>{const s=await this._fetch(`${(t==null?void 0:t.apiUrl)??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await fe(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===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 t??[])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,m)=>(m.id&&(h[m.id]=m),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:m,outputs:g,events:y,extra:b,error:_,serialized:w,attachments:S,...T}=h,A={inputs:m,outputs:g,events:y,extra:b,error:_,serialized:w},I=await this._serializeBody(T,`Serializing for multipart ingestion of run with id: ${T.id}`);l.push({name:`${d}.${T.id}`,payload:new Blob([I],{type:`application/json; length=${I.length}`})});for(const[k,R]of Object.entries(A)){if(R===void 0)continue;const x=await this._serializeBody(R,`Serializing ${k} for multipart ingestion of run with id: ${T.id}`);l.push({name:`${d}.${T.id}.${k}`,payload:new Blob([x],{type:`application/json; length=${x.length}`})})}if(T.id!==void 0){const k=s[T.id];if(k){delete s[T.id];for(const[R,x]of Object.entries(k)){let O,U;if(Array.isArray(x)?[O,U]=x:(O=x.mimeType,U=x.data),R.includes(".")){console.warn(`Skipping attachment '${R}' for run ${T.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${T.id}.${R}`,payload:new Blob([U],{type:`${O}; length=${U.byteLength}`})})}}}u.push(`trace=${T.trace_id},id=${T.id}`)}await this._sendMultipartRequest(l,u.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const a of e)r.push(new Blob([`--${t}\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([`--${t}--\r
|
|
36
|
+
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,t){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(`--${t}\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(`--${t}--\r
|
|
42
|
+
`),i.close()}})}async _sendMultipartRequest(e,t,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 fe(f,"Failed to send multipart request",!0),f});try{let c,u=!1;o2()&&!this.multipartStreamingDisabled&&Ly()!=="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)!==Tg&&(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 "${t}".`),this.multipartStreamingDisabled=!0,c=await o(i))}catch(c){if(tm(c))throw c;if(console.warn(`${c.message.trim()}
|
|
43
|
+
|
|
44
|
+
Context: ${t}`),this.failedTracesDir){const u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await ds._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,t,r){ze(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t.extra!=null&&"metadata"in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events&&(t.events=this._filterNewTokenEvents(t.events));const s={...t,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(t.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=$n(t,`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 fe(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){ze(e);let r=Fa(await this._get(`/runs/${e}`));return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(t!==void 0){let s;t.session_id?s=t.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:Ut("PROJECT")||"default"})).id;const i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${s}/r/${t.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 t=await hL(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};t.sort((a,o)=>((a==null?void 0:a.dotted_order)??"").localeCompare((o==null?void 0:o.dotted_order)??""));for(const a of t){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:t,projectName:r,parentRunId:s,traceId:i,referenceExampleId:a,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:f,query:h,filter:m,traceFilter:g,treeFilter:y,limit:b,select:_,order:w}=e;let S=[];if(t&&(S=Array.isArray(t)?t:[t]),r){const k=Array.isArray(r)?r:[r],R=await Promise.all(k.map(x=>this.readProject({projectName:x}).then(O=>O.id)));S.push(...R)}const T=["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"],A={session:S.length?S:null,run_type:l,reference_example:a,query:h,filter:m,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:_||T,is_root:u,order:w};A.select.includes("child_run_ids")&&Qd("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let I=0;for await(const k of this._getCursorPaginatedList("/runs/query",A)){const R=k.map(Fa);if(b){if(I>=b)break;if(R.length+I>b){yield*R.slice(0,b-I);break}I+=R.length,yield*R}else yield*R}}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:s,filter:i,startTime:a,endTime:o,limit:c,offset:u}=e,d={session_id:t||(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",m=`${this.apiUrl}${h}`;for(;;){const g={...d,offset:f},y=Object.fromEntries(Object.entries(g).filter(([A,I])=>I!==void 0)),b=JSON.stringify(y),w=await(await this.caller.call(async()=>{const A=await this._fetch(m,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await fe(A,`Failed to fetch ${h}`),A})).json(),{groups:S,total:T}=w;if(S.length===0)break;for(const A of S)yield A;if(f+=S.length,f>=T)break}}async*readThread(e){const{threadId:t,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(t)})`,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:t,projectName:r,limit:s,offset:i=0,filter:a,startTime:o,isRoot:c=!0}=e;if(!t&&!r)throw new Error("Either projectId or projectName must be provided");if(t&&r)throw new Error("Provide exactly one of projectId or projectName");const u=t??(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=Fa(_),S=w.thread_id;if(S){const T=h.get(S)??[];T.push(w),h.set(S,T)}}const m=[];for(const[b,_]of h.entries()){_.sort((I,k)=>{const R=I,x=k,O=R.start_time??"",U=x.start_time??"";if(O!==U)return O.localeCompare(U);const B=R.dotted_order??"",F=x.dotted_order??"";return B.localeCompare(F)});const S=[..._.map(I=>I.start_time).filter(Boolean)].sort(),T=S.length?S[0]:"",A=S.length?S[S.length-1]:"";m.push({thread_id:b,runs:_,count:_.length,filter:"",total_tokens:0,total_cost:null,min_start_time:T,max_start_time:A,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}m.sort((b,_)=>{const w=b.max_start_time??"";return(_.max_start_time??"").localeCompare(w)});const g=i>0?m.slice(i):m;return s!==void 0?g.slice(0,s):g}async getRunStats({id:e,trace:t,parentRun:r,runType:s,projectNames:i,projectIds:a,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:f,traceFilter:h,treeFilter:m,isRoot:g,dataSourceType:y}){let b=a||[];i&&(b=[...a||[],...await Promise.all(i.map(I=>this.readProject({projectName:I}).then(k=>k.id)))]);const w=Object.fromEntries(Object.entries({id:e,trace:t,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:m,is_root:g,data_source_type:y}).filter(([I,k])=>k!==void 0)),S=JSON.stringify(w);return await(await this.caller.call(async()=>{const I=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await fe(I,"get run stats"),I})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||Rc()};ze(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 fe(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){ze(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(t,"unshare run",!0),t})}async readRunSharedLink(e){ze(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 fe(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:t}={}){const r=new URLSearchParams({share_token:e});if(t!==void 0)for(const a of t)r.append("id",a);return ze(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 fe(a,"list shared runs"),a})).json()).map(Fa)}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),ze(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 fe(i,"read dataset shared schema"),i})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const r={dataset_id:e};ze(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 fe(o,"share dataset"),o})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){ze(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(t,"unshare dataset",!0),t})}async readSharedDataset(e){return ze(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 fe(s,"read shared dataset"),s})).json()}async listSharedExamples(e,t){const r={};t!=null&&t.exampleIds&&(r.id=t.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 fe(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:t=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:t};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 m=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:m});return await fe(b,"create project"),b})).json()}async updateProject(e,{name:t=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:t,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 fe(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)ze(e),r+=`/${e}`;else if(t!==void 0)s.append("name",t);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 fe(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:t,includeStats:r}){let s="/sessions";const i=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)ze(e),s+=`/${e}`;else if(t!==void 0)i.append("name",t);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=${t}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),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 t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,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(t!==void 0&&l.append("name",t),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:t}){let r;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:t})).id:r=e,ze(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 fe(s,`delete session ${r} (${t})`,!0),s})}async uploadCsv({csvFile:e,fileName:t,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,t),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 fe(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:r,inputsSchema:s,outputsSchema:i,metadata:a}={}){const o={name:e,description:t,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 fe(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)ze(e),r+=`/${e}`;else if(t)s.append("name",t);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=${t}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:s}){let i=e;if(i===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:t})).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:t}){const r="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).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:t=0,datasetIds:r,datasetName:s,datasetNameContains:i,metadata:a}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:t.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:t,datasetName:r,...s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;ze(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 fe(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:s,tag:i}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;ze(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 fe(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",s=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(s=(await this.readDataset({datasetName:t})).id),s!==void 0)ze(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 fe(i,`delete ${r}`,!0),i})}async createExample(e,t,r){var l;if(zv(e)&&(t!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?r==null?void 0:r.datasetId:e.dataset_id;const i=t?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=(t?r==null?void 0:r.createdAt:e.created_at)||new Date;let o;zv(e)?o=e:o={inputs:e,outputs:t,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])??Rc())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const _=e;let w=_[0].dataset_id;const S=_[0].dataset_name;if(w===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(w!==void 0&&S!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");w===void 0&&(w=(await this.readDataset({datasetName:S})).id);const T=await this._uploadExamplesMultipart(w,_);return await Promise.all(T.example_ids.map(I=>this.readExample(I)))}const{inputs:t,outputs:r,metadata:s,splits:i,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:f}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const m=f;if(h===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:m})).id);const g=t.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,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const s=e.map(a=>Rv(a)?Pv(a):a),i=Rv(t)?Pv(t):t;return this.createExample({input:s},{output:i},r)}async readExample(e){ze(e);const t=`/examples/${e}`,r=await this._get(t),{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:t,exampleIds:r,asOf:s,splits:i,inlineS3Urls:a,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let f;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(t!==void 0)f=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),m=s?typeof s=="string"?s:s==null?void 0:s.toISOString():void 0;m&&h.append("as_of",m);const 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,...S}=_,T=S;w&&(T.attachments=Object.entries(w).reduce((A,[I,k])=>(A[I.slice(11)]={presigned_url:k.presigned_url,mime_type:k.mime_type||void 0},A),{})),yield T,y++}if(c!==void 0&&y>=c)break}}async deleteExample(e){ze(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(r,`delete ${t}`,!0),r})}async deleteExamples(e,t){if(e.forEach(r=>ze(r)),t!=null&&t.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 fe(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 fe(s,"delete examples",!0),s})}}async updateExample(e,t){let r;t?r=e:r=e.id,ze(r);let s;t?s={id:r,...t}: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 t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:s}){let i;if(e?i=e:i=(await this.readDataset({datasetName:t})).id,ze(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 fe(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let s;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:t})).id:s=e,ze(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:t,splitName:r,exampleIds:s,remove:i=!1}){let a;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:t})).id:a=e,ze(a);const o={split_name:r,examples:s.map(u=>(ze(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 fe(u,"update dataset splits",!0),u})}async createFeedback(e,t,{score:r,value:s,correction:i,comment:a,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:f,comparativeExperimentId:h,sessionId:m,startTime:g}){var S;if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const y={type:c??"api",metadata:o??{}};u!==void 0&&(y==null?void 0:y.metadata)!==void 0&&!y.metadata.__run&&(y.metadata.__run={run_id:u}),(y==null?void 0:y.metadata)!==void 0&&((S=y.metadata.__run)==null?void 0:S.run_id)!==void 0&&ze(y.metadata.__run.run_id);const b={id:l??CE(),run_id:e,key:t,score:Uv(r),value:s,correction:i,comment:a,feedback_source:y,comparative_experiment_id:h,feedbackConfig:d,session_id:m??f,start_time:g},_=JSON.stringify(b),w=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const T=await this._fetch(w,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await fe(T,"create feedback",!0),T}),b}async updateFeedback(e,{score:t,value:r,correction:s,comment:i}){const a={};t!=null&&(a.score=Uv(t)),r!=null&&(a.value=r),s!=null&&(a.correction=s),i!=null&&(a.comment=i),ze(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 fe(c,"update feedback",!0),c})}async readFeedback(e){ze(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){ze(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(r,`delete ${t}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const i of e)ze(i),s.append("run",i);if(t)for(const i of t)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,t,{expiration:r,feedbackConfig:s}={}){const i={run_id:e,feedback_key:t,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 fe(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:s,description:i,metadata:a,id:o}){var d;if(t.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:t,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 fe(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){ze(e);const t=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",t))yield*r}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,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:t&&(c=t.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:t==null?void 0:t.session_id,startTime:t==null?void 0:t.start_time}))}return[s,i]}async logEvaluationFeedback(e,t,r){const[s]=await this._logEvaluationFeedback(e,t,r);return s}async createFeedbackConfig(e){const{feedbackKey:t,feedbackConfig:r,isLowerScoreBetter:s=!1}=e,i={feedback_key:t,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 fe(o,"create feedback config"),o})).json()}async*listFeedbackConfigs(e={}){const{feedbackKeys:t,nameContains:r,limit:s}=e,i=new URLSearchParams;t&&t.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,t={}){const{feedbackConfig:r,isLowerScoreBetter:s}=t,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 fe(o,"update feedback config"),o})).json()}async deleteFeedbackConfig(e){const t=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/feedback-configs?${t}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(r,"delete feedback config",!0),r})}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:s,limit:i}=e,a=new URLSearchParams;t&&t.forEach((c,u)=>{ze(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:t,description:r,queueId:s,rubricInstructions:i,rubricItems:a}=e,o={name:t,description:r,id:s||Rc(),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 fe(l,"create annotation queue"),l})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${ze(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,t){const{name:r,description:s,rubricInstructions:i,rubricItems:a}=t,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/${ze(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await fe(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${ze(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((s,i)=>ze(s,`runIds[${i}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${ze(e,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await fe(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${ze(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(a,"get run from annotation queue"),a})).json();return Fa(i)}async*listRunsFromAnnotationQueue(e,t={}){const{status:r,limit:s}=t,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/${ze(e,"queueId")}/runs`;for await(const u of this._getPaginated(c,i))for(const l of u)if(yield Fa(l),o++,o>=a)return}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${ze(e,"queueId")}/runs/${ze(t,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(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/${ze(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
49
|
+
|
|
50
|
+
Current tenant: ${r.tenant_handle}
|
|
51
|
+
|
|
52
|
+
Requested tenant: ${t}`)}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 fe(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _createCommitTags(e,t,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:t})});return await fe(a,"create commit tag"),a})))}async _likeOrUnlikePrompt(e,t){const[r,s,i]=Cn(e),a=JSON.stringify({like:t});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 fe(c,`${t?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[t,r,s]=Cn(e);if(await this._currentTenantIsOwner(t)){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/${t}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${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[t,r,s]=Cn(e);for await(const i of this._getPaginated(`/commits/${t}/${r}/`,new URLSearchParams,a=>a.commits))yield*i}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&t.append("is_public",e.isPublic.toString()),e!=null&&e.query&&t.append("query",e.query);for await(const r of this._getPaginated("/repos",t,s=>s.repos))yield*r}async getPrompt(e){const[t,r,s]=Cn(e),i=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return(o==null?void 0:o.status)===404?null:(await fe(o,"get prompt"),o)}),a=await(i==null?void 0:i.json());return a!=null&&a.repo?a.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t!=null&&t.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]=Cn(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:i,...(t==null?void 0:t.description)&&{description:t.description},...(t==null?void 0:t.readme)&&{readme:t.readme},...(t==null?void 0:t.tags)&&{tags:t.tags},is_public:!!(t!=null&&t.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 fe(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,i,a]=Cn(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(t)),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 fe(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,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){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 t){const c=o.id,u={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},l=$n(u,`Serializing body for example with id: ${c}`),d=new Blob([l],{type:"application/json"});if(r.append(c,d),o.inputs){const f=$n(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=$n(o.outputs,`Serializing outputs whle updating example with id: ${c}`),h=new Blob([f],{type:"application/json"});r.append(`${c}.outputs`,h)}if(o.attachments)for(const[f,h]of Object.entries(o.attachments)){let m,g;Array.isArray(h)?[m,g]=h:(m=h.mimeType,g=h.data);const y=new Blob([g],{type:`${m}; length=${g.byteLength}`});r.append(`${c}.attachment.${f}`,y)}if(o.attachments_operations){const f=$n(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=t[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 fe(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){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 t){const a=(i.id??Rc()).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=$n(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=$n(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=$n(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 m=new Blob([h],{type:`${f}; length=${h.byteLength}`});r.append(`${a}.attachment.${l}`,m)}}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 fe(i,"upload examples"),i})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=Cn(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const i={};if((t==null?void 0:t.description)!==void 0&&(i.description=t.description),(t==null?void 0:t.readme)!==void 0&&(i.readme=t.readme),(t==null?void 0:t.tags)!==void 0&&(i.tags=t.tags),(t==null?void 0:t.isPublic)!==void 0&&(i.is_public=t.isPublic),(t==null?void 0:t.isArchived)!==void 0&&(i.is_archived=t.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 fe(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[t,r,s]=Cn(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,t){return`${e}${t?":with_model":""}`}async _fetchPromptFromApi(e,t){const[r,s,i]=Cn(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${i}${t!=null&&t.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(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,t){uL(e,t==null?void 0:t.dangerouslyPullPublicPrompt);const r=this._fetchPromptFromApi.bind(this,e,t);if(!(t!=null&&t.skipCache)&&this._promptCache){const s=this._getPromptCacheKey(e,t==null?void 0:t.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,t)}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t==null?void 0:t.includeModel,skipCache:t==null?void 0:t.skipCache,dangerouslyPullPublicPrompt:t==null?void 0:t.dangerouslyPullPublicPrompt});return JSON.stringify(r.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&["description","readme","tags","isPublic"].some(s=>t[s]!==void 0)&&await this.updatePrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}):await this.createPrompt(e,{description:t==null?void 0:t.description,readme:t==null?void 0:t.readme,tags:t==null?void 0:t.tags,isPublic:t==null?void 0:t.isPublic}),t!=null&&t.object?await this.createCommit(e,t==null?void 0:t.object,{parentCommitHash:t==null?void 0:t.parentCommitHash,tags:t==null?void 0:t.commitTags,description:t==null?void 0:t.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){const[t,r]=Cn(e);return this._repoExists(t,r)}async skillExists(e){const[t,r]=Cn(e);return this._repoExists(t,r)}async pullAgent(e,t){return await this._pullDirectory(e,"agent",t==null?void 0:t.version)}async pullSkill(e,t){return await this._pullDirectory(e,"skill",t==null?void 0:t.version)}async pushAgent(e,t){return this._pushDirectory(e,"agent",t)}async pushSkill(e,t){return this._pushDirectory(e,"skill",t)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,t){const r=new URLSearchParams;r.append("repo_type",e),r.append("is_archived",(!!(t!=null&&t.isArchived)).toString()),(t==null?void 0:t.isPublic)!==void 0&&r.append("is_public",t.isPublic.toString()),t!=null&&t.query&&r.append("query",t.query);for await(const s of this._getPaginated("/repos",r,i=>i.repos))yield*s}async _pullDirectory(e,t,r){const[s,i,a]=Cn(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",t),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 fe(l,"pull directory"),l})).json()}async _pushDirectory(e,t,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]=Cn(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError(`push ${t}`,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,t,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 fe(f,`push ${t}`),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[t,r]=Cn(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete",t);await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${t}/${r}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(s,"delete directory"),s})}async _repoExists(e,t){try{return await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await fe(r,"check repo exists"),r}),!0}catch(r){if(tm(r))return!1;throw r}}async _createRepo(e,t,r){const s={repo_handle:e,repo_type:t,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 fe(i,`create ${t}`),i})}catch(i){if(Oj(i))return;throw i}}async _updateRepoMetadata(e,t,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}/${t}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await fe(i,"update repo metadata"),i})}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=t,[i,a]=this.parseTokenOrUrl(e,r),o=new ds({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,t,r=2,s="dataset"){try{return ze(e),[t,e]}catch{}try{const a=new URL(e).pathname.split("/").filter(o=>o!=="");if(a.length>=r){const o=a[a.length-r];return[t,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,t;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((t=(e=ej())==null?void 0:e.DEFAULT_LANGSMITH_SPAN_PROCESSOR)==null?void 0:t.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(ds,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function zv(n){return"dataset_id"in n||"dataset_name"in n}const yL=n=>!!["TRACING_V2","TRACING"].find(t=>Ut(t)==="true"),ki=Symbol.for("lc:context_variables"),sm=Symbol.for("langsmith:replica_trace_roots");function Fv(n,e){if(ki in n)return n[ki][e]}function wL(n,e,t){const r=ki in n?n[ki]:{};r[e]=t,n[ki]=r}const bL="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Bv(n){const t=Object.keys(n).sort().map(r=>`${r}:${n[r]??""}`).join("|");return Ny(t,bL)}function vL(n){return n.replace(/[-:.]/g,"")}function ik(n,e=1){const t=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(n).toISOString().slice(0,-1)}${t}Z`}function ak(n,e,t=1){const r=ik(n,t);return{dottedOrder:vL(r)+e,microsecondPrecisionDatestring:r}}const SL=new Set(["projectName","updates","reroot"]);function AL(n){const e={};for(const t of Object.keys(n))SL.has(t)&&(e[t]=n[t]);return e}class zh{constructor(e,t,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=t,this.project_name=r,this.replicas=s}static fromHeader(e){const t=e.split(",");let r={},s=[],i,a;for(const o of t){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:AL(f)))}return new zh(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 Hn{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}),TL(e)){Object.assign(this,{...e});return}const t=Hn.getDefaultConfig(),{metadata:r,...s}=e,i=s.client??Hn.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,{...t,...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=ik(this.start_time,this.execution_order)),this.id||(this.id=C2(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=xL(this.replicas),!this.dotted_order){const{dottedOrder:c}=ak(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 t;this.extra={...this.extra,metadata:{...(t=this.extra)==null?void 0:t.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:RE(),child_runs:[],api_url:lr("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:lr("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Hn.sharedClient||(Hn.sharedClient=new ds),Hn.sharedClient}createChild(e){var f,h,m,g,y,b,_,w,S;const t=this.child_execution_order+1,r=(f=this.replicas)==null?void 0:f.map(T=>{const{reroot:A,...I}=T;return I}),s=e.replicas??r,i=new Hn({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t}),a=((h=this.extra)==null?void 0:h.metadata)??{},o=((m=i.extra)==null?void 0:m.metadata)??{};Object.keys(a).length>0&&(i.extra={...i.extra,metadata:{...a,...o}}),ki in this&&(i[ki]=this[ki]);const c=Symbol.for("lc:child_config"),u=((g=e.extra)==null?void 0:g[c])??this.extra[c];if(kL(u)){const T={...u},A=EL(T.callbacks)?(b=(y=T.callbacks).copy)==null?void 0:b.call(y):void 0;A&&(Object.assign(A,{_parentRunId:i.id}),(S=(w=(_=A.handlers)==null?void 0:_.find(ok))==null?void 0:w.updateFromRunTree)==null||S.call(w,i),T.callbacks=A),i.extra[c]=T}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,t),d=d.parent_run;return this.child_runs.push(i),i}async end(e,t,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??t,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,t,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={}),t))for(const[u,l]of Object.entries(t))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,t,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,t){if(t.dotted_order){const r=t.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);t.dotted_order=i.join("."),i.length>0?t.trace_id=i[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){const r=Fv(this,sm)??{};r[e]=t,wL(this,sm,r);for(const s of this.child_runs)s._setReplicaTraceRoot(e,t)}_remapForProject(e){const{projectName:t,runtimeEnv:r,excludeChildRuns:s=!0,reroot:i=!1,distributedParentId:a,apiUrl:o,apiKey:c,workspaceId:u}=e,l=this._convertToCreate(this,r,s);if(t===this.project_name)return{...l,session_name:t};if(i){if(a)this._sliceParentId(a,l);else if(l.parent_run_id=void 0,l.dotted_order){const _=l.dotted_order.split(".");_.length>0&&(l.dotted_order=_[_.length-1],l.trace_id=l.id)}const b=Bv({projectName:t,apiUrl:o,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(b,l.id)}let d;if(!i){const b=Fv(this,sm)??{},_=Bv({projectName:t,apiUrl:o,apiKey:c,workspaceId:u});if(d=b[_],d&&(l.trace_id=d,l.dotted_order)){const w=l.dotted_order.split(".");let S=null;for(let T=0;T<w.length;T++)if(w[T].slice(-36)===d){S=T;break}if(S!==null){const T=w.slice(S);l.dotted_order=T.join(".")}}}const f=l.id,h=id(f,t);let m;l.trace_id?m=id(l.trace_id,t):m=h;let g;l.parent_run_id&&(g=id(l.parent_run_id,t));let y;return l.dotted_order&&(y=l.dotted_order.split(".").map(w=>{const S=w.slice(-36),T=id(S,t);return w.slice(0,-36)+T}).join(".")),{...l,id:h,trace_id:m,parent_run_id:g,dotted_order:y,session_name:t}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const t=VE();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:t,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,t,e);await this.client.createRun(r)}if(!e){Qd("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(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){var t;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:((t=this.parent_run)==null?void 0:t.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,t){var u,l,d,f;const r=e==null?void 0:e.callbacks;let s,i,a,o=yL();if(r){const h=((u=r==null?void 0:r.getParentRunId)==null?void 0:u.call(r))??"",m=(l=r==null?void 0:r.handlers)==null?void 0:l.find(g=>(g==null?void 0:g.name)=="langchain_tracer");s=(d=m==null?void 0:m.getRun)==null?void 0:d.call(m,h),i=m==null?void 0:m.projectName,a=m==null?void 0:m.client,o=o||!!m}return s?new Hn({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(t):new Hn({...t,client:a,tracingEnabled:o,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){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={...t,name:(t==null?void 0:t.name)??"parent",run_type:(t==null?void 0:t.run_type)??"chain",start_time:(t==null?void 0:t.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=zh.fromHeader(r.baggage);c.metadata=d.metadata,c.tags=d.tags,c.project_name=d.project_name,c.replicas=d.replicas}const u=new Hn(c);return u.distributedParentId=u.id,u}toHeaders(e){var r;const t={"langsmith-trace":this.dotted_order,baggage:new zh((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(t))e.set(s,i);return t}}Object.defineProperty(Hn,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function TL(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function ok(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function Hv(n){return Array.isArray(n)&&n.some(e=>ok(e))}function EL(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function kL(n){const e=n==null?void 0:n.callbacks;return n!=null&&typeof e=="object"&&(Hv(e==null?void 0:e.handlers)||Hv(e))}function IL(){const n=lr("LANGSMITH_RUNS_ENDPOINTS");if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e)){const t=[];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}t.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return t}else if(typeof e=="object"&&e!==null){OL(e);const t=[];for(const[r,s]of Object.entries(e)){const i=r.replace(/\/$/,"");if(typeof s=="string")t.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 t}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($j(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 xL(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):IL()}function OL(n){if(Object.keys(n).length>0&&Ut("ENDPOINT"))throw new Cj}var CL=he({BaseTracer:()=>ei,isBaseTracer:()=>ro});const $L=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function kg(n,e){if(n)return new Hn({...n,start_time:n._serialized_start_time??n.start_time,parent_run:kg(e),child_runs:n.child_runs.map(t=>kg(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:IE()},tracingEnabled:!1})}function im(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function ro(n){return typeof n._addRunToRunMap=="function"}var ei=class extends Qs{constructor(e){super(...arguments);p(this,"runMap",new Map);p(this,"runTreeMap",new Map);p(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?$L(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,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=ak(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,t].join("."),s._serialized_start_time=r)):s.parent_run_id=void 0:(s.trace_id=s.id,s.dotted_order=t,s._serialized_start_time=r),this.usesRunTreeMap){const a=kg(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 t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await((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 t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,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:t},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,t,r,s,i,a,o,c){var l,d;const u=this.getRunById(r)??this._createRunForLLMStart(e,t,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,t,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:t},execution_order:u,child_runs:[],child_execution_order:u,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,t,r,s,i,a,o,c){var l,d;const u=this.getRunById(r)??this._createRunForChatModelStart(e,t,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,t,r,s,i){var o;const a=this.getRunById(t);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,t,r,s,i){var o;const a=this.getRunById(t);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,t,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:t,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,t,r,s,i,a,o,c){var l,d;const u=this.getRunById(r)??this._createRunForChainStart(e,t,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,t,r,s,i){var o;const a=this.getRunById(t);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=im(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),(i==null?void 0:i.inputs)!==void 0&&(a.inputs=im(i.inputs,"input")),await((o=this.onChainEnd)==null?void 0:o.call(this,a)),await this._endTrace(a),a}async handleChainError(e,t,r,s,i){var o;const a=this.getRunById(t);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=im(i.inputs,"input")),await((o=this.onChainError)==null?void 0:o.call(this,a)),await this._endTrace(a),a}_createRunForToolStart(e,t,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:t},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,t,r,s,i,a,o){var u,l;const c=this.getRunById(r)??this._createRunForToolStart(e,t,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,t){var s;const r=this.getRunById(t);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,t){var s;const r=this.getRunById(t);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,t){var i;const r=this.getRunById(t);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,t){var s;const r=this.getRunById(t);!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,t,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:t},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,t,r,s,i,a,o){var u,l;const c=this.getRunById(r)??this._createRunForRetrieverStart(e,t,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,t){var s;const r=this.getRunById(t);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,t){var s;const r=this.getRunById(t);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,t){var s;const r=this.getRunById(t);!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,t,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:t,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}},RL=he({ConsoleCallbackHandler:()=>Ig});const ck={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 xn(n,e){return`${n.open}${e}${n.close}`}function Sr(n,e){try{return JSON.stringify(n,null,2)}catch{return e}}function Vv(n){return typeof n=="string"?n.trim():n==null?n:Sr(n,n.toString())}function ri(n){if(!n.end_time)return"";const e=n.end_time-n.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:zn}=ck;var Ig=class extends ei{constructor(){super(...arguments);p(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const s=this.runMap.get(r.parent_run_id);if(s)t.push(s),r=s;else break}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map((r,s,i)=>{const a=`${r.execution_order}:${r.run_type}:${r.name}`;return s===i.length-1?xn(ck.bold,a):a}).join(" > ");return xn(zn.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Sr(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.cyan,"[chain/end]")} [${t}] [${ri(e)}] Exiting Chain run with output: ${Sr(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.red,"[chain/error]")} [${t}] [${ri(e)}] Chain run errored with error: ${Sr(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${xn(zn.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Sr(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.cyan,"[llm/end]")} [${t}] [${ri(e)}] Exiting LLM run with output: ${Sr(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.red,"[llm/error]")} [${t}] [${ri(e)}] LLM run errored with error: ${Sr(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Vv(e.inputs.input)}"`)}onToolEnd(e){var r;const t=this.getBreadcrumbs(e);console.log(`${xn(zn.cyan,"[tool/end]")} [${t}] [${ri(e)}] Exiting Tool run with output: "${Vv((r=e.outputs)==null?void 0:r.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.red,"[tool/error]")} [${t}] [${ri(e)}] Tool run errored with error: ${Sr(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Sr(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.cyan,"[retriever/end]")} [${t}] [${ri(e)}] Exiting Retriever run with output: ${Sr(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${xn(zn.red,"[retriever/error]")} [${t}] [${ri(e)}] Retriever run errored with error: ${Sr(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${xn(zn.blue,"[agent/action]")} [${r}] Agent selected action: ${Sr(t.actions[t.actions.length-1],"[action]")}`)}};let am;const uk=()=>(am===void 0&&(am=new ds(Bt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),am);let PL=class{getStore(){}run(e,t){return t()}};const om=Symbol.for("ls:tracing_async_local_storage"),NL=new PL;let ML=class{getInstance(){return globalThis[om]??NL}initializeGlobalInstance(e){globalThis[om]===void 0&&(globalThis[om]=e)}};const jL=new ML;function LL(n=!1){const e=jL.getInstance().getStore();if(!n&&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 Fy(n){return typeof n=="function"&&"langsmith:traceable"in n}var DL=he({LangChainTracer:()=>tu,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>By});const By=new Set(["ls_agent_type"]);function UL(n){let e;for(const t of n)for(const r of t)Ve.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=Iy(e,r.message.usage_metadata));return e}var tu=class xg extends ei{constructor(t={}){super(t);p(this,"name","langchain_tracer");p(this,"projectName");p(this,"exampleId");p(this,"client");p(this,"replicas");p(this,"usesRunTreeMap",!0);p(this,"tracingMetadata");p(this,"tracingTags",[]);this.fields=t;const{exampleId:r,projectName:s,client:i,replicas:a,metadata:o,tags:c}=t;this.projectName=s??RE(),this.replicas=a,this.exampleId=r,this.client=i??uk(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];const u=xg.getTraceableRunTree();u&&this.updateFromRunTree(u)}async persistRun(t){}async onRunCreate(t){var r,s;Zv(this,t),(r=t.extra)!=null&&r.lc_defers_inputs||await((s=this.getRunTreeWithTracingConfig(t.id))==null?void 0:s.postRun())}async onRunUpdate(t){var s;Zv(this,t);const r=this.getRunTreeWithTracingConfig(t.id);(s=t.extra)!=null&&s.lc_defers_inputs?await(r==null?void 0:r.postRun()):await(r==null?void 0:r.patchRun())}onLLMEnd(t){const r=t.outputs;if(r!=null&&r.generations){const s=UL(r.generations);if(s!==void 0){t.extra=t.extra??{};const i=t.extra.metadata??{};i.usage_metadata=s,t.extra.metadata=i}}}copyWithTracingConfig({metadata:t,tags:r}){let s;if(t===void 0)s=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)s={...t};else{s={...this.tracingMetadata};for(const[o,c]of Object.entries(t))(!Object.prototype.hasOwnProperty.call(s,o)||By.has(o))&&(s[o]=c)}const i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],a=new xg({...this.fields,metadata:s,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let r=t;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=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(t){const r=this.runTreeMap.get(t);if(r)return new Hn({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return LL(!0)}catch{return}}static[Symbol.hasInstance](t){if(typeof t!="object"||t===null)return!1;const r=t;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Zv(n,e){if(n.tracingMetadata){e.extra??(e.extra={});const t=e.extra.metadata??{};let r=!1;for(const[s,i]of Object.entries(n.tracingMetadata))(!Object.prototype.hasOwnProperty.call(t,s)||By.has(s))&&t[s]!==i&&(t[s]=i,r=!0);r&&(e.extra.metadata=t)}n.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...n.tracingTags])))}const lk=Symbol.for("ls:tracing_async_local_storage"),Iu=Symbol.for("lc:context_variables"),zL=n=>{globalThis[lk]=n},Bu=()=>globalThis[lk];let ba;function FL(){return new("default"in Hs?Hs.default:Hs)({autoStart:!0,concurrency:1})}function BL(){return typeof ba>"u"&&(ba=FL()),ba}async function jt(n,e){if(e===!0){const t=Bu();t!==void 0?await t.run(void 0,async()=>n()):await n()}else ba=BL(),ba.add(async()=>{const t=Bu();t!==void 0?await t.run(void 0,async()=>n()):await n()})}async function HL(){const n=uk();await Promise.allSettled([typeof ba<"u"?ba.onIdle():Promise.resolve(),n.awaitPendingTraceBatches()])}var VL=he({awaitAllCallbacks:()=>HL,consumeCallback:()=>jt});const ZL=n=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Bt(e)==="true");function dk(n){var t,r;const e=Bu();if(e!==void 0)return(r=(t=e.getStore())==null?void 0:t[Iu])==null?void 0:r[n]}const KL=Symbol("lc:configure_hooks"),WL=()=>dk(KL)||[];var qL=he({BaseCallbackManager:()=>hk,BaseRunManager:()=>Nl,CallbackManager:()=>An,CallbackManagerForChainRun:()=>pk,CallbackManagerForLLMRun:()=>Og,CallbackManagerForRetrieverRun:()=>fk,CallbackManagerForToolRun:()=>mk,ensureHandler:()=>Hu,parseCallbackConfigArg:()=>Pl});function Pl(n){return n?Array.isArray(n)||"name"in n?{callbacks:n}:n:{}}var hk=class{setHandler(n){return this.setHandlers([n])}},Nl=class{constructor(n,e,t,r,s,i,a,o){this.runId=n,this.handlers=e,this.inheritableHandlers=t,this.tags=r,this.inheritableTags=s,this.metadata=i,this.inheritableMetadata=a,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;try{await((t=e.handleText)==null?void 0:t.call(e,n,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(n,e,t,r,s){await Promise.all(this.handlers.map(i=>jt(async()=>{var a;try{await((a=i.handleCustomEvent)==null?void 0:a.call(i,n,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)))}},fk=class extends Nl{getChild(n){const e=new An(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),n&&e.addTags([n],!1),e}async handleRetrieverEnd(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreRetriever)try{await((t=e.handleRetrieverEnd)==null?void 0:t.call(e,n,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(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreRetriever)try{await((t=e.handleRetrieverError)==null?void 0:t.call(e,n,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 n}},e.awaitHandlers)))}},Og=class extends Nl{async handleLLMNewToken(n,e,t,r,s,i){await Promise.all(this.handlers.map(a=>jt(async()=>{var o;if(!a.ignoreLLM)try{await((o=a.handleLLMNewToken)==null?void 0:o.call(a,n,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(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreLLM)try{await((t=e.handleChatModelStreamEvent)==null?void 0:t.call(e,n,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(n,e,t,r,s){await Promise.all(this.handlers.map(i=>jt(async()=>{var a;if(!i.ignoreLLM)try{await((a=i.handleLLMError)==null?void 0:a.call(i,n,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(n,e,t,r,s){await Promise.all(this.handlers.map(i=>jt(async()=>{var a;if(!i.ignoreLLM)try{await((a=i.handleLLMEnd)==null?void 0:a.call(i,n,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)))}},pk=class extends Nl{getChild(n){const e=new An(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),n&&e.addTags([n],!1),e}async handleChainError(n,e,t,r,s){await Promise.all(this.handlers.map(i=>jt(async()=>{var a;if(!i.ignoreChain)try{await((a=i.handleChainError)==null?void 0:a.call(i,n,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(n,e,t,r,s){await Promise.all(this.handlers.map(i=>jt(async()=>{var a;if(!i.ignoreChain)try{await((a=i.handleChainEnd)==null?void 0:a.call(i,n,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(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleAgentAction)==null?void 0:t.call(e,n,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(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleAgentEnd)==null?void 0:t.call(e,n,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)))}},mk=class extends Nl{getChild(n){const e=new An(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),n&&e.addTags([n],!1),e}async handleToolError(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleToolError)==null?void 0:t.call(e,n,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(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleToolEvent)==null?void 0:t.call(e,n,this.runId,this._parentRunId,this.tags))}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(n){await Promise.all(this.handlers.map(e=>jt(async()=>{var t;if(!e.ignoreAgent)try{await((t=e.handleToolEnd)==null?void 0:t.call(e,n,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)))}},An=class nu extends hk{constructor(t,r){super();p(this,"handlers",[]);p(this,"inheritableHandlers",[]);p(this,"tags",[]);p(this,"inheritableTags",[]);p(this,"metadata",{});p(this,"inheritableMetadata",{});p(this,"name","callback_manager");p(this,"_parentRunId");this.handlers=(r==null?void 0:r.handlers)??this.handlers,this.inheritableHandlers=(r==null?void 0:r.inheritableHandlers)??this.inheritableHandlers,this.tags=(r==null?void 0:r.tags)??this.tags,this.inheritableTags=(r==null?void 0:r.inheritableTags)??this.inheritableTags,this.metadata=(r==null?void 0:r.metadata)??this.metadata,this.inheritableMetadata=(r==null?void 0:r.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,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:js();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return ro(h)&&h._createRunForLLMStart(t,[l],f,this._parentRunId,a,this.tags,this.metadata,u),jt(async()=>{var m;try{await((m=h.handleLLMStart)==null?void 0:m.call(h,t,[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 Og(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,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:js();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return ro(h)&&h._createRunForChatModelStart(t,[l],f,this._parentRunId,a,this.tags,this.metadata,u),jt(async()=>{var m,g;try{if(h.handleChatModelStart)await((m=h.handleChatModelStart)==null?void 0:m.call(h,t,[l],f,this._parentRunId,a,this.tags,this.metadata,u));else if(h.handleLLMStart){const y=xy(l);await((g=h.handleLLMStart)==null?void 0:g.call(h,t,[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 Og(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,r,s=js(),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 ro(d)&&d._createRunForChainStart(t,r,s,this._parentRunId,this.tags,this.metadata,i,c,l),jt(async()=>{var f;try{await((f=d.handleChainStart)==null?void 0:f.call(d,t,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 pk(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,r,s=js(),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 ro(l)&&l._createRunForToolStart(t,r,s,this._parentRunId,this.tags,this.metadata,c),jt(async()=>{var d;try{await((d=l.handleToolStart)==null?void 0:d.call(l,t,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 mk(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,r,s=js(),i=void 0,a=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return ro(u)&&u._createRunForRetrieverStart(t,r,s,this._parentRunId,this.tags,this.metadata,c),jt(async()=>{var l;try{await((l=u.handleRetrieverStart)==null?void 0:l.call(u,t,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 fk(s,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,r,s,i,a){await Promise.all(this.handlers.map(o=>jt(async()=>{var c;if(!o.ignoreCustomEvent)try{await((c=o.handleCustomEvent)==null?void 0:c.call(o,t,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(t,r=!0){this.handlers.push(t),r&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(r=>r!==t),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==t)}setHandlers(t,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const s of t)this.addHandler(s,r)}addTags(t,r=!0){this.removeTags(t),this.tags.push(...t),r&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(r=>!t.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!t.includes(r))}addMetadata(t,r=!0){this.metadata={...this.metadata,...t},r&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const r of Object.keys(t))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(t=[],r=!0){const s=new nu(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 t)s.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===i.name)||s.addHandler(i,r);return s}static fromHandlers(t){class r extends Qs{constructor(){super();p(this,"name",js());Object.assign(this,t)}}const s=new this;return s.addHandler(new r),s}static configure(t,r,s,i,a,o,c){return this._configureSync(t,r,s,i,a,o,c)}static _configureSync(t,r,s,i,a,o,c){var y;let u;(t||r)&&(Array.isArray(t)||!t?(u=new nu,u.setHandlers((t==null?void 0:t.map(Hu))??[],!0)):u=t,u=u.copy(Array.isArray(r)?r.map(Hu):r==null?void 0:r.handlers,!1));const l=Bt("LANGCHAIN_VERBOSE")==="true"||(c==null?void 0:c.verbose),d=tu.getTraceableRunTree(),f=(d==null?void 0:d.tracingEnabled)??ZL();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||(Bt("LANGCHAIN_TRACING")??!1);if(l||h){if(u||(u=new nu),l&&!u.handlers.some(b=>b.name===Ig.prototype.name)){const b=new Ig;u.addHandler(b,!0)}if(h&&!u.handlers.some(b=>b.name==="langchain_tracer")&&f){const b=new tu;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:S}of WL()){const T=S&&Bt(S)==="true"&&w;let A;const I=b!==void 0?dk(b):void 0;I&&OE(I)?A=I:T&&(A=new w({})),A!==void 0&&(u||(u=new nu),u.handlers.some(k=>k.name===A.name)||u.addHandler(A,_))}(s||i)&&u&&(u.addTags(s??[]),u.addTags(i??[],!1)),(a||o)&&u&&(u.addMetadata(a??{}),u.addMetadata(o??{},!1));const m=c==null?void 0:c.tracerInheritableMetadata,g=c==null?void 0:c.tracerInheritableTags;return u&&(m||g)&&(u.handlers=u.handlers.map(b=>b instanceof tu?b.copyWithTracingConfig({metadata:m,tags:g}):b),u.inheritableHandlers=u.inheritableHandlers.map(b=>b instanceof tu?b.copyWithTracingConfig({metadata:m,tags:g}):b)),u}};function Hu(n){return"name"in n?n:Qs.fromMethods(n)}var gk=class{getStore(){}run(n,e){return e()}enterWith(n){}};const GL=new gk,Kv=Symbol.for("lc:child_config");var JL=class{getInstance(){return Bu()??GL}getRunnableConfig(){var n,e;return(e=(n=this.getInstance().getStore())==null?void 0:n.extra)==null?void 0:e[Kv]}runWithConfig(n,e,t){var u;const r=An._configureSync(n==null?void 0:n.callbacks,void 0,n==null?void 0:n.tags,void 0,n==null?void 0:n.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):t||(c=new Hn({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Kv]:n}),i!==void 0&&i[Iu]!==void 0&&(c===void 0&&(c={}),c[Iu]=i[Iu]),s.run(c,e)}initializeGlobalInstance(n){Bu()===void 0&&zL(n)}};const yn=new JL;var YL=he({AsyncLocalStorageProviderSingleton:()=>yn,MockAsyncLocalStorage:()=>gk,_CONTEXT_VARIABLES_KEY:()=>Iu});const XL=new Set(["api_key"]),QL=new Set(["string","number","boolean"]);function eD(n){const e=n.configurable??{},t=n.metadata??{},r={};for(const[s,i]of Object.entries(e))!s.startsWith("__")&&!Object.prototype.hasOwnProperty.call(t,s)&&!XL.has(s)&&QL.has(typeof i)&&(r[s]=i);return Object.keys(r).length>0?r:void 0}async function dr(n){return An._configureSync(n==null?void 0:n.callbacks,void 0,n==null?void 0:n.tags,void 0,n==null?void 0:n.metadata,void 0,{tracerInheritableMetadata:n?eD(n):void 0})}function or(...n){const e={};for(const t of n.filter(r=>!!r))for(const r of Object.keys(t))if(r==="metadata")e[r]={...e[r],...t[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(t[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...t[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(r==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(r==="callbacks"){const s=e.callbacks,i=t.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(Hu(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(Hu(o),!0);e.callbacks=a}else e.callbacks=new An(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]=t[s]??e[s]}return e}function rt(n){var r;const e=yn.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:s,runName:i,...a}=e;t=Object.entries(a).reduce((o,[c,u])=>(u!==void 0&&(o[c]=u),o),t)}if(n&&(t=Object.entries(n).reduce((s,[i,a])=>(a!==void 0&&(s[i]=a),s),t)),t!=null&&t.configurable&&typeof t.configurable.model=="string"&&((r=t.metadata)==null?void 0:r.model)===void 0&&(t.metadata||(t.metadata={}),t.metadata.model=t.configurable.model),t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const s=t.timeout,i=AbortSignal.timeout(s);t.metadata||(t.metadata={}),t.metadata.timeoutMs===void 0&&(t.metadata.timeoutMs=s),t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,i])):t.signal=i,delete t.timeout}return t}function ut(n={},{callbacks:e,maxConcurrency:t,recursionLimit:r,runName:s,configurable:i,runId:a}={}){const o=rt(n);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),t!==void 0&&(o.maxConcurrency=t),s!==void 0&&(o.runName=s),i!==void 0&&(o.configurable={...o.configurable,...i}),a!==void 0&&delete o.runId,o}function Ks(n){if(n)return{configurable:n.configurable,recursionLimit:n.recursionLimit,callbacks:n.callbacks,tags:n.tags,metadata:n.metadata,maxConcurrency:n.maxConcurrency,timeout:n.timeout,signal:n.signal,store:n.store}}async function Ts(n,e){if(e===void 0)return n;let t;return Promise.race([n.catch(r=>{if(!(e!=null&&e.aborted))throw r}),new Promise((r,s)=>{t=()=>{s(Vu(e))},e.addEventListener("abort",t,{once:!0}),e.aborted&&s(Vu(e))})]).finally(()=>e.removeEventListener("abort",t))}function Vu(n){return(n==null?void 0:n.reason)instanceof Error?n.reason:typeof(n==null?void 0:n.reason)=="string"?new Error(n.reason):new Error("Aborted")}var tD=he({AsyncGeneratorWithSetup:()=>Ua,IterableReadableStream:()=>Wn,atee:()=>Hy,concat:()=>Ws,pipeGeneratorWithSetup:()=>_k}),Wn=class Cg extends ReadableStream{constructor(){super(...arguments);p(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const r=t.getReader();return new Cg({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(t){return new Cg({async pull(r){const{value:s,done:i}=await t.next();i&&r.close(),r.enqueue(s)},async cancel(r){await t.return(r)}})}};function Hy(n,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(s){for(;;)if(s.length===0){const i=await n.next();for(const a of t)a.push(i)}else{if(s[0].done)return;yield s.shift().value}})}function Ws(n,e){if(Array.isArray(n)&&Array.isArray(e))return n.concat(e);if(typeof n=="string"&&typeof e=="string")return n+e;if(typeof n=="number"&&typeof e=="number")return n+e;if("concat"in n&&typeof n.concat=="function")return n.concat(e);if(typeof n=="object"&&typeof e=="object"){const t={...n};for(const[r,s]of Object.entries(e))r in t&&!Array.isArray(t[r])?t[r]=Ws(t[r],s):t[r]=s;return t}else throw new Error(`Cannot concat ${typeof n} and ${typeof e}`)}var Ua=class{constructor(n){p(this,"generator");p(this,"setup");p(this,"config");p(this,"signal");p(this,"firstResult");p(this,"firstResultUsed",!1);var e;this.generator=n.generator,this.config=n.config,this.signal=n.signal??((e=this.config)==null?void 0:e.signal),this.setup=new Promise((t,r)=>{yn.runWithConfig(Ks(n.config),async()=>{this.firstResult=this.signal?Ts(n.generator.next(),this.signal):n.generator.next(),n.startSetup?this.firstResult.then(n.startSetup).then(t,r):this.firstResult.then(s=>t(void 0),r)},!0)})}async next(...n){var e;return(e=this.signal)==null||e.throwIfAborted(),this.firstResultUsed?yn.runWithConfig(Ks(this.config),this.signal?async()=>Ts(this.generator.next(...n),this.signal):async()=>this.generator.next(...n),!0):(this.firstResultUsed=!0,this.firstResult)}async return(n){return this.generator.return(n)}async throw(n){return this.generator.throw(n)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function _k(n,e,t,r,...s){const i=new Ua({generator:e,startSetup:t,signal:r}),a=await i.setup;return{output:n(i,a,...s),setup:a}}/*!
|
|
62
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
63
|
+
* (c) 2017-2022 Joachim Wester
|
|
64
|
+
* MIT licensed
|
|
65
|
+
*/const nD=Object.prototype.hasOwnProperty;function $g(n,e){return nD.call(n,e)}function Rg(n){if(Array.isArray(n)){const t=new Array(n.length);for(let r=0;r<t.length;r++)t[r]=""+r;return t}if(Object.keys)return Object.keys(n);let e=[];for(let t in n)$g(n,t)&&e.push(t);return e}function Kr(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function Pg(n){let e=0;const t=n.length;let r;for(;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Ba(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function rD(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function Ng(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Ng(n[t]))return!0}else if(typeof n=="object"){const t=Rg(n),r=t.length;for(var e=0;e<r;e++)if(Ng(n[t[e]]))return!0}}return!1}function Wv(n,e){const t=[n];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(`${r}: ${s}`)}return t.join(`
|
|
66
|
+
`)}var sD=class extends Error{constructor(n,e,t,r,s){super(Wv(n,{name:e,index:t,operation:r,tree:s})),this.name=e,this.index=t,this.operation=r,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=Wv(n,{name:e,index:t,operation:r,tree:s})}},iD=he({JsonPatchError:()=>Mt,_areEquals:()=>Zu,applyOperation:()=>va,applyPatch:()=>Yo,applyReducer:()=>cD,deepClone:()=>aD,getValueByPointer:()=>Fh,validate:()=>yk,validator:()=>Bh});const Mt=sD,aD=Kr,yo={add:function(n,e,t){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){let r=Fh(t,this.path);r&&(r=Kr(r));const s=va(t,{op:"remove",path:this.from}).removed;return va(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){const r=Fh(t,this.from);return va(t,{op:"add",path:this.path,value:Kr(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:Zu(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}};var oD={add:function(n,e,t){return Pg(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){return{newDocument:t,removed:n.splice(e,1)[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:yo.move,copy:yo.copy,test:yo.test,_get:yo._get};function Fh(n,e){if(e=="")return n;var t={op:"_get",path:e};return va(n,t),t.value}function va(n,e,t=!1,r=!0,s=!0,i=0){if(t&&(typeof t=="function"?t(e,0,n,e.path):Bh(e,0)),e.path===""){let a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Fh(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=Zu(n,e.value),a.test===!1)throw new Mt("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new Mt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=Kr(n));const a=(e.path||"").split("/");let o=n,c=1,u=a.length,l,d,f;for(typeof t=="function"?f=t:f=Bh;;){if(d=a[c],d&&d.indexOf("~")!=-1&&(d=rD(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(t&&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,n,l)),c++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!Pg(d))throw new Mt("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,n);Pg(d)&&(d=~~d)}if(c>=u){if(t&&e.op==="add"&&d>o.length)throw new Mt("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);const h=oD[e.op].call(e,o,d,n);if(h.test===!1)throw new Mt("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return h}}else if(c>=u){const h=yo[e.op].call(e,o,d,n);if(h.test===!1)throw new Mt("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return h}if(o=o[d],t&&c<u&&(!o||typeof o!="object"))throw new Mt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}function Yo(n,e,t,r=!0,s=!0){if(t&&!Array.isArray(e))throw new Mt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=Kr(n));const i=new Array(e.length);for(let a=0,o=e.length;a<o;a++)i[a]=va(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}function cD(n,e,t){const r=va(n,e);if(r.test===!1)throw new Mt("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}function Bh(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new Mt("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(yo[n.op]){if(typeof n.path!="string")throw new Mt("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new Mt('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new Mt("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new Mt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&Ng(n.value))throw new Mt("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new Mt("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new Mt("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a=yk([{op:"_get",path:n.from,value:void 0}],t);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new Mt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new Mt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function yk(n,e,t){try{if(!Array.isArray(n))throw new Mt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Yo(Kr(e),Kr(n),t||!0);else{t=t||Bh;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof Mt)return s;throw s}}function Zu(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!Zu(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var o=Object.keys(n);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],!Zu(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}/*!
|
|
67
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
68
|
+
* (c) 2013-2021 Joachim Wester
|
|
69
|
+
* MIT license
|
|
70
|
+
*/function wk(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=Rg(e),a=Rg(n),o=!1,c=a.length-1;c>=0;c--){var u=a[c],l=n[u];if($g(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)?wk(l,d,t,r+"/"+Ba(u),s):l!==d&&(s&&t.push({op:"test",path:r+"/"+Ba(u),value:Kr(l)}),t.push({op:"replace",path:r+"/"+Ba(u),value:Kr(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+Ba(u),value:Kr(l)}),t.push({op:"remove",path:r+"/"+Ba(u)}),o=!0):(s&&t.push({op:"test",path:r,value:n}),t.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];!$g(n,u)&&e[u]!==void 0&&t.push({op:"add",path:r+"/"+Ba(u),value:Kr(e[u])})}}}function Zf(n,e,t=!1){var r=[];return wk(n,e,r,"",t),r}({...iD});var uD=he({LogStreamCallbackHandler:()=>jg,RunLog:()=>Vy,RunLogPatch:()=>Ds,isLogStreamHandler:()=>bk}),Ds=class{constructor(n){p(this,"ops");this.ops=n.ops??[]}concat(n){const e=this.ops.concat(n.ops),t=Yo({},e);return new Vy({ops:e,state:t[t.length-1].newDocument})}},Vy=class Mg extends Ds{constructor(t){super(t);p(this,"state");this.state=t.state}concat(t){const r=this.ops.concat(t.ops),s=Yo(this.state,t.ops);return new Mg({ops:r,state:s[s.length-1].newDocument})}static fromRunLogPatch(t){const r=Yo({},t.ops);return new Mg({ops:t.ops,state:r[r.length-1].newDocument})}};const bk=n=>n.name==="log_stream_tracer";async function qv(n,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:t}=n;if(["retriever","llm","prompt"].includes(n.run_type))return t;if(!(Object.keys(t).length===1&&(t==null?void 0:t.input)===""))return t.input}async function Gv(n,e){const{outputs:t}=n;return e==="original"||["retriever","llm","prompt"].includes(n.run_type)?t:t!==void 0&&Object.keys(t).length===1&&(t==null?void 0:t.output)!==void 0?t.output:t}function lD(n){return n!==void 0&&n.message!==void 0}var jg=class extends ei{constructor(e){super({_awaitHandler:!0,...e});p(this,"autoClose",!0);p(this,"includeNames");p(this,"includeTypes");p(this,"includeTags");p(this,"excludeNames");p(this,"excludeTypes");p(this,"excludeTags");p(this,"_schemaFormat","original");p(this,"rootId");p(this,"keyMapByRunId",{});p(this,"counterMapByRunName",{});p(this,"transformStream");p(this,"writer");p(this,"receiveStream");p(this,"name","log_stream_tracer");p(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Wn.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=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||t.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&&t.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new Ds({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 Ds({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 t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;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 qv(e,this._schemaFormat)),await this.writer.write(new Ds({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await qv(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await Gv(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const s=new Ds({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const t=new Ds({ops:[{op:"replace",path:"/final_output",value:await Gv(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const i=e.inputs.messages!==void 0;let a;i?lD(r==null?void 0:r.chunk)?a=r==null?void 0:r.chunk:a=new nt({id:`run-${e.id}`,content:t}):a=t;const o=new Ds({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${s}/streamed_output/-`,value:a}]});await this.writer.write(o)}},dD=he({ChatGenerationChunk:()=>fr,GenerationChunk:()=>Xo,RUN_KEY:()=>Ku});const Ku="__run";var Xo=class vk{constructor(e){p(this,"text");p(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new vk({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},fr=class Sk extends Xo{constructor(t){super(t);p(this,"message");this.message=t.message}concat(t){return new Sk({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function ld({name:n,serialized:e}){return n!==void 0?n:(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 hD=n=>n.name==="event_stream_tracer";var fD=class extends ei{constructor(e){super({_awaitHandler:!0,...e});p(this,"autoClose",!0);p(this,"includeNames");p(this,"includeTypes");p(this,"includeTags");p(this,"excludeNames");p(this,"excludeTypes");p(this,"excludeTags");p(this,"runInfoMap",new Map);p(this,"tappedPromises",new Map);p(this,"transformStream");p(this,"writer");p(this,"receiveStream");p(this,"readableStreamClosed",!1);p(this,"name","event_stream_tracer");p(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Wn.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=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||t.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&&t.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),r}async*tapOutputIterable(e,t){const r=await t.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 Xo({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 t)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 t)yield o}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){var a,o;const t=ld(e),r=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:t,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:t,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onLLMNewToken(e,t,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 nt({content:t,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 Xo({text:t}):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 t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===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(t.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(t.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: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){var a,o;const t=ld(e),r=e.run_type??"chain",s={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:t,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:t,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},s)}async onChainEnd(e){var a;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===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??t.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,t.inputs=s.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){var s,i;const t=ld(e),r={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{}},r)}async onToolEnd(e){var s;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.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:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.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:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){var s,i;const t=ld(e),r={tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{},name:t,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:t,tags:e.tags??[],run_id:e.id,metadata:((i=e.extra)==null?void 0:i.metadata)??{}},r)}async onRetrieverEnd(e){var r;const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===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:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,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:t},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};const pD=Object.prototype.toString,mD=n=>pD.call(n)==="[object Error]",gD=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 _D(n){if(!(n&&mD(n)&&n.name==="TypeError"&&typeof n.message=="string"))return!1;const{message:e,stack:t}=n;return e==="Load failed"?t===void 0||"__sentry_captured__"in n:e.startsWith("error sending request for url")?!0:gD.has(e)}function yD(n){if(typeof n=="number"){if(n<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(n))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(n!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function dd(n,e,{min:t=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${n}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${n}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${n}\` to be ≥ ${t}.`)}}var wD=class extends Error{constructor(n){super(),n instanceof Error?(this.originalError=n,{message:n}=n):(this.originalError=new Error(n),this.originalError.stack=this.stack),this.name="AbortError",this.message=n}};function bD(n,e){const t=Math.max(1,n+1),r=e.randomize?Math.random()+1:1;let s=Math.round(r*e.minTimeout*e.factor**(t-1));return s=Math.min(s,e.maxTimeout),s}function Jv(n,e){return Number.isFinite(e)?e-(performance.now()-n):e}async function vD({error:n,attemptNumber:e,retriesConsumed:t,startTime:r,options:s}){var h,m,g;const i=n instanceof Error?n:new TypeError(`Non-error was thrown: "${n}". You should only throw errors.`);if(i instanceof wD)throw i.originalError;const a=Number.isFinite(s.retries)?Math.max(0,s.retries-t):s.retries,o=s.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:t});if(await s.onFailedAttempt(c),Jv(r,o)<=0)throw i;const u=await s.shouldConsumeRetry(c),l=Jv(r,o);if(l<=0||a<=0)throw i;if(i instanceof TypeError&&!_D(i)){if(u)throw i;return(h=s.signal)==null||h.throwIfAborted(),!1}if(!await s.shouldRetry(c))throw i;if(!u)return(m=s.signal)==null||m.throwIfAborted(),!1;const d=bD(t,s),f=Math.min(d,l);return f>0&&await new Promise((y,b)=>{var S,T;const _=()=>{var A;clearTimeout(w),(A=s.signal)==null||A.removeEventListener("abort",_),b(s.signal.reason)},w=setTimeout(()=>{var A;(A=s.signal)==null||A.removeEventListener("abort",_),y()},f);s.unref&&((S=w.unref)==null||S.call(w)),(T=s.signal)==null||T.addEventListener("abort",_,{once:!0})}),(g=s.signal)==null||g.throwIfAborted(),!0}async function Lg(n,e={}){var i,a,o;if(e={...e},yD(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),dd("factor",e.factor,{min:0,allowInfinity:!1}),dd("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),dd("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),dd("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(i=e.signal)==null||i.throwIfAborted();let t=0,r=0;const s=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){t++;try{(a=e.signal)==null||a.throwIfAborted();const c=await n(t);return(o=e.signal)==null||o.throwIfAborted(),c}catch(c){await vD({error:c,attemptNumber:t,retriesConsumed:r,startTime:s,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var SD=he({AsyncCaller:()=>Ml});const AD=[400,401,402,403,404,405,406,407,409],TD=n=>{if(typeof n!="object"||n===null)return;if("message"in n&&typeof n.message=="string"&&(n.message.startsWith("Cancel")||n.message.startsWith("AbortError"))||"name"in n&&typeof n.name=="string"&&n.name==="AbortError"||"code"in n&&typeof n.code=="string"&&n.code==="ECONNABORTED")throw n;const e="response"in n&&typeof n.response=="object"&&n.response!==null&&"status"in n.response&&typeof n.response.status=="number"?n.response.status:void 0,t="status"in n&&typeof n.status=="number"?n.status:void 0,r=e??t;if(r&&AD.includes(+r))throw n;if(("error"in n&&typeof n.error=="object"&&n.error!==null&&"code"in n.error&&typeof n.error.code=="string"?n.error.code:void 0)==="insufficient_quota"){const s=new Error("message"in n&&typeof n.message=="string"?n.message:"Insufficient quota");throw s.name="InsufficientQuotaError",s}};var Ml=class{constructor(n){p(this,"maxConcurrency");p(this,"maxRetries");p(this,"onFailedAttempt");p(this,"queue");this.maxConcurrency=n.maxConcurrency??1/0,this.maxRetries=n.maxRetries??6,this.onFailedAttempt=n.onFailedAttempt??TD;const e="default"in Hs?Hs.default:Hs;this.queue=new e({concurrency:this.maxConcurrency})}async call(n,...e){return this.queue.add(()=>Lg(()=>n(...e).catch(t=>{throw t instanceof Error?t:new Error(t)}),{onFailedAttempt:({error:t})=>{var r;return(r=this.onFailedAttempt)==null?void 0:r.call(this,t)},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(n,e,...t){if(n.signal){let r;return Promise.race([this.call(e,...t),new Promise((s,i)=>{var a;r=()=>{i(Vu(n.signal))},(a=n.signal)==null||a.addEventListener("abort",r,{once:!0})})]).finally(()=>{n.signal&&r&&n.signal.removeEventListener("abort",r)})}return this.call(e,...t)}fetch(...n){return this.call(()=>fetch(...n).then(e=>e.ok?e:Promise.reject(e)))}},Ak=class extends ei{constructor({config:e,onStart:t,onEnd:r,onError:s}){super({_awaitHandler:!0});p(this,"name","RootListenersTracer");p(this,"rootId");p(this,"config");p(this,"argOnStart");p(this,"argOnEnd");p(this,"argOnError");this.config=e,this.argOnStart=t,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 Zy(n){return n?n.lc_runnable:!1}var ED=class{constructor(n){p(this,"includeNames");p(this,"includeTypes");p(this,"includeTags");p(this,"excludeNames");p(this,"excludeTypes");p(this,"excludeTags");this.includeNames=n.includeNames,this.includeTypes=n.includeTypes,this.includeTags=n.includeTags,this.excludeNames=n.excludeNames,this.excludeTypes=n.excludeTypes,this.excludeTags=n.excludeTags}includeEvent(n,e){let t=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const r=n.tags??[];return this.includeNames!==void 0&&(t=t||this.includeNames.includes(n.name)),this.includeTypes!==void 0&&(t=t||this.includeTypes.includes(e)),this.includeTags!==void 0&&(t=t||r.some(s=>{var i;return(i=this.includeTags)==null?void 0:i.includes(s)})),this.excludeNames!==void 0&&(t=t&&!this.excludeNames.includes(n.name)),this.excludeTypes!==void 0&&(t=t&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(t=t&&r.every(s=>{var i;return!((i=this.excludeTags)!=null&&i.includes(s))})),t}};const kD=n=>btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var Yv;function z(n,e,t){function r(o,c){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1}),o._zod.traits.has(n))return;o._zod.traits.add(n),e(o,c);const u=a.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){const f=l[d];f in o||(o[f]=u[f].bind(o))}}const s=(t==null?void 0:t.Parent)??Object;class i extends s{}Object.defineProperty(i,"name",{value:n});function a(o){var c;const u=t!=null&&t.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 t!=null&&t.Parent&&o instanceof t.Parent?!0:(u=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:u.has(n)}}),Object.defineProperty(a,"name",{value:n}),a}class xo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Tk extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Yv=globalThis).__zod_globalConfig??(Yv.__zod_globalConfig={});const Ky=globalThis.__zod_globalConfig;function qs(n){return Ky}function Ek(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Dg(n,e){return typeof e=="bigint"?e.toString():e}function Kf(n){return{get value(){{const e=n();return Object.defineProperty(this,"value",{value:e}),e}}}}function Wy(n){return n==null}function qy(n){const e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function ID(n,e){const t=n/e,r=Math.round(t),s=Number.EPSILON*Math.max(Math.abs(t),1);return Math.abs(t-r)<s?0:t-r}const Xv=Symbol("evaluating");function pt(n,e,t){let r;Object.defineProperty(n,e,{get(){if(r!==Xv)return r===void 0&&(r=Xv,r=t()),r},set(s){Object.defineProperty(n,e,{value:s})},configurable:!0})}function za(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Bi(...n){const e={};for(const t of n){const r=Object.getOwnPropertyDescriptors(t);Object.assign(e,r)}return Object.defineProperties({},e)}function Qv(n){return JSON.stringify(n)}function xD(n){return n.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const kk="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function Wu(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}const OD=Kf(()=>{var n;if(Ky.jitless||typeof navigator<"u"&&((n=navigator==null?void 0:navigator.userAgent)!=null&&n.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Qo(n){if(Wu(n)===!1)return!1;const e=n.constructor;if(e===void 0||typeof e!="function")return!0;const t=e.prototype;return!(Wu(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function Ik(n){return Qo(n)?{...n}:Array.isArray(n)?[...n]:n instanceof Map?new Map(n):n instanceof Set?new Set(n):n}const CD=new Set(["string","number","symbol"]);function ec(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pn(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t!=null&&t.parent)&&(r._zod.parent=n),r}function Ae(n){const e=n;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 $D(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}const RD={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 PD(n,e){const t=n._zod.def,r=t.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=Bi(n._zod.def,{get shape(){const a={};for(const o in e){if(!(o in t.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(a[o]=t.shape[o])}return za(this,"shape",a),a},checks:[]});return pn(n,i)}function ND(n,e){const t=n._zod.def,r=t.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=Bi(n._zod.def,{get shape(){const a={...n._zod.def.shape};for(const o in e){if(!(o in t.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete a[o]}return za(this,"shape",a),a},checks:[]});return pn(n,i)}function xk(n,e){if(!Qo(e))throw new Error("Invalid input to extend: expected a plain object");const t=n._zod.def.checks;if(t&&t.length>0){const i=n._zod.def.shape;for(const a in e)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const s=Bi(n._zod.def,{get shape(){const i={...n._zod.def.shape,...e};return za(this,"shape",i),i}});return pn(n,s)}function MD(n,e){if(!Qo(e))throw new Error("Invalid input to safeExtend: expected a plain object");const t=Bi(n._zod.def,{get shape(){const r={...n._zod.def.shape,...e};return za(this,"shape",r),r}});return pn(n,t)}function jD(n,e){var r;if((r=n._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const t=Bi(n._zod.def,{get shape(){const s={...n._zod.def.shape,...e._zod.def.shape};return za(this,"shape",s),s},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pn(n,t)}function Ok(n,e,t){const s=e._zod.def.checks;if(s&&s.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=Bi(e._zod.def,{get shape(){const o=e._zod.def.shape,c={...o};if(t)for(const u in t){if(!(u in o))throw new Error(`Unrecognized key: "${u}"`);t[u]&&(c[u]=n?new n({type:"optional",innerType:o[u]}):o[u])}else for(const u in o)c[u]=n?new n({type:"optional",innerType:o[u]}):o[u];return za(this,"shape",c),c},checks:[]});return pn(e,a)}function LD(n,e,t){const r=Bi(e._zod.def,{get shape(){const s=e._zod.def.shape,i={...s};if(t)for(const a in t){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=new n({type:"nonoptional",innerType:s[a]}))}else for(const a in s)i[a]=new n({type:"nonoptional",innerType:s[a]});return za(this,"shape",i),i}});return pn(e,r)}function wo(n,e=0){var t;if(n.aborted===!0)return!0;for(let r=e;r<n.issues.length;r++)if(((t=n.issues[r])==null?void 0:t.continue)!==!0)return!0;return!1}function DD(n,e=0){var t;if(n.aborted===!0)return!0;for(let r=e;r<n.issues.length;r++)if(((t=n.issues[r])==null?void 0:t.continue)===!1)return!0;return!1}function yi(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function hd(n){return typeof n=="string"?n:n==null?void 0:n.message}function Gs(n,e,t){var c,u,l,d,f,h;const r=n.message?n.message:hd((l=(u=(c=n.inst)==null?void 0:c._zod.def)==null?void 0:u.error)==null?void 0:l.call(u,n))??hd((d=e==null?void 0:e.error)==null?void 0:d.call(e,n))??hd((f=t.customError)==null?void 0:f.call(t,n))??hd((h=t.localeError)==null?void 0:h.call(t,n))??"Invalid input",{inst:s,continue:i,input:a,...o}=n;return o.path??(o.path=[]),o.message=r,e!=null&&e.reportInput&&(o.input=a),o}function Gy(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function qu(...n){const[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}const Ck=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),n.message=JSON.stringify(e,Dg,2),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},$k=z("$ZodError",Ck),Wf=z("$ZodError",Ck,{Parent:Error});function UD(n,e=t=>t.message){const t={},r=[];for(const s of n.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}function zD(n,e=t=>t.message){const t={_errors:[]},r=(s,i=[])=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>r({issues:o},[...i,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...i,...a.path]);else{const o=[...i,...a.path];if(o.length===0)t._errors.push(e(a));else{let c=t,u=0;for(;u<o.length;){const l=o[u];u===o.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(e(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}}};return r(n),t}function FD(n){const e=[],t=n.map(r=>typeof r=="object"?r.key:r);for(const r of t)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}function BD(n){var r;const e=[],t=[...n.issues].sort((s,i)=>(s.path??[]).length-(i.path??[]).length);for(const s of t)e.push(`✖ ${s.message}`),(r=s.path)!=null&&r.length&&e.push(` → at ${FD(s.path)}`);return e.join(`
|
|
71
|
+
`)}const qf=n=>(e,t,r,s)=>{const i=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:t,issues:[]},i);if(a instanceof Promise)throw new xo;if(a.issues.length){const o=new((s==null?void 0:s.Err)??n)(a.issues.map(c=>Gs(c,i,qs())));throw kk(o,s==null?void 0:s.callee),o}return a.value},Gf=qf(Wf),Jf=n=>async(e,t,r,s)=>{const i=r?{...r,async:!0}:{async:!0};let a=e._zod.run({value:t,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const o=new((s==null?void 0:s.Err)??n)(a.issues.map(c=>Gs(c,i,qs())));throw kk(o,s==null?void 0:s.callee),o}return a.value},Rk=Jf(Wf),Yf=n=>(e,t,r)=>{const s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},s);if(i instanceof Promise)throw new xo;return i.issues.length?{success:!1,error:new(n??$k)(i.issues.map(a=>Gs(a,s,qs())))}:{success:!0,data:i.value}},HD=Yf(Wf),Xf=n=>async(e,t,r)=>{const s=r?{...r,async:!0}:{async:!0};let i=e._zod.run({value:t,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new n(i.issues.map(a=>Gs(a,s,qs())))}:{success:!0,data:i.value}},VD=Xf(Wf),ZD=n=>(e,t,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return qf(n)(e,t,s)},KD=n=>(e,t,r)=>qf(n)(e,t,r),WD=n=>async(e,t,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Jf(n)(e,t,s)},qD=n=>async(e,t,r)=>Jf(n)(e,t,r),GD=n=>(e,t,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Yf(n)(e,t,s)},JD=n=>(e,t,r)=>Yf(n)(e,t,r),YD=n=>async(e,t,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Xf(n)(e,t,s)},XD=n=>async(e,t,r)=>Xf(n)(e,t,r),QD=/^[cC][0-9a-z]{6,}$/,e4=/^[0-9a-z]+$/,t4=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,n4=/^[0-9a-vA-V]{20}$/,r4=/^[A-Za-z0-9]{27}$/,s4=/^[a-zA-Z0-9_-]{21}$/,i4=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,a4=/^([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})$/,e0=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,o4=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,c4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function u4(){return new RegExp(c4,"u")}const l4=/^(?:(?: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])$/,d4=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,h4=/^((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])$/,f4=/^(([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])$/,p4=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pk=/^[A-Za-z0-9_-]*$/,m4=/^https?$/,g4=/^\+[1-9]\d{6,14}$/,Nk="(?:(?:\\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])))",_4=new RegExp(`^${Nk}$`);function Mk(n){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function y4(n){return new RegExp(`^${Mk(n)}$`)}function w4(n){const e=Mk({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${t.join("|")})`;return new RegExp(`^${Nk}T(?:${r})$`)}const b4=n=>{const e=n?`[\\s\\S]{${(n==null?void 0:n.minimum)??0},${(n==null?void 0:n.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},v4=/^-?\d+$/,jk=/^-?\d+(?:\.\d+)?$/,S4=/^(?:true|false)$/i,A4=/^[^A-Z]*$/,T4=/^[^a-z]*$/,Yn=z("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),Lk={number:"number",bigint:"bigint",object:"date"},Dk=z("$ZodCheckLessThan",(n,e)=>{Yn.init(n,e);const t=Lk[typeof e.value];n._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)}),n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),Uk=z("$ZodCheckGreaterThan",(n,e)=>{Yn.init(n,e);const t=Lk[typeof e.value];n._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)}),n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),E4=z("$ZodCheckMultipleOf",(n,e)=>{Yn.init(n,e),n._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):ID(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),k4=z("$ZodCheckNumberFormat",(n,e)=>{var a;Yn.init(n,e),e.format=e.format||"float64";const t=(a=e.format)==null?void 0:a.includes("int"),r=t?"int":"number",[s,i]=RD[e.format];n._zod.onattach.push(o=>{const c=o._zod.bag;c.format=e.format,c.minimum=s,c.maximum=i,t&&(c.pattern=v4)}),n._zod.check=o=>{const c=o.value;if(t){if(!Number.isInteger(c)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:c,inst:n});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:n,origin:r,inclusive:!0,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:n,origin:r,inclusive:!0,continue:!e.abort});return}}c<s&&o.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:n,continue:!e.abort}),c>i&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:n,continue:!e.abort})}}),I4=z("$ZodCheckMaxLength",(n,e)=>{var t;Yn.init(n,e),(t=n._zod.def).when??(t.when=r=>{const s=r.value;return!Wy(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),n._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const a=Gy(s);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:n,continue:!e.abort})}}),x4=z("$ZodCheckMinLength",(n,e)=>{var t;Yn.init(n,e),(t=n._zod.def).when??(t.when=r=>{const s=r.value;return!Wy(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),n._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const a=Gy(s);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:n,continue:!e.abort})}}),O4=z("$ZodCheckLengthEquals",(n,e)=>{var t;Yn.init(n,e),(t=n._zod.def).when??(t.when=r=>{const s=r.value;return!Wy(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),n._zod.check=r=>{const s=r.value,i=s.length;if(i===e.length)return;const a=Gy(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:n,continue:!e.abort})}}),Qf=z("$ZodCheckStringFormat",(n,e)=>{var t,r;Yn.init(n,e),n._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?(t=n._zod).check??(t.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:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),C4=z("$ZodCheckRegex",(n,e)=>{Qf.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),$4=z("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=A4),Qf.init(n,e)}),R4=z("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=T4),Qf.init(n,e)}),P4=z("$ZodCheckIncludes",(n,e)=>{Yn.init(n,e);const t=ec(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=r,n._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._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:n,continue:!e.abort})}}),N4=z("$ZodCheckStartsWith",(n,e)=>{Yn.init(n,e);const t=new RegExp(`^${ec(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(t)}),n._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:n,continue:!e.abort})}}),M4=z("$ZodCheckEndsWith",(n,e)=>{Yn.init(n,e);const t=new RegExp(`.*${ec(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(t)}),n._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:n,continue:!e.abort})}}),j4=z("$ZodCheckOverwrite",(n,e)=>{Yn.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}});class L4{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,t=this==null?void 0:this.args,s=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new e(...t,s.join(`
|
|
73
|
+
`))}}const D4={major:4,minor:4,patch:3},Et=z("$ZodType",(n,e)=>{var s;var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=D4;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const i of r)for(const a of i._zod.onattach)a(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),(s=n._zod.deferred)==null||s.push(()=>{n._zod.run=n._zod.parse});else{const i=(o,c,u)=>{let l=wo(o),d;for(const f of c){if(f._zod.def.when){if(DD(o)||!f._zod.def.when(o))continue}else if(l)continue;const h=o.issues.length,m=f._zod.check(o);if(m instanceof Promise&&(u==null?void 0:u.async)===!1)throw new xo;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,o.issues.length!==h&&(l||(l=wo(o,h)))});else{if(o.issues.length===h)continue;l||(l=wo(o,h))}}return d?d.then(()=>o):o},a=(o,c,u)=>{if(wo(o))return o.aborted=!0,o;const l=i(c,r,u);if(l instanceof Promise){if(u.async===!1)throw new xo;return l.then(d=>n._zod.parse(d,u))}return n._zod.parse(l,u)};n._zod.run=(o,c)=>{if(c.skipChecks)return n._zod.parse(o,c);if(c.direction==="backward"){const l=n._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(d=>a(d,o,c)):a(l,o,c)}const u=n._zod.parse(o,c);if(u instanceof Promise){if(c.async===!1)throw new xo;return u.then(l=>i(l,r,c))}return i(u,r,c)}}pt(n,"~standard",()=>({validate:i=>{var a;try{const o=HD(n,i);return o.success?{value:o.data}:{issues:(a=o.error)==null?void 0:a.issues}}catch{return VD(n,i).then(c=>{var u;return c.success?{value:c.data}:{issues:(u=c.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}))}),Jy=z("$ZodString",(n,e)=>{var t;Et.init(n,e),n._zod.pattern=[...((t=n==null?void 0:n._zod.bag)==null?void 0:t.patterns)??[]].pop()??b4(n._zod.bag),n._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:n}),r}}),$t=z("$ZodStringFormat",(n,e)=>{Qf.init(n,e),Jy.init(n,e)}),U4=z("$ZodGUID",(n,e)=>{e.pattern??(e.pattern=a4),$t.init(n,e)}),z4=z("$ZodUUID",(n,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=e0(r))}else e.pattern??(e.pattern=e0());$t.init(n,e)}),F4=z("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=o4),$t.init(n,e)}),B4=z("$ZodURL",(n,e)=>{$t.init(n,e),n._zod.check=t=>{var r;try{const s=t.value.trim();if(!e.normalize&&((r=e.protocol)==null?void 0:r.source)===m4.source&&!/^https?:\/\//i.test(s)){t.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:t.value,inst:n,continue:!e.abort});return}const i=new URL(s);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:t.value,inst:n,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort})),e.normalize?t.value=i.href:t.value=s;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}}),H4=z("$ZodEmoji",(n,e)=>{e.pattern??(e.pattern=u4()),$t.init(n,e)}),V4=z("$ZodNanoID",(n,e)=>{e.pattern??(e.pattern=s4),$t.init(n,e)}),Z4=z("$ZodCUID",(n,e)=>{e.pattern??(e.pattern=QD),$t.init(n,e)}),K4=z("$ZodCUID2",(n,e)=>{e.pattern??(e.pattern=e4),$t.init(n,e)}),W4=z("$ZodULID",(n,e)=>{e.pattern??(e.pattern=t4),$t.init(n,e)}),q4=z("$ZodXID",(n,e)=>{e.pattern??(e.pattern=n4),$t.init(n,e)}),G4=z("$ZodKSUID",(n,e)=>{e.pattern??(e.pattern=r4),$t.init(n,e)}),J4=z("$ZodISODateTime",(n,e)=>{e.pattern??(e.pattern=w4(e)),$t.init(n,e)}),Y4=z("$ZodISODate",(n,e)=>{e.pattern??(e.pattern=_4),$t.init(n,e)}),X4=z("$ZodISOTime",(n,e)=>{e.pattern??(e.pattern=y4(e)),$t.init(n,e)}),Q4=z("$ZodISODuration",(n,e)=>{e.pattern??(e.pattern=i4),$t.init(n,e)}),eU=z("$ZodIPv4",(n,e)=>{e.pattern??(e.pattern=l4),$t.init(n,e),n._zod.bag.format="ipv4"}),tU=z("$ZodIPv6",(n,e)=>{e.pattern??(e.pattern=d4),$t.init(n,e),n._zod.bag.format="ipv6",n._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:n,continue:!e.abort})}}}),nU=z("$ZodCIDRv4",(n,e)=>{e.pattern??(e.pattern=h4),$t.init(n,e)}),rU=z("$ZodCIDRv6",(n,e)=>{e.pattern??(e.pattern=f4),$t.init(n,e),n._zod.check=t=>{const r=t.value.split("/");try{if(r.length!==2)throw new Error;const[s,i]=r;if(!i)throw new Error;const a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${s}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:n,continue:!e.abort})}}});function zk(n){if(n==="")return!0;if(/\s/.test(n)||n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}const sU=z("$ZodBase64",(n,e)=>{e.pattern??(e.pattern=p4),$t.init(n,e),n._zod.bag.contentEncoding="base64",n._zod.check=t=>{zk(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:n,continue:!e.abort})}});function iU(n){if(!Pk.test(n))return!1;const e=n.replace(/[-_]/g,r=>r==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return zk(t)}const aU=z("$ZodBase64URL",(n,e)=>{e.pattern??(e.pattern=Pk),$t.init(n,e),n._zod.bag.contentEncoding="base64url",n._zod.check=t=>{iU(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:n,continue:!e.abort})}}),oU=z("$ZodE164",(n,e)=>{e.pattern??(e.pattern=g4),$t.init(n,e)});function cU(n,e=null){try{const t=n.split(".");if(t.length!==3)return!1;const[r]=t;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 uU=z("$ZodJWT",(n,e)=>{$t.init(n,e),n._zod.check=t=>{cU(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:n,continue:!e.abort})}}),Fk=z("$ZodNumber",(n,e)=>{Et.init(n,e),n._zod.pattern=n._zod.bag.pattern??jk,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}const s=t.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return t;const i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:s,inst:n,...i?{received:i}:{}}),t}}),lU=z("$ZodNumberFormat",(n,e)=>{k4.init(n,e),Fk.init(n,e)}),dU=z("$ZodBoolean",(n,e)=>{Et.init(n,e),n._zod.pattern=S4,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=!!t.value}catch{}const s=t.value;return typeof s=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:n}),t}}),hU=z("$ZodAny",(n,e)=>{Et.init(n,e),n._zod.parse=t=>t}),Bk=z("$ZodUnknown",(n,e)=>{Et.init(n,e),n._zod.parse=t=>t}),Hk=z("$ZodNever",(n,e)=>{Et.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});function t0(n,e,t){n.issues.length&&e.issues.push(...yi(t,n.issues)),e.value[t]=n.value}const fU=z("$ZodArray",(n,e)=>{Et.init(n,e),n._zod.parse=(t,r)=>{const s=t.value;if(!Array.isArray(s))return t.issues.push({expected:"array",code:"invalid_type",input:s,inst:n}),t;t.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=>t0(u,t,a))):t0(c,t,a)}return i.length?Promise.all(i).then(()=>t):t}});function Hh(n,e,t,r,s,i){const a=t in r;if(n.issues.length){if(s&&i&&!a)return;e.issues.push(...yi(t,n.issues))}if(!a&&!s){n.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}n.value===void 0?a&&(e.value[t]=void 0):e.value[t]=n.value}function Vk(n){var r,s,i,a;const e=Object.keys(n.shape);for(const o of e)if(!((a=(i=(s=(r=n.shape)==null?void 0:r[o])==null?void 0:s._zod)==null?void 0:i.traits)!=null&&a.has("$ZodType")))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const t=$D(n.shape);return{...n,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(t)}}function Zk(n,e,t,r,s,i){const a=[],o=s.keySet,c=s.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(const f in e){if(f==="__proto__"||o.has(f))continue;if(u==="never"){a.push(f);continue}const h=c.run({value:e[f],issues:[]},r);h instanceof Promise?n.push(h.then(m=>Hh(m,t,f,e,l,d))):Hh(h,t,f,e,l,d)}return a.length&&t.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:i}),n.length?Promise.all(n).then(()=>t):t}const pU=z("$ZodObject",(n,e)=>{Et.init(n,e);const t=Object.getOwnPropertyDescriptor(e,"shape");if(!(t!=null&&t.get)){const o=e.shape;Object.defineProperty(e,"shape",{get:()=>{const c={...o};return Object.defineProperty(e,"shape",{value:c}),c}})}const r=Kf(()=>Vk(e));pt(n._zod,"propValues",()=>{const o=e.shape,c={};for(const u in o){const l=o[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(const d of l.values)c[u].add(d)}}return c});const s=Wu,i=e.catchall;let a;n._zod.parse=(o,c)=>{a??(a=r.value);const u=o.value;if(!s(u))return o.issues.push({expected:"object",code:"invalid_type",input:u,inst:n}),o;o.value={};const l=[],d=a.shape;for(const f of a.keys){const h=d[f],m=h._zod.optin==="optional",g=h._zod.optout==="optional",y=h._zod.run({value:u[f],issues:[]},c);y instanceof Promise?l.push(y.then(b=>Hh(b,o,f,u,m,g))):Hh(y,o,f,u,m,g)}return i?Zk(l,u,o,c,r.value,n):l.length?Promise.all(l).then(()=>o):o}}),mU=z("$ZodObjectJIT",(n,e)=>{pU.init(n,e);const t=n._zod.parse,r=Kf(()=>Vk(e)),s=f=>{var w,S;const h=new L4(["shape","payload","ctx"]),m=r.value,g=T=>{const A=Qv(T);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};h.write("const input = payload.value;");const y=Object.create(null);let b=0;for(const T of m.keys)y[T]=`key_${b++}`;h.write("const newResult = {};");for(const T of m.keys){const A=y[T],I=Qv(T),k=f[T],R=((w=k==null?void 0:k._zod)==null?void 0:w.optin)==="optional",x=((S=k==null?void 0:k._zod)==null?void 0:S.optout)==="optional";h.write(`const ${A} = ${g(T)};`),R&&x?h.write(`
|
|
74
|
+
if (${A}.issues.length) {
|
|
75
|
+
if (${I} in input) {
|
|
76
|
+
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
|
|
77
|
+
...iss,
|
|
78
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
79
|
+
})));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (${A}.value === undefined) {
|
|
84
|
+
if (${I} in input) {
|
|
85
|
+
newResult[${I}] = undefined;
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
newResult[${I}] = ${A}.value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
`):R?h.write(`
|
|
92
|
+
if (${A}.issues.length) {
|
|
93
|
+
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
|
|
94
|
+
...iss,
|
|
95
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
96
|
+
})));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (${A}.value === undefined) {
|
|
100
|
+
if (${I} in input) {
|
|
101
|
+
newResult[${I}] = undefined;
|
|
102
|
+
}
|
|
103
|
+
} else {
|
|
104
|
+
newResult[${I}] = ${A}.value;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
`):h.write(`
|
|
108
|
+
const ${A}_present = ${I} in input;
|
|
109
|
+
if (${A}.issues.length) {
|
|
110
|
+
payload.issues = payload.issues.concat(${A}.issues.map(iss => ({
|
|
111
|
+
...iss,
|
|
112
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
113
|
+
})));
|
|
114
|
+
}
|
|
115
|
+
if (!${A}_present && !${A}.issues.length) {
|
|
116
|
+
payload.issues.push({
|
|
117
|
+
code: "invalid_type",
|
|
118
|
+
expected: "nonoptional",
|
|
119
|
+
input: undefined,
|
|
120
|
+
path: [${I}]
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (${A}_present) {
|
|
125
|
+
if (${A}.value === undefined) {
|
|
126
|
+
newResult[${I}] = undefined;
|
|
127
|
+
} else {
|
|
128
|
+
newResult[${I}] = ${A}.value;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
`)}h.write("payload.value = newResult;"),h.write("return payload;");const _=h.compile();return(T,A)=>_(f,T,A)};let i;const a=Wu,o=!Ky.jitless,u=o&&OD.value,l=e.catchall;let d;n._zod.parse=(f,h)=>{d??(d=r.value);const m=f.value;return a(m)?o&&u&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(i||(i=s(e.shape)),f=i(f,h),l?Zk([],m,f,h,d,n):f):t(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:n}),f)}});function n0(n,e,t,r){for(const i of n)if(i.issues.length===0)return e.value=i.value,e;const s=n.filter(i=>!wo(i));return s.length===1?(e.value=s[0].value,s[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(i=>i.issues.map(a=>Gs(a,r,qs())))}),e)}const Kk=z("$ZodUnion",(n,e)=>{Et.init(n,e),pt(n._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pt(n._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pt(n._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pt(n._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${r.map(s=>qy(s.source)).join("|")})$`)}});const t=e.options.length===1?e.options[0]._zod.run:null;n._zod.parse=(r,s)=>{if(t)return t(r,s);let i=!1;const a=[];for(const o of e.options){const c=o._zod.run({value:r.value,issues:[]},s);if(c instanceof Promise)a.push(c),i=!0;else{if(c.issues.length===0)return c;a.push(c)}}return i?Promise.all(a).then(o=>n0(o,r,n,s)):n0(a,r,n,s)}}),gU=z("$ZodDiscriminatedUnion",(n,e)=>{e.inclusive=!1,Kk.init(n,e);const t=n._zod.parse;pt(n._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=Kf(()=>{var a;const s=e.options,i=new Map;for(const o of s){const c=(a=o._zod.propValues)==null?void 0:a[e.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const u of c){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,o)}}return i});n._zod.parse=(s,i)=>{const a=s.value;if(!Wu(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:n}),s;const o=r.value.get(a==null?void 0:a[e.discriminator]);return o?o._zod.run(s,i):e.unionFallback||i.direction==="backward"?t(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:a,path:[e.discriminator],inst:n}),s)}}),_U=z("$ZodIntersection",(n,e)=>{Et.init(n,e),n._zod.parse=(t,r)=>{const s=t.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])=>r0(t,c,u)):r0(t,i,a)}});function Ug(n,e){if(n===e)return{valid:!0,data:n};if(n instanceof Date&&e instanceof Date&&+n==+e)return{valid:!0,data:n};if(Qo(n)&&Qo(e)){const t=Object.keys(e),r=Object.keys(n).filter(i=>t.indexOf(i)!==-1),s={...n,...e};for(const i of r){const a=Ug(n[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(n)&&Array.isArray(e)){if(n.length!==e.length)return{valid:!1,mergeErrorPath:[]};const t=[];for(let r=0;r<n.length;r++){const s=n[r],i=e[r],a=Ug(s,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};t.push(a.data)}return{valid:!0,data:t}}return{valid:!1,mergeErrorPath:[]}}function r0(n,e,t){const r=new Map;let s;for(const o of e.issues)if(o.code==="unrecognized_keys"){s??(s=o);for(const c of o.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else n.issues.push(o);for(const o of t.issues)if(o.code==="unrecognized_keys")for(const c of o.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else n.issues.push(o);const i=[...r].filter(([,o])=>o.l&&o.r).map(([o])=>o);if(i.length&&s&&n.issues.push({...s,keys:i}),wo(n))return n;const a=Ug(e.value,t.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return n.value=a.data,n}const yU=z("$ZodTuple",(n,e)=>{Et.init(n,e);const t=e.items;n._zod.parse=(r,s)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:n,expected:"tuple",code:"invalid_type"}),r;r.value=[];const a=[],o=s0(t,"optin"),c=s0(t,"optout");if(!e.rest){if(i.length<o)return r.issues.push({code:"too_small",minimum:o,inclusive:!0,input:i,inst:n,origin:"array"}),r;i.length>t.length&&r.issues.push({code:"too_big",maximum:t.length,inclusive:!0,input:i,inst:n,origin:"array"})}const u=new Array(t.length);for(let l=0;l<t.length;l++){const d=t[l]._zod.run({value:i[l],issues:[]},s);d instanceof Promise?a.push(d.then(f=>{u[l]=f})):u[l]=d}if(e.rest){let l=t.length-1;const d=i.slice(t.length);for(const f of d){l++;const h=e.rest._zod.run({value:f,issues:[]},s);h instanceof Promise?a.push(h.then(m=>i0(m,r,l))):i0(h,r,l)}}return a.length?Promise.all(a).then(()=>a0(u,r,t,i,c)):a0(u,r,t,i,c)}});function s0(n,e){for(let t=n.length-1;t>=0;t--)if(n[t]._zod[e]!=="optional")return t+1;return 0}function i0(n,e,t){n.issues.length&&e.issues.push(...yi(t,n.issues)),e.value[t]=n.value}function a0(n,e,t,r,s){for(let i=0;i<t.length;i++){const a=n[i],o=i<r.length;if(a.issues.length){if(!o&&i>=s){e.value.length=i;break}e.issues.push(...yi(i,a.issues))}e.value[i]=a.value}for(let i=e.value.length-1;i>=r.length&&(t[i]._zod.optout==="optional"&&e.value[i]===void 0);i--)e.value.length=i;return e}const wU=z("$ZodRecord",(n,e)=>{Et.init(n,e),n._zod.parse=(t,r)=>{const s=t.value;if(!Qo(s))return t.issues.push({expected:"record",code:"invalid_type",input:s,inst:n}),t;const i=[],a=e.keyType._zod.values;if(a){t.value={};const o=new Set;for(const u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){o.add(typeof u=="number"?u.toString():u);const l=e.keyType._zod.run({value:u,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){t.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(h=>Gs(h,r,qs())),input:u,path:[u],inst:n});continue}const d=l.value,f=e.valueType._zod.run({value:s[u],issues:[]},r);f instanceof Promise?i.push(f.then(h=>{h.issues.length&&t.issues.push(...yi(u,h.issues)),t.value[d]=h.value})):(f.issues.length&&t.issues.push(...yi(u,f.issues)),t.value[d]=f.value)}let c;for(const u in s)o.has(u)||(c=c??[],c.push(u));c&&c.length>0&&t.issues.push({code:"unrecognized_keys",input:s,inst:n,keys:c})}else{t.value={};for(const o of Reflect.ownKeys(s)){if(o==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,o))continue;let c=e.keyType._zod.run({value:o,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof o=="string"&&jk.test(o)&&c.issues.length){const d=e.keyType._zod.run({value:Number(o),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?t.value[o]=s[o]:t.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Gs(d,r,qs())),input:o,path:[o],inst:n});continue}const l=e.valueType._zod.run({value:s[o],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&t.issues.push(...yi(o,d.issues)),t.value[c.value]=d.value})):(l.issues.length&&t.issues.push(...yi(o,l.issues)),t.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>t):t}}),bU=z("$ZodEnum",(n,e)=>{Et.init(n,e);const t=Ek(e.entries),r=new Set(t);n._zod.values=r,n._zod.pattern=new RegExp(`^(${t.filter(s=>CD.has(typeof s)).map(s=>typeof s=="string"?ec(s):s.toString()).join("|")})$`),n._zod.parse=(s,i)=>{const a=s.value;return r.has(a)||s.issues.push({code:"invalid_value",values:t,input:a,inst:n}),s}}),vU=z("$ZodLiteral",(n,e)=>{if(Et.init(n,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const t=new Set(e.values);n._zod.values=t,n._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ec(r):r?ec(r.toString()):String(r)).join("|")})$`),n._zod.parse=(r,s)=>{const i=r.value;return t.has(i)||r.issues.push({code:"invalid_value",values:e.values,input:i,inst:n}),r}}),SU=z("$ZodTransform",(n,e)=>{Et.init(n,e),n._zod.optin="optional",n._zod.parse=(t,r)=>{if(r.direction==="backward")throw new Tk(n.constructor.name);const s=e.transform(t.value,t);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(t.value=a,t.fallback=!0,t));if(s instanceof Promise)throw new xo;return t.value=s,t.fallback=!0,t}});function o0(n,e){return e===void 0&&(n.issues.length||n.fallback)?{issues:[],value:void 0}:n}const ep=z("$ZodOptional",(n,e)=>{Et.init(n,e),n._zod.optin="optional",n._zod.optout="optional",pt(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pt(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${qy(t.source)})?$`):void 0}),n._zod.parse=(t,r)=>{if(e.innerType._zod.optin==="optional"){const s=t.value,i=e.innerType._zod.run(t,r);return i instanceof Promise?i.then(a=>o0(a,s)):o0(i,s)}return t.value===void 0?t:e.innerType._zod.run(t,r)}}),AU=z("$ZodExactOptional",(n,e)=>{ep.init(n,e),pt(n._zod,"values",()=>e.innerType._zod.values),pt(n._zod,"pattern",()=>e.innerType._zod.pattern),n._zod.parse=(t,r)=>e.innerType._zod.run(t,r)}),TU=z("$ZodNullable",(n,e)=>{Et.init(n,e),pt(n._zod,"optin",()=>e.innerType._zod.optin),pt(n._zod,"optout",()=>e.innerType._zod.optout),pt(n._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${qy(t.source)}|null)$`):void 0}),pt(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),n._zod.parse=(t,r)=>t.value===null?t:e.innerType._zod.run(t,r)}),EU=z("$ZodDefault",(n,e)=>{Et.init(n,e),n._zod.optin="optional",pt(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);if(t.value===void 0)return t.value=e.defaultValue,t;const s=e.innerType._zod.run(t,r);return s instanceof Promise?s.then(i=>c0(i,e)):c0(s,e)}});function c0(n,e){return n.value===void 0&&(n.value=e.defaultValue),n}const kU=z("$ZodPrefault",(n,e)=>{Et.init(n,e),n._zod.optin="optional",pt(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>(r.direction==="backward"||t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,r))}),IU=z("$ZodNonOptional",(n,e)=>{Et.init(n,e),pt(n._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(r=>r!==void 0)):void 0}),n._zod.parse=(t,r)=>{const s=e.innerType._zod.run(t,r);return s instanceof Promise?s.then(i=>u0(i,n)):u0(s,n)}});function u0(n,e){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:e}),n}const xU=z("$ZodCatch",(n,e)=>{Et.init(n,e),n._zod.optin="optional",pt(n._zod,"optout",()=>e.innerType._zod.optout),pt(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);const s=e.innerType._zod.run(t,r);return s instanceof Promise?s.then(i=>(t.value=i.value,i.issues.length&&(t.value=e.catchValue({...t,error:{issues:i.issues.map(a=>Gs(a,r,qs()))},input:t.value}),t.issues=[],t.fallback=!0),t)):(t.value=s.value,s.issues.length&&(t.value=e.catchValue({...t,error:{issues:s.issues.map(i=>Gs(i,r,qs()))},input:t.value}),t.issues=[],t.fallback=!0),t)}}),OU=z("$ZodPipe",(n,e)=>{Et.init(n,e),pt(n._zod,"values",()=>e.in._zod.values),pt(n._zod,"optin",()=>e.in._zod.optin),pt(n._zod,"optout",()=>e.out._zod.optout),pt(n._zod,"propValues",()=>e.in._zod.propValues),n._zod.parse=(t,r)=>{if(r.direction==="backward"){const i=e.out._zod.run(t,r);return i instanceof Promise?i.then(a=>fd(a,e.in,r)):fd(i,e.in,r)}const s=e.in._zod.run(t,r);return s instanceof Promise?s.then(i=>fd(i,e.out,r)):fd(s,e.out,r)}});function fd(n,e,t){return n.issues.length?(n.aborted=!0,n):e._zod.run({value:n.value,issues:n.issues,fallback:n.fallback},t)}const CU=z("$ZodReadonly",(n,e)=>{Et.init(n,e),pt(n._zod,"propValues",()=>e.innerType._zod.propValues),pt(n._zod,"values",()=>e.innerType._zod.values),pt(n._zod,"optin",()=>{var t,r;return(r=(t=e.innerType)==null?void 0:t._zod)==null?void 0:r.optin}),pt(n._zod,"optout",()=>{var t,r;return(r=(t=e.innerType)==null?void 0:t._zod)==null?void 0:r.optout}),n._zod.parse=(t,r)=>{if(r.direction==="backward")return e.innerType._zod.run(t,r);const s=e.innerType._zod.run(t,r);return s instanceof Promise?s.then(l0):l0(s)}});function l0(n){return n.value=Object.freeze(n.value),n}const $U=z("$ZodCustom",(n,e)=>{Yn.init(n,e),Et.init(n,e),n._zod.parse=(t,r)=>t,n._zod.check=t=>{const r=t.value,s=e.fn(r);if(s instanceof Promise)return s.then(i=>d0(i,t,r,n));d0(s,t,r,n)}});function d0(n,e,t,r){if(!n){const s={code:"custom",input:t,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(qu(s))}}var h0;class RU{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const s={...r,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function PU(){return new RU}(h0=globalThis).__zod_globalRegistry??(h0.__zod_globalRegistry=PU());const sn=globalThis.__zod_globalRegistry;function NU(n,e){return new n({type:"string",...Ae(e)})}function MU(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...Ae(e)})}function f0(n,e){return new n({type:"string",format:"guid",check:"string_format",abort:!1,...Ae(e)})}function jU(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,...Ae(e)})}function LU(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ae(e)})}function DU(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ae(e)})}function UU(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ae(e)})}function zU(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...Ae(e)})}function FU(n,e){return new n({type:"string",format:"emoji",check:"string_format",abort:!1,...Ae(e)})}function BU(n,e){return new n({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ae(e)})}function HU(n,e){return new n({type:"string",format:"cuid",check:"string_format",abort:!1,...Ae(e)})}function VU(n,e){return new n({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ae(e)})}function ZU(n,e){return new n({type:"string",format:"ulid",check:"string_format",abort:!1,...Ae(e)})}function KU(n,e){return new n({type:"string",format:"xid",check:"string_format",abort:!1,...Ae(e)})}function WU(n,e){return new n({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ae(e)})}function qU(n,e){return new n({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ae(e)})}function GU(n,e){return new n({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ae(e)})}function JU(n,e){return new n({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ae(e)})}function YU(n,e){return new n({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ae(e)})}function XU(n,e){return new n({type:"string",format:"base64",check:"string_format",abort:!1,...Ae(e)})}function QU(n,e){return new n({type:"string",format:"base64url",check:"string_format",abort:!1,...Ae(e)})}function ez(n,e){return new n({type:"string",format:"e164",check:"string_format",abort:!1,...Ae(e)})}function tz(n,e){return new n({type:"string",format:"jwt",check:"string_format",abort:!1,...Ae(e)})}function nz(n,e){return new n({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ae(e)})}function rz(n,e){return new n({type:"string",format:"date",check:"string_format",...Ae(e)})}function sz(n,e){return new n({type:"string",format:"time",check:"string_format",precision:null,...Ae(e)})}function iz(n,e){return new n({type:"string",format:"duration",check:"string_format",...Ae(e)})}function az(n,e){return new n({type:"number",checks:[],...Ae(e)})}function oz(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...Ae(e)})}function cz(n,e){return new n({type:"boolean",...Ae(e)})}function uz(n){return new n({type:"any"})}function Wk(n){return new n({type:"unknown"})}function qk(n,e){return new n({type:"never",...Ae(e)})}function p0(n,e){return new Dk({check:"less_than",...Ae(e),value:n,inclusive:!1})}function cm(n,e){return new Dk({check:"less_than",...Ae(e),value:n,inclusive:!0})}function m0(n,e){return new Uk({check:"greater_than",...Ae(e),value:n,inclusive:!1})}function um(n,e){return new Uk({check:"greater_than",...Ae(e),value:n,inclusive:!0})}function g0(n,e){return new E4({check:"multiple_of",...Ae(e),value:n})}function Gk(n,e){return new I4({check:"max_length",...Ae(e),maximum:n})}function Vh(n,e){return new x4({check:"min_length",...Ae(e),minimum:n})}function Jk(n,e){return new O4({check:"length_equals",...Ae(e),length:n})}function lz(n,e){return new C4({check:"string_format",format:"regex",...Ae(e),pattern:n})}function dz(n){return new $4({check:"string_format",format:"lowercase",...Ae(n)})}function hz(n){return new R4({check:"string_format",format:"uppercase",...Ae(n)})}function fz(n,e){return new P4({check:"string_format",format:"includes",...Ae(e),includes:n})}function pz(n,e){return new N4({check:"string_format",format:"starts_with",...Ae(e),prefix:n})}function mz(n,e){return new M4({check:"string_format",format:"ends_with",...Ae(e),suffix:n})}function bc(n){return new j4({check:"overwrite",tx:n})}function gz(n){return bc(e=>e.normalize(n))}function _z(){return bc(n=>n.trim())}function yz(){return bc(n=>n.toLowerCase())}function wz(){return bc(n=>n.toUpperCase())}function bz(){return bc(n=>xD(n))}function vz(n,e,t){return new n({type:"array",element:e,...Ae(t)})}function Sz(n,e,t){const r=Ae(t);return r.abort??(r.abort=!0),new n({type:"custom",check:"custom",fn:e,...r})}function Az(n,e,t){return new n({type:"custom",check:"custom",fn:e,...Ae(t)})}function Tz(n,e){const t=Ez(r=>(r.addIssue=s=>{if(typeof s=="string")r.issues.push(qu(s,r.value,t._zod.def));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(qu(i))}},n(r.value,r)),e);return t}function Ez(n,e){const t=new Yn({check:"custom",...Ae(e)});return t._zod.check=n,t}function Zh(n){let e=(n==null?void 0:n.target)??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:n.processors??{},metadataRegistry:(n==null?void 0:n.metadata)??sn,target:e,unrepresentable:(n==null?void 0:n.unrepresentable)??"throw",override:(n==null?void 0:n.override)??(()=>{}),io:(n==null?void 0:n.io)??"output",counter:0,seen:new Map,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}}function Tt(n,e,t={path:[],schemaPath:[]}){var l,d;var r;const s=n._zod.def,i=e.seen.get(n);if(i)return i.count++,t.schemaPath.includes(n)&&(i.cycle=t.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:t.path};e.seen.set(n,a);const o=(d=(l=n._zod).toJSONSchema)==null?void 0:d.call(l);if(o)a.schema=o;else{const f={...t,schemaPath:[...t.schemaPath,n],path:t.path};if(n._zod.processJSONSchema)n._zod.processJSONSchema(e,a.schema,f);else{const m=a.schema,g=e.processors[s.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);g(n,e,m,f)}const h=n._zod.parent;h&&(a.ref||(a.ref=h),Tt(h,e,f),e.seen.get(h).isParent=!0)}const c=e.metadataRegistry.get(n);return c&&Object.assign(a.schema,c),e.io==="input"&&Rn(n)&&(delete a.schema.examples,delete a.schema.default),e.io==="input"&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,e.seen.get(n).schema}function Kh(n,e){var a,o,c,u;const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const l of n.seen.entries()){const d=(a=n.metadataRegistry.get(l[0]))==null?void 0:a.id;if(d){const f=r.get(d);if(f&&f!==l[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(d,l[0])}}const s=l=>{var g;const d=n.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const y=(g=n.external.registry.get(l[0]))==null?void 0:g.id,b=n.external.uri??(w=>w);if(y)return{ref:b(y)};const _=l[1].defId??l[1].schema.id??`schema${n.counter++}`;return l[1].defId=_,{defId:_,ref:`${b("__shared")}#/${d}/${_}`}}if(l[1]===t)return{ref:"#"};const h=`#/${d}/`,m=l[1].schema.id??`__schema${n.counter++}`;return{defId:m,ref:h+m}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:f,defId:h}=s(l);d.def={...d.schema},h&&(d.defId=h);const m=d.schema;for(const g in m)delete m[g];m.$ref=f};if(n.cycles==="throw")for(const l of n.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${(o=d.cycle)==null?void 0:o.join("/")}/<root>
|
|
133
|
+
|
|
134
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of n.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(n.external){const h=(c=n.external.registry.get(l[0]))==null?void 0:c.id;if(e!==l[0]&&h){i(l);continue}}if((u=n.metadataRegistry.get(l[0]))==null?void 0:u.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}}function Wh(n,e){var o,c,u,l;const t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=d=>{const f=n.seen.get(d);if(f.ref===null)return;const h=f.def??f.schema,m={...h},g=f.ref;if(f.ref=null,g){r(g);const b=n.seen.get(g),_=b.schema;if(_.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0")?(h.allOf=h.allOf??[],h.allOf.push(_)):Object.assign(h,_),Object.assign(h,m),d._zod.parent===g)for(const S in h)S==="$ref"||S==="allOf"||S in m||delete h[S];if(_.$ref&&b.def)for(const S in h)S==="$ref"||S==="allOf"||S in b.def&&JSON.stringify(h[S])===JSON.stringify(b.def[S])&&delete h[S]}const y=d._zod.parent;if(y&&y!==g){r(y);const b=n.seen.get(y);if(b!=null&&b.schema.$ref&&(h.$ref=b.schema.$ref,b.def))for(const _ in h)_==="$ref"||_==="allOf"||_ in b.def&&JSON.stringify(h[_])===JSON.stringify(b.def[_])&&delete h[_]}n.override({zodSchema:d,jsonSchema:h,path:f.path??[]})};for(const d of[...n.seen.entries()].reverse())r(d[0]);const s={};if(n.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":n.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":n.target==="draft-04"?s.$schema="http://json-schema.org/draft-04/schema#":n.target,(o=n.external)!=null&&o.uri){const d=(c=n.external.registry.get(e))==null?void 0:c.id;if(!d)throw new Error("Schema is missing an `id` property");s.$id=n.external.uri(d)}Object.assign(s,t.def??t.schema);const i=(u=n.metadataRegistry.get(e))==null?void 0:u.id;i!==void 0&&s.id===i&&delete s.id;const a=((l=n.external)==null?void 0:l.defs)??{};for(const d of n.seen.entries()){const f=d[1];f.def&&f.defId&&(f.def.id===f.defId&&delete f.def.id,a[f.defId]=f.def)}n.external||Object.keys(a).length>0&&(n.target==="draft-2020-12"?s.$defs=a:s.definitions=a);try{const d=JSON.parse(JSON.stringify(s));return Object.defineProperty(d,"~standard",{value:{...e["~standard"],jsonSchema:{input:qh(e,"input",n.processors),output:qh(e,"output",n.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function Rn(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const r=n._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Rn(r.element,t);if(r.type==="set")return Rn(r.valueType,t);if(r.type==="lazy")return Rn(r.getter(),t);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Rn(r.innerType,t);if(r.type==="intersection")return Rn(r.left,t)||Rn(r.right,t);if(r.type==="record"||r.type==="map")return Rn(r.keyType,t)||Rn(r.valueType,t);if(r.type==="pipe")return n._zod.traits.has("$ZodCodec")?!0:Rn(r.in,t)||Rn(r.out,t);if(r.type==="object"){for(const s in r.shape)if(Rn(r.shape[s],t))return!0;return!1}if(r.type==="union"){for(const s of r.options)if(Rn(s,t))return!0;return!1}if(r.type==="tuple"){for(const s of r.items)if(Rn(s,t))return!0;return!!(r.rest&&Rn(r.rest,t))}return!1}const kz=(n,e={})=>t=>{const r=Zh({...t,processors:e});return Tt(n,r),Kh(r,n),Wh(r,n)},qh=(n,e,t={})=>r=>{const{libraryOptions:s,target:i}=r??{},a=Zh({...s??{},target:i,io:e,processors:t});return Tt(n,a),Kh(a,n),Wh(a,n)},Iz={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Yk=(n,e,t,r)=>{const s=t;s.type="string";const{minimum:i,maximum:a,format:o,patterns:c,contentEncoding:u}=n._zod.bag;if(typeof i=="number"&&(s.minLength=i),typeof a=="number"&&(s.maxLength=a),o&&(s.format=Iz[o]??o,s.format===""&&delete s.format,o==="time"&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){const l=[...c];l.length===1?s.pattern=l[0].source:l.length>1&&(s.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Xk=(n,e,t,r)=>{const s=t,{minimum:i,maximum:a,format:o,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=n._zod.bag;typeof o=="string"&&o.includes("int")?s.type="integer":s.type="number";const d=typeof l=="number"&&l>=(i??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),h=e.target==="draft-04"||e.target==="openapi-3.0";d?h?(s.minimum=l,s.exclusiveMinimum=!0):s.exclusiveMinimum=l:typeof i=="number"&&(s.minimum=i),f?h?(s.maximum=u,s.exclusiveMaximum=!0):s.exclusiveMaximum=u:typeof a=="number"&&(s.maximum=a),typeof c=="number"&&(s.multipleOf=c)},Qk=(n,e,t,r)=>{t.type="boolean"},xz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Oz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Cz=(n,e,t,r)=>{e.target==="openapi-3.0"?(t.type="string",t.nullable=!0,t.enum=[null]):t.type="null"},$z=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Rz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},eI=(n,e,t,r)=>{t.not={}},tI=(n,e,t,r)=>{},nI=(n,e,t,r)=>{},Pz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},rI=(n,e,t,r)=>{const s=n._zod.def,i=Ek(s.entries);i.every(a=>typeof a=="number")&&(t.type="number"),i.every(a=>typeof a=="string")&&(t.type="string"),t.enum=i},sI=(n,e,t,r)=>{const s=n._zod.def,i=[];for(const a of s.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){const a=i[0];t.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?t.enum=[a]:t.const=a}else i.every(a=>typeof a=="number")&&(t.type="number"),i.every(a=>typeof a=="string")&&(t.type="string"),i.every(a=>typeof a=="boolean")&&(t.type="boolean"),i.every(a=>a===null)&&(t.type="null"),t.enum=i},Nz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Mz=(n,e,t,r)=>{const s=t,i=n._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=i.source},jz=(n,e,t,r)=>{const s=t,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:o,mime:c}=n._zod.bag;a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),c?c.length===1?(i.contentMediaType=c[0],Object.assign(s,i)):(Object.assign(s,i),s.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(s,i)},Lz=(n,e,t,r)=>{t.type="boolean"},iI=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Dz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},aI=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Uz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},zz=(n,e,t,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},oI=(n,e,t,r)=>{const s=t,i=n._zod.def,{minimum:a,maximum:o}=n._zod.bag;typeof a=="number"&&(s.minItems=a),typeof o=="number"&&(s.maxItems=o),s.type="array",s.items=Tt(i.element,e,{...r,path:[...r.path,"items"]})},cI=(n,e,t,r)=>{var u;const s=t,i=n._zod.def;s.type="object",s.properties={};const a=i.shape;for(const l in a)s.properties[l]=Tt(a[l],e,{...r,path:[...r.path,"properties",l]});const o=new Set(Object.keys(a)),c=new Set([...o].filter(l=>{const d=i.shape[l]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(s.required=Array.from(c)),((u=i.catchall)==null?void 0:u._zod.def.type)==="never"?s.additionalProperties=!1:i.catchall?i.catchall&&(s.additionalProperties=Tt(i.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(s.additionalProperties=!1)},uI=(n,e,t,r)=>{const s=n._zod.def,i=s.inclusive===!1,a=s.options.map((o,c)=>Tt(o,e,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?t.oneOf=a:t.anyOf=a},lI=(n,e,t,r)=>{const s=n._zod.def,i=Tt(s.left,e,{...r,path:[...r.path,"allOf",0]}),a=Tt(s.right,e,{...r,path:[...r.path,"allOf",1]}),o=u=>"allOf"in u&&Object.keys(u).length===1,c=[...o(i)?i.allOf:[i],...o(a)?a.allOf:[a]];t.allOf=c},dI=(n,e,t,r)=>{const s=t,i=n._zod.def;s.type="array";const a=e.target==="draft-2020-12"?"prefixItems":"items",o=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((f,h)=>Tt(f,e,{...r,path:[...r.path,a,h]})),u=i.rest?Tt(i.rest,e,{...r,path:[...r.path,o,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(s.prefixItems=c,u&&(s.items=u)):e.target==="openapi-3.0"?(s.items={anyOf:c},u&&s.items.anyOf.push(u),s.minItems=c.length,u||(s.maxItems=c.length)):(s.items=c,u&&(s.additionalItems=u));const{minimum:l,maximum:d}=n._zod.bag;typeof l=="number"&&(s.minItems=l),typeof d=="number"&&(s.maxItems=d)},hI=(n,e,t,r)=>{const s=t,i=n._zod.def;s.type="object";const a=i.keyType,o=a._zod.bag,c=o==null?void 0:o.patterns;if(i.mode==="loose"&&c&&c.size>0){const l=Tt(i.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(const d of c)s.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(s.propertyNames=Tt(i.keyType,e,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=Tt(i.valueType,e,{...r,path:[...r.path,"additionalProperties"]});const u=a._zod.values;if(u){const l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(s.required=l)}},fI=(n,e,t,r)=>{const s=n._zod.def,i=Tt(s.innerType,e,r),a=e.seen.get(n);e.target==="openapi-3.0"?(a.ref=s.innerType,t.nullable=!0):t.anyOf=[i,{type:"null"}]},pI=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType},mI=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType,t.default=JSON.parse(JSON.stringify(s.defaultValue))},gI=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},_I=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType;let a;try{a=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=a},yI=(n,e,t,r)=>{const s=n._zod.def,i=s.in._zod.traits.has("$ZodTransform"),a=e.io==="input"?i?s.out:s.in:s.out;Tt(a,e,r);const o=e.seen.get(n);o.ref=a},wI=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType,t.readOnly=!0},Fz=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType},Yy=(n,e,t,r)=>{const s=n._zod.def;Tt(s.innerType,e,r);const i=e.seen.get(n);i.ref=s.innerType},Bz=(n,e,t,r)=>{const s=n._zod.innerType;Tt(s,e,r);const i=e.seen.get(n);i.ref=s},_0={string:Yk,number:Xk,boolean:Qk,bigint:xz,symbol:Oz,null:Cz,undefined:$z,void:Rz,never:eI,any:tI,unknown:nI,date:Pz,enum:rI,literal:sI,nan:Nz,template_literal:Mz,file:jz,success:Lz,custom:iI,function:Dz,transform:aI,map:Uz,set:zz,array:oI,object:cI,union:uI,intersection:lI,tuple:dI,record:hI,nullable:fI,nonoptional:pI,default:mI,prefault:gI,catch:_I,pipe:yI,readonly:wI,promise:Fz,optional:Yy,lazy:Bz};function zg(n,e){if("_idmap"in n){const r=n,s=Zh({...e,processors:_0}),i={};for(const c of r._idmap.entries()){const[u,l]=c;Tt(l,s)}const a={},o={registry:r,uri:e==null?void 0:e.uri,defs:i};s.external=o;for(const c of r._idmap.entries()){const[u,l]=c;Kh(s,l),a[u]=Wh(s,l)}if(Object.keys(i).length>0){const c=s.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:i}}return{schemas:a}}const t=Zh({...e,processors:_0});return Tt(n,t),Kh(t,n),Wh(t,n)}function It(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_zod"in e))return!1;const t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function Ht(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function Hz(n){return It(n)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Ht(n)}function Xt(n){return!n||typeof n!="object"||Array.isArray(n)?!1:!!(It(n)||Ht(n))}function bI(n){return typeof n=="object"&&n!==null&&"_def"in n&&typeof n._def=="object"&&n._def!==null&&"typeName"in n._def&&n._def.typeName==="ZodLiteral"}function vI(n){return It(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="literal":!1}function Vz(n){return!!(bI(n)||vI(n))}async function tp(n,e){if(It(n))try{return{success:!0,data:await Rk(n,e)}}catch(t){return{success:!1,error:t}}if(Ht(n))return await n.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function np(n,e){if(It(n))return await Rk(n,e);if(Ht(n))return await n.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Zz(n,e){if(It(n))try{return{success:!0,data:Gf(n,e)}}catch(t){return{success:!1,error:t}}if(Ht(n))return n.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function so(n,e){if(It(n))return Gf(n,e);if(Ht(n))return n.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function tc(n){var e;if(It(n))return(e=sn.get(n))==null?void 0:e.description;if(Ht(n)||"description"in n&&typeof n.description=="string")return n.description}function Kz(n){if(!Xt(n))return!1;if(Ht(n)){const e=n._def;if(e.typeName==="ZodObject"){const t=n;return!t.shape||Object.keys(t.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(It(n)){const e=n._zod.def;if(e.type==="object"){const t=n;return!t.shape||Object.keys(t.shape).length===0}if(e.type==="record")return!0}return typeof n=="object"&&n!==null&&!("shape"in n)}function Xy(n){return Xt(n)?Ht(n)?n._def.typeName==="ZodString":It(n)?n._zod.def.type==="string":!1:!1}function rp(n){return typeof n=="object"&&n!==null&&"_def"in n&&typeof n._def=="object"&&n._def!==null&&"typeName"in n._def&&n._def.typeName==="ZodObject"}function ws(n){return It(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="object":!1}function sp(n){return It(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="array":!1}function SI(n){return It(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="optional":!1}function AI(n){return It(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="nullable":!1}function ir(n){return!!(rp(n)||ws(n))}function nc(n){if(Ht(n))return n.shape;if(It(n))return n._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function TI(n,e){if(Ht(n))return n.extend(e);if(It(n))return xk(n,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function xu(n){if(Ht(n))return n.partial();if(It(n))return Ok(ep,n,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Gh(n,e=!1){if(rp(n))return n.strict();if(ws(n)){const t=n._zod.def.shape;if(e)for(const[i,a]of Object.entries(n._zod.def.shape)){if(ws(a))t[i]=Gh(a,e);else if(sp(a)){let c=a._zod.def.element;ws(c)&&(c=Gh(c,e)),t[i]=pn(a,{...a._zod.def,element:c})}else t[i]=a;const o=sn.get(a);o&&sn.add(t[i],o)}const r=pn(n,{...n._zod.def,shape:t,catchall:qk(Hk)}),s=sn.get(n);return s&&sn.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Fg(n,e=!1){if(rp(n))return n.passthrough();if(ws(n)){const t=n._zod.def.shape;if(e)for(const[i,a]of Object.entries(n._zod.def.shape)){if(ws(a))t[i]=Fg(a,e);else if(sp(a)){let c=a._zod.def.element;ws(c)&&(c=Fg(c,e)),t[i]=pn(a,{...a._zod.def,element:c})}else t[i]=a;const o=sn.get(a);o&&sn.add(t[i],o)}const r=pn(n,{...n._zod.def,shape:t,catchall:Wk(Bk)}),s=sn.get(n);return s&&sn.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Wz(n){if(Ht(n))try{const e=n.parse(void 0);return()=>e}catch{return}if(It(n))try{const e=Gf(n,void 0);return()=>e}catch{return}}function qz(n){return Ht(n)&&"typeName"in n._def&&n._def.typeName==="ZodEffects"}function Gz(n){return It(n)&&n._zod.def.type==="pipe"}function Xi(n,e,t){const r=t.get(n);if(r!==void 0)return r;if(Ht(n))return qz(n)?Xi(n._def.schema,e,t):n;if(It(n)){let s=n;if(Gz(n)&&(s=Xi(n._zod.def.in,e,t)),e){if(ws(s)){const a={};for(const[o,c]of Object.entries(s._zod.def.shape))a[o]=Xi(c,e,t);s=pn(s,{...s._zod.def,shape:a})}else if(sp(s)){const a=Xi(s._zod.def.element,e,t);s=pn(s,{...s._zod.def,element:a})}else if(SI(s)){const a=Xi(s._zod.def.innerType,e,t);s=pn(s,{...s._zod.def,innerType:a})}else if(AI(s)){const a=Xi(s._zod.def.innerType,e,t);s=pn(s,{...s._zod.def,innerType:a})}}const i=sn.get(n);return i&&sn.add(s,i),t.set(n,s),s}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function EI(n,e=!1){return Xi(n,e,new WeakMap)}function Jz(n,e){if(Ht(n)){const t=nc(n),r={};for(const[s,i]of Object.entries(t))e(s,i)?r[s]=i.optional():r[s]=i;return n.extend(r)}if(It(n)){const t=nc(n),r={...n._zod.def.shape};for(const[a,o]of Object.entries(t))e(a,o)&&(r[a]=new ep({type:"optional",innerType:o}));const s=pn(n,{...n._zod.def,shape:r}),i=sn.get(n);return i&&sn.add(s,i),s}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function kI(n){return n instanceof Error&&(n.constructor.name==="ZodError"||n.constructor.name==="$ZodError")}function lm(n){return n.replace(/[^a-zA-Z-_0-9]/g,"_")}const Yz=["*","_","`"];function Xz(n){let e="";for(const[t,r]of Object.entries(n))e+=` classDef ${t} ${r};
|
|
135
|
+
`;return e}function Qz(n,e,t){const{firstNode:r,lastNode:s,nodeColors:i,withStyles:a=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=t??{};let u=a?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
136
|
+
graph TD;
|
|
137
|
+
`:`graph TD;
|
|
138
|
+
`;if(a){const m="default",g={[m]:"{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(n)){const _=b.name.split(":").pop()??"";let w=Yz.some(T=>_.startsWith(T)&&_.endsWith(T))?`<p>${_}</p>`:_;Object.keys(b.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([T,A])=>`${T} = ${A}`).join(`
|
|
139
|
+
`)}</em></small>`);const S=(g[y]??g[m]).replace("{0}",lm(y)).replace("{1}",w);u+=` ${S}
|
|
140
|
+
`}}const l={};for(const m of e){const g=m.source.split(":"),y=m.target.split(":"),b=g.filter((_,w)=>_===y[w]).join(":");l[b]||(l[b]=[]),l[b].push(m)}const d=new Set;function f(m){return[...m].sort((g,y)=>g.split(":").length-y.split(":").length)}function h(m,g){const y=m.length===1&&m[0].source===m[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 ${_}
|
|
141
|
+
`}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 m){const{source:w,target:S,data:T,conditional:A}=_;let I="";if(T!==void 0){let k=T;const R=k.split(" ");R.length>c&&(k=Array.from({length:Math.ceil(R.length/c)},(x,O)=>R.slice(O*c,(O+1)*c).join(" ")).join(" <br> ")),I=A?` -. ${k} .-> `:` -- ${k} --> `}else I=A?" -.-> ":" --> ";u+=` ${lm(w)}${I}${lm(S)};
|
|
142
|
+
`}g&&!y&&(u+=` end
|
|
143
|
+
`)}h(l[""]??[],"");for(const m in l)!m.includes(":")&&m!==""&&h(l[m],m);return a&&(u+=Xz(i??{})),u}async function eF(n,e){let t=(e==null?void 0:e.backgroundColor)??"white";const r=(e==null?void 0:e.imageType)??"png",s=kD(n);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const i=`https://mermaid.ink/img/${s}?bgColor=${t}&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(`
|
|
144
|
+
`));return await a.blob()}const tF=Symbol("Let zodToJsonSchema decide on which parser to use"),nF={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"},rF=n=>({...nF,...n}),sF=n=>{const e=rF(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,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}]))}},II=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")};function qn(n){if(n.target!=="openAi")return{};const e=[...n.basePath,n.definitionPath,n.openAiAnyTypeName];return n.flags.hasReferencedOpenAiAnyType=!0,{$ref:n.$refStrategy==="relative"?II(e,n.currentPath):e.join("/")}}function xI(n,e,t,r){r!=null&&r.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function ht(n,e,t,r,s){n[e]=t,xI(n,e,r,s)}var at;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},n.getValidEnumValues=s=>{const i=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return n.objectValues(a)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.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},n.find=(s,i)=>{for(const a of s)if(i(a))return a},n.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)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(at||(at={}));var y0;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(y0||(y0={}));const ye=at.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),di=n=>{switch(typeof n){case"undefined":return ye.undefined;case"string":return ye.string;case"number":return Number.isNaN(n)?ye.nan:ye.number;case"boolean":return ye.boolean;case"function":return ye.function;case"bigint":return ye.bigint;case"symbol":return ye.symbol;case"object":return Array.isArray(n)?ye.array:n===null?ye.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ye.promise:typeof Map<"u"&&n instanceof Map?ye.map:typeof Set<"u"&&n instanceof Set?ye.set:typeof Date<"u"&&n instanceof Date?ye.date:ye.object;default:return ye.unknown}},G=at.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"]);let xa=class OI 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=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(t(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(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof OI))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,at.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t=Object.create(null),r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};xa.create=n=>new xa(n);const Bg=(n,e)=>{let t;switch(n.code){case G.invalid_type:n.received===ye.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case G.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,at.jsonStringifyReplacer)}`;break;case G.unrecognized_keys:t=`Unrecognized key(s) in object: ${at.joinValues(n.keys,", ")}`;break;case G.invalid_union:t="Invalid input";break;case G.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${at.joinValues(n.options)}`;break;case G.invalid_enum_value:t=`Invalid enum value. Expected ${at.joinValues(n.options)}, received '${n.received}'`;break;case G.invalid_arguments:t="Invalid function arguments";break;case G.invalid_return_type:t="Invalid function return type";break;case G.invalid_date:t="Invalid date";break;case G.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:at.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case G.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case G.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case G.custom:t="Invalid input";break;case G.invalid_intersection_types:t="Intersection results could not be merged";break;case G.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case G.not_finite:t="Number must be finite";break;default:t=e.defaultError,at.assertNever(n)}return{message:t}};let iF=Bg;function aF(){return iF}const oF=n=>{const{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...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 ue(n,e){const t=aF(),r=oF({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Bg?void 0:Bg].filter(s=>!!s)});n.common.issues.push(r)}let Yr=class CI{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if(s.status==="aborted")return je;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return CI.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return je;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 je=Object.freeze({status:"aborted"}),ru=n=>({status:"dirty",value:n}),Cr=n=>({status:"valid",value:n}),w0=n=>n.status==="aborted",b0=n=>n.status==="dirty",rc=n=>n.status==="valid",Jh=n=>typeof Promise<"u"&&n instanceof Promise;var ve;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(ve||(ve={}));let ji=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,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 v0=(n,e)=>{if(rc(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new xa(n.common.issues);return this._error=t,this._error}}};function We(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||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}=n;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??t??o.defaultError}},description:s}}let st=class{get description(){return this._def.description}_getType(e){return di(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:di(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Yr,ctx:{common:e.parent.common,data:e.data,parsedType:di(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Jh(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:di(e)},s=this._parseSync({data:e,path:r.path,parent:r});return v0(r,s)}"~validate"(e){var r,s;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:di(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return rc(i)?{value:i.value}:{issues:t.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),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>rc(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:di(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Jh(s)?s:Promise.resolve(s));return v0(r,i)}refine(e,t){const r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:G.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new ic({schema:this,typeName:D.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:t=>this["~validate"](t)}}optional(){return Ii.create(this,this._def)}nullable(){return ac.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sc.create(this)}promise(){return Qh.create(this,this._def)}or(e){return Yh.create([this,e],this._def)}and(e){return Xh.create(this,e,this._def)}transform(e){return new ic({...We(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Jg({...We(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new CF({typeName:D.ZodBranded,type:this,...We(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Yg({...We(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return $F.create(this,e)}readonly(){return Xg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cF=/^c[^\s-]{8,}$/i,uF=/^[0-9a-z]+$/,lF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dF=/^[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,hF=/^[a-z0-9_-]{21}$/i,fF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pF=/^[-+]?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)?)??$/,mF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let dm;const _F=/^(?:(?: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])$/,yF=/^(?:(?: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])$/,wF=/^(([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]))$/,bF=/^(([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])$/,vF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,SF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$I="((\\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])))",AF=new RegExp(`^${$I}$`);function RI(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function TF(n){return new RegExp(`^${RI(n)}$`)}function EF(n){let e=`${$I}T${RI(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function kF(n,e){return!!((e==="v4"||!e)&&_F.test(n)||(e==="v6"||!e)&&wF.test(n))}function IF(n,e){if(!fF.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.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 xF(n,e){return!!((e==="v4"||!e)&&yF.test(n)||(e==="v6"||!e)&&bF.test(n))}let Hg=class su extends st{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ye.string){const i=this._getOrReturnCtx(e);return ue(i,{code:G.invalid_type,expected:ye.string,received:i.parsedType}),je}const r=new Yr;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),ue(s,{code:G.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),ue(s,{code:G.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?ue(s,{code:G.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&ue(s,{code:G.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")mF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"email",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")dm||(dm=new RegExp(gF,"u")),dm.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"emoji",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")dF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"uuid",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")hF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"nanoid",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")cF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"cuid",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")uF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"cuid2",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")lF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"ulid",code:G.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ue(s,{validation:"url",code:G.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),ue(s,{validation:"regex",code:G.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),ue(s,{code:G.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),ue(s,{code:G.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),ue(s,{code:G.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?EF(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{code:G.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?AF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{code:G.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?TF(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{code:G.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?pF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"duration",code:G.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?kF(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"ip",code:G.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?IF(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"jwt",code:G.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?xF(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"cidr",code:G.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?vF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"base64",code:G.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?SF.test(e.data)||(s=this._getOrReturnCtx(e,s),ue(s,{validation:"base64url",code:G.invalid_string,message:i.message}),r.dirty()):at.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:G.invalid_string,...ve.errToObj(r)})}_addCheck(e){return new su({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ve.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ve.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ve.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ve.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ve.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ve.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ve.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ve.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ve.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ve.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ve.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ve.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ve.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,...ve.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,...ve.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...ve.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ve.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...ve.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ve.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ve.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ve.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ve.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ve.errToObj(t)})}nonempty(e){return this.min(1,ve.errToObj(e))}trim(){return new su({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new su({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new su({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Hg.create=n=>new Hg({checks:[],typeName:D.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...We(n)});function OF(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}let S0=class Vg extends st{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)!==ye.number){const i=this._getOrReturnCtx(e);return ue(i,{code:G.invalid_type,expected:ye.number,received:i.parsedType}),je}let r;const s=new Yr;for(const i of this._def.checks)i.kind==="int"?at.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ue(r,{code:G.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),ue(r,{code:G.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),ue(r,{code:G.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?OF(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),ue(r,{code:G.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ue(r,{code:G.not_finite,message:i.message}),s.dirty()):at.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ve.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ve.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ve.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ve.toString(t))}setLimit(e,t,r,s){return new Vg({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ve.toString(s)}]})}_addCheck(e){return new Vg({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ve.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ve.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ve.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ve.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ve.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ve.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ve.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ve.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ve.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&at.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};S0.create=n=>new S0({checks:[],typeName:D.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...We(n)});let A0=class Zg extends st{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)!==ye.bigint)return this._getInvalidInput(e);let r;const s=new Yr;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),ue(r,{code:G.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),ue(r,{code:G.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),ue(r,{code:G.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):at.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return ue(t,{code:G.invalid_type,expected:ye.bigint,received:t.parsedType}),je}gte(e,t){return this.setLimit("min",e,!0,ve.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ve.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ve.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ve.toString(t))}setLimit(e,t,r,s){return new Zg({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ve.toString(s)}]})}_addCheck(e){return new Zg({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ve.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ve.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ve.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ve.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ve.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};A0.create=n=>new A0({checks:[],typeName:D.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...We(n)});let T0=class extends st{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ye.boolean){const r=this._getOrReturnCtx(e);return ue(r,{code:G.invalid_type,expected:ye.boolean,received:r.parsedType}),je}return Cr(e.data)}};T0.create=n=>new T0({typeName:D.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...We(n)});let E0=class PI extends st{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ye.date){const i=this._getOrReturnCtx(e);return ue(i,{code:G.invalid_type,expected:ye.date,received:i.parsedType}),je}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return ue(i,{code:G.invalid_date}),je}const r=new Yr;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),ue(s,{code:G.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),ue(s,{code:G.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):at.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new PI({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ve.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ve.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};E0.create=n=>new E0({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:D.ZodDate,...We(n)});let k0=class extends st{_parse(e){if(this._getType(e)!==ye.symbol){const r=this._getOrReturnCtx(e);return ue(r,{code:G.invalid_type,expected:ye.symbol,received:r.parsedType}),je}return Cr(e.data)}};k0.create=n=>new k0({typeName:D.ZodSymbol,...We(n)});let I0=class extends st{_parse(e){if(this._getType(e)!==ye.undefined){const r=this._getOrReturnCtx(e);return ue(r,{code:G.invalid_type,expected:ye.undefined,received:r.parsedType}),je}return Cr(e.data)}};I0.create=n=>new I0({typeName:D.ZodUndefined,...We(n)});let x0=class extends st{_parse(e){if(this._getType(e)!==ye.null){const r=this._getOrReturnCtx(e);return ue(r,{code:G.invalid_type,expected:ye.null,received:r.parsedType}),je}return Cr(e.data)}};x0.create=n=>new x0({typeName:D.ZodNull,...We(n)});let Kg=class extends st{constructor(){super(...arguments),this._any=!0}_parse(e){return Cr(e.data)}};Kg.create=n=>new Kg({typeName:D.ZodAny,...We(n)});let O0=class extends st{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Cr(e.data)}};O0.create=n=>new O0({typeName:D.ZodUnknown,...We(n)});let Li=class extends st{_parse(e){const t=this._getOrReturnCtx(e);return ue(t,{code:G.invalid_type,expected:ye.never,received:t.parsedType}),je}};Li.create=n=>new Li({typeName:D.ZodNever,...We(n)});let C0=class extends st{_parse(e){if(this._getType(e)!==ye.undefined){const r=this._getOrReturnCtx(e);return ue(r,{code:G.invalid_type,expected:ye.void,received:r.parsedType}),je}return Cr(e.data)}};C0.create=n=>new C0({typeName:D.ZodVoid,...We(n)});let sc=class th extends st{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==ye.array)return ue(t,{code:G.invalid_type,expected:ye.array,received:t.parsedType}),je;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(ue(t,{code:a?G.too_big:G.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&&t.data.length<s.minLength.value&&(ue(t,{code:G.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(ue(t,{code:G.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new ji(t,a,t.path,o)))).then(a=>Yr.mergeArray(r,a));const i=[...t.data].map((a,o)=>s.type._parseSync(new ji(t,a,t.path,o)));return Yr.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new th({...this._def,minLength:{value:e,message:ve.toString(t)}})}max(e,t){return new th({...this._def,maxLength:{value:e,message:ve.toString(t)}})}length(e,t){return new th({...this._def,exactLength:{value:e,message:ve.toString(t)}})}nonempty(e){return this.min(1,e)}};sc.create=(n,e)=>new sc({type:n,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...We(e)});function io(n){if(n instanceof Js){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=Ii.create(io(r))}return new Js({...n._def,shape:()=>e})}else return n instanceof sc?new sc({...n._def,type:io(n.element)}):n instanceof Ii?Ii.create(io(n.unwrap())):n instanceof ac?ac.create(io(n.unwrap())):n instanceof Gu?Gu.create(n.items.map(e=>io(e))):n}let Js=class zr extends st{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(),t=at.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ye.object){const u=this._getOrReturnCtx(e);return ue(u,{code:G.invalid_type,expected:ye.object,received:u.parsedType}),je}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Li&&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 ji(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Li){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&&(ue(s,{code:G.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 ji(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=>Yr.mergeObjectSync(r,u)):Yr.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return ve.errToObj,new zr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var i,a;const s=((a=(i=this._def).errorMap)==null?void 0:a.call(i,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:ve.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new zr({...this._def,unknownKeys:"strip"})}passthrough(){return new zr({...this._def,unknownKeys:"passthrough"})}extend(e){return new zr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new zr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new zr({...this._def,catchall:e})}pick(e){const t={};for(const r of at.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new zr({...this._def,shape:()=>t})}omit(e){const t={};for(const r of at.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new zr({...this._def,shape:()=>t})}deepPartial(){return io(this)}partial(e){const t={};for(const r of at.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new zr({...this._def,shape:()=>t})}required(e){const t={};for(const r of at.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ii;)i=i._def.innerType;t[r]=i}return new zr({...this._def,shape:()=>t})}keyof(){return MI(at.objectKeys(this.shape))}};Js.create=(n,e)=>new Js({shape:()=>n,unknownKeys:"strip",catchall:Li.create(),typeName:D.ZodObject,...We(e)});Js.strictCreate=(n,e)=>new Js({shape:()=>n,unknownKeys:"strict",catchall:Li.create(),typeName:D.ZodObject,...We(e)});Js.lazycreate=(n,e)=>new Js({shape:n,unknownKeys:"strip",catchall:Li.create(),typeName:D.ZodObject,...We(e)});let Yh=class extends st{_parse(e){const{ctx:t}=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 t.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new xa(o.ctx.common.issues));return ue(t,{code:G.invalid_union,unionErrors:a}),je}if(t.common.async)return Promise.all(r.map(async i=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of r){const u={...t,common:{...t.common,issues:[]},parent:null},l=c._parseSync({data:t.data,path:t.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 t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new xa(c));return ue(t,{code:G.invalid_union,unionErrors:o}),je}}get options(){return this._def.options}};Yh.create=(n,e)=>new Yh({options:n,typeName:D.ZodUnion,...We(e)});function Wg(n,e){const t=di(n),r=di(e);if(n===e)return{valid:!0,data:n};if(t===ye.object&&r===ye.object){const s=at.objectKeys(e),i=at.objectKeys(n).filter(o=>s.indexOf(o)!==-1),a={...n,...e};for(const o of i){const c=Wg(n[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===ye.array&&r===ye.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<n.length;i++){const a=n[i],o=e[i],c=Wg(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===ye.date&&r===ye.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}let Xh=class extends st{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(w0(i)||w0(a))return je;const o=Wg(i.value,a.value);return o.valid?((b0(i)||b0(a))&&t.dirty(),{status:t.value,value:o.data}):(ue(r,{code:G.invalid_intersection_types}),je)};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}))}};Xh.create=(n,e,t)=>new Xh({left:n,right:e,typeName:D.ZodIntersection,...We(t)});let Gu=class NI extends st{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ye.array)return ue(r,{code:G.invalid_type,expected:ye.array,received:r.parsedType}),je;if(r.data.length<this._def.items.length)return ue(r,{code:G.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),je;!this._def.rest&&r.data.length>this._def.items.length&&(ue(r,{code:G.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...r.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new ji(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Yr.mergeArray(t,a)):Yr.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new NI({...this._def,rest:e})}};Gu.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gu({items:n,typeName:D.ZodTuple,rest:null,...We(e)})};let $0=class extends st{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ye.map)return ue(r,{code:G.invalid_type,expected:ye.map,received:r.parsedType}),je;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new ji(r,o,r.path,[u,"key"])),value:i._parse(new ji(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 je;(u.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(u.value,l.value)}return{status:t.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 je;(u.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(u.value,l.value)}return{status:t.value,value:o}}}};$0.create=(n,e,t)=>new $0({valueType:e,keyType:n,typeName:D.ZodMap,...We(t)});let R0=class qg extends st{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ye.set)return ue(r,{code:G.invalid_type,expected:ye.set,received:r.parsedType}),je;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ue(r,{code:G.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ue(r,{code:G.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const l of c){if(l.status==="aborted")return je;l.status==="dirty"&&t.dirty(),u.add(l.value)}return{status:t.value,value:u}}const o=[...r.data.values()].map((c,u)=>i._parse(new ji(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new qg({...this._def,minSize:{value:e,message:ve.toString(t)}})}max(e,t){return new qg({...this._def,maxSize:{value:e,message:ve.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};R0.create=(n,e)=>new R0({valueType:n,minSize:null,maxSize:null,typeName:D.ZodSet,...We(e)});let P0=class extends st{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};P0.create=(n,e)=>new P0({getter:n,typeName:D.ZodLazy,...We(e)});let N0=class extends st{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return ue(t,{received:t.data,code:G.invalid_literal,expected:this._def.value}),je}return{status:"valid",value:e.data}}get value(){return this._def.value}};N0.create=(n,e)=>new N0({value:n,typeName:D.ZodLiteral,...We(e)});function MI(n,e){return new Qy({values:n,typeName:D.ZodEnum,...We(e)})}let Qy=class Gg extends st{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return ue(t,{expected:at.joinValues(r),received:t.parsedType,code:G.invalid_type}),je}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return ue(t,{received:t.data,code:G.invalid_enum_value,options:r}),je}return Cr(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Gg.create(e,{...this._def,...t})}exclude(e,t=this._def){return Gg.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};Qy.create=MI;let M0=class extends st{_parse(e){const t=at.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ye.string&&r.parsedType!==ye.number){const s=at.objectValues(t);return ue(r,{expected:at.joinValues(s),received:r.parsedType,code:G.invalid_type}),je}if(this._cache||(this._cache=new Set(at.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=at.objectValues(t);return ue(r,{received:r.data,code:G.invalid_enum_value,options:s}),je}return Cr(e.data)}get enum(){return this._def.values}};M0.create=(n,e)=>new M0({values:n,typeName:D.ZodNativeEnum,...We(e)});let Qh=class extends st{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ye.promise&&t.common.async===!1)return ue(t,{code:G.invalid_type,expected:ye.promise,received:t.parsedType}),je;const r=t.parsedType===ye.promise?t.data:Promise.resolve(t.data);return Cr(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Qh.create=(n,e)=>new Qh({type:n,typeName:D.ZodPromise,...We(e)});let ic=class extends st{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{ue(r,a),a.fatal?t.abort():t.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(t.value==="aborted")return je;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?je:c.status==="dirty"||t.value==="dirty"?ru(c.value):c});{if(t.value==="aborted")return je;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?je:o.status==="dirty"||t.value==="dirty"?ru(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"?je:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?je:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.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(!rc(a))return je;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:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>rc(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:t.value,value:o})):je);at.assertNever(s)}};ic.create=(n,e,t)=>new ic({schema:n,typeName:D.ZodEffects,effect:e,...We(t)});ic.createWithPreprocess=(n,e,t)=>new ic({schema:e,effect:{type:"preprocess",transform:n},typeName:D.ZodEffects,...We(t)});let Ii=class extends st{_parse(e){return this._getType(e)===ye.undefined?Cr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ii.create=(n,e)=>new Ii({innerType:n,typeName:D.ZodOptional,...We(e)});let ac=class extends st{_parse(e){return this._getType(e)===ye.null?Cr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ac.create=(n,e)=>new ac({innerType:n,typeName:D.ZodNullable,...We(e)});let Jg=class extends st{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ye.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Jg.create=(n,e)=>new Jg({innerType:n,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...We(e)});let Yg=class extends st{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Jh(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new xa(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Yg.create=(n,e)=>new Yg({innerType:n,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...We(e)});let j0=class extends st{_parse(e){if(this._getType(e)!==ye.nan){const r=this._getOrReturnCtx(e);return ue(r,{code:G.invalid_type,expected:ye.nan,received:r.parsedType}),je}return{status:"valid",value:e.data}}};j0.create=n=>new j0({typeName:D.ZodNaN,...We(n)});let CF=class extends st{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},$F=class jI extends st{_parse(e){const{status:t,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"?je:i.status==="dirty"?(t.dirty(),ru(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"?je:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new jI({in:e,out:t,typeName:D.ZodPipeline})}},Xg=class extends st{_parse(e){const t=this._def.innerType._parse(e),r=s=>(rc(s)&&(s.value=Object.freeze(s.value)),s);return Jh(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};Xg.create=(n,e)=>new Xg({innerType:n,typeName:D.ZodReadonly,...We(e)});var D;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(D||(D={}));const ip=Hg.create,L0=Kg.create;Li.create;sc.create;const ap=Js.create;Yh.create;Xh.create;Gu.create;Qy.create;Qh.create;Ii.create;ac.create;function RF(n,e){var r,s,i;const t={type:"array"};return(r=n.type)!=null&&r._def&&((i=(s=n.type)==null?void 0:s._def)==null?void 0:i.typeName)!==D.ZodAny&&(t.items=lt(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&ht(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&ht(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(ht(t,"minItems",n.exactLength.value,n.exactLength.message,e),ht(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function PF(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ht(t,"minimum",r.value,r.message,e):ht(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),ht(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ht(t,"maximum",r.value,r.message,e):ht(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),ht(t,"maximum",r.value,r.message,e));break;case"multipleOf":ht(t,"multipleOf",r.value,r.message,e);break}return t}function NF(){return{type:"boolean"}}function LI(n,e){return lt(n.type._def,e)}const MF=(n,e)=>lt(n.innerType._def,e);function DI(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(s=>DI(n,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 jF(n,e)}}const jF=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":ht(t,"minimum",r.value,r.message,e);break;case"max":ht(t,"maximum",r.value,r.message,e);break}return t};function LF(n,e){return{...lt(n.innerType._def,e),default:n.defaultValue()}}function DF(n,e){return e.effectStrategy==="input"?lt(n.schema._def,e):qn(e)}function UF(n){return{type:"string",enum:Array.from(n.values)}}const zF=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function FF(n,e){const t=[lt(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),lt(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(i=>{if(zF(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 BF(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let hm;const Mr={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:()=>(hm===void 0&&(hm=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hm),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 UI(n,e){const t={type:"string"};if(n.checks)for(const r of n.checks)switch(r.kind){case"min":ht(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":ht(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":jr(t,"email",r.message,e);break;case"format:idn-email":jr(t,"idn-email",r.message,e);break;case"pattern:zod":On(t,Mr.email,r.message,e);break}break;case"url":jr(t,"uri",r.message,e);break;case"uuid":jr(t,"uuid",r.message,e);break;case"regex":On(t,r.regex,r.message,e);break;case"cuid":On(t,Mr.cuid,r.message,e);break;case"cuid2":On(t,Mr.cuid2,r.message,e);break;case"startsWith":On(t,RegExp(`^${fm(r.value,e)}`),r.message,e);break;case"endsWith":On(t,RegExp(`${fm(r.value,e)}$`),r.message,e);break;case"datetime":jr(t,"date-time",r.message,e);break;case"date":jr(t,"date",r.message,e);break;case"time":jr(t,"time",r.message,e);break;case"duration":jr(t,"duration",r.message,e);break;case"length":ht(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),ht(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":On(t,RegExp(fm(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&jr(t,"ipv4",r.message,e),r.version!=="v4"&&jr(t,"ipv6",r.message,e);break;case"base64url":On(t,Mr.base64url,r.message,e);break;case"jwt":On(t,Mr.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&On(t,Mr.ipv4Cidr,r.message,e),r.version!=="v4"&&On(t,Mr.ipv6Cidr,r.message,e);break;case"emoji":On(t,Mr.emoji(),r.message,e);break;case"ulid":On(t,Mr.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":jr(t,"binary",r.message,e);break;case"contentEncoding:base64":ht(t,"contentEncoding","base64",r.message,e);break;case"pattern:zod":On(t,Mr.base64,r.message,e);break}break;case"nanoid":On(t,Mr.nanoid,r.message,e);break}return t}function fm(n,e){return e.patternStrategy==="escape"?VF(n):n}const HF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function VF(n){let e="";for(let t=0;t<n.length;t++)HF.has(n[t])||(e+="\\"),e+=n[t];return e}function jr(n,e,t,r){var s;n.format||(s=n.anyOf)!=null&&s.some(i=>i.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):ht(n,"format",e,t,r)}function On(n,e,t,r){var s;n.pattern||(s=n.allOf)!=null&&s.some(i=>i.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:D0(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):ht(n,"pattern",D0(e,r),t,r)}function D0(n,e){var c;if(!e.applyRegexFlags||!n.flags)return n.source;const t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.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(t.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(t.m){if(r[u]==="^"){s+=`(^|(?<=[\r
|
|
145
|
+
]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\r
|
|
146
|
+
]))`;continue}}if(t.s&&r[u]==="."){s+=a?`${r[u]}\r
|
|
147
|
+
`:`[${r[u]}\r
|
|
148
|
+
]`;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`),n.source}return s}function zI(n,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=n.keyType)==null?void 0:r._def.typeName)===D.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((u,l)=>({...u,[l]:lt(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",l]})??qn(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const t={type:"object",additionalProperties:lt(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(((s=n.keyType)==null?void 0:s._def.typeName)===D.ZodString&&((i=n.keyType._def.checks)!=null&&i.length)){const{type:u,...l}=UI(n.keyType._def,e);return{...t,propertyNames:l}}else{if(((a=n.keyType)==null?void 0:a._def.typeName)===D.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(((o=n.keyType)==null?void 0:o._def.typeName)===D.ZodBranded&&n.keyType._def.type._def.typeName===D.ZodString&&((c=n.keyType._def.type._def.checks)!=null&&c.length)){const{type:u,...l}=LI(n.keyType._def,e);return{...t,propertyNames:l}}}return t}function ZF(n,e){return e.mapStrategy==="record"?zI(n,e):{type:"array",maxItems:125,items:{type:"array",items:[lt(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||qn(e),lt(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||qn(e)],minItems:2,maxItems:2}}}function KF(n){const e=n.values,t=Object.keys(n.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),r=Array.from(new Set(t.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:t}}function WF(n){return n.target==="openAi"?void 0:{not:qn({...n,currentPath:[...n.currentPath,"not"]})}}function qF(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ef={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function GF(n,e){if(e.target==="openApi3")return U0(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in ef&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,i)=>{const a=ef[i._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.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===t.length){const s=r.filter((i,a,o)=>o.indexOf(i)===a);return{type:s.length>1?s:s[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(i=>!r.includes(i))],[])};return U0(n,e)}const U0=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>lt(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function JF(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:ef[n.innerType._def.typeName],nullable:!0}:{type:[ef[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=lt(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=lt(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function YF(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",xI(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ht(t,"minimum",r.value,r.message,e):ht(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),ht(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ht(t,"maximum",r.value,r.message,e):ht(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),ht(t,"maximum",r.value,r.message,e));break;case"multipleOf":ht(t,"multipleOf",r.value,r.message,e);break}return t}function XF(n,e){const t=e.target==="openAi",r={type:"object",properties:{}},s=[],i=n.shape();for(const o in i){let c=i[o];if(c===void 0||c._def===void 0)continue;let u=eB(c);u&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=lt(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=QF(n,e);return a!==void 0&&(r.additionalProperties=a),r}function QF(n,e){if(n.catchall._def.typeName!=="ZodNever")return lt(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function eB(n){try{return n.isOptional()}catch{return!0}}const tB=(n,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return lt(n.innerType._def,e);const t=lt(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:qn(e)},t]}:qn(e)},nB=(n,e)=>{if(e.pipeStrategy==="input")return lt(n.in._def,e);if(e.pipeStrategy==="output")return lt(n.out._def,e);const t=lt(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[t,lt(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]})].filter(r=>r!==void 0)}};function rB(n,e){return lt(n.type._def,e)}function sB(n,e){const t={type:"array",uniqueItems:!0,items:lt(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&ht(t,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&ht(t,"maxItems",n.maxSize.value,n.maxSize.message,e),t}function iB(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>lt(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:lt(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>lt(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function aB(n){return{not:qn(n)}}function oB(n){return qn(n)}const cB=(n,e)=>lt(n.innerType._def,e),uB=(n,e,t)=>{switch(e){case D.ZodString:return UI(n,t);case D.ZodNumber:return YF(n,t);case D.ZodObject:return XF(n,t);case D.ZodBigInt:return PF(n,t);case D.ZodBoolean:return NF();case D.ZodDate:return DI(n,t);case D.ZodUndefined:return aB(t);case D.ZodNull:return qF(t);case D.ZodArray:return RF(n,t);case D.ZodUnion:case D.ZodDiscriminatedUnion:return GF(n,t);case D.ZodIntersection:return FF(n,t);case D.ZodTuple:return iB(n,t);case D.ZodRecord:return zI(n,t);case D.ZodLiteral:return BF(n,t);case D.ZodEnum:return UF(n);case D.ZodNativeEnum:return KF(n);case D.ZodNullable:return JF(n,t);case D.ZodOptional:return tB(n,t);case D.ZodMap:return ZF(n,t);case D.ZodSet:return sB(n,t);case D.ZodLazy:return()=>n.getter()._def;case D.ZodPromise:return rB(n,t);case D.ZodNaN:case D.ZodNever:return WF(t);case D.ZodEffects:return DF(n,t);case D.ZodAny:return qn(t);case D.ZodUnknown:return oB(t);case D.ZodDefault:return LF(n,t);case D.ZodBranded:return LI(n,t);case D.ZodReadonly:return cB(n,t);case D.ZodCatch:return MF(n,t);case D.ZodPipeline:return nB(n,t);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(r=>{})()}};function lt(n,e,t=!1){var o;const r=e.seen.get(n);if(e.override){const c=(o=e.override)==null?void 0:o.call(e,n,e,r,t);if(c!==tF)return c}if(r&&!t){const c=lB(r,e);if(c!==void 0)return c}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const i=uB(n,n.typeName,e),a=typeof i=="function"?lt(i(),e):i;if(a&&dB(n,e,a),e.postProcess){const c=e.postProcess(a,n,e);return s.jsonSchema=a,c}return s.jsonSchema=a,a}const lB=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:II(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),qn(e)):e.$refStrategy==="seen"?qn(e):void 0}},dB=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),hB=(n,e)=>{const t=sF(e);let r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:lt(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,c]},!0)??qn(t)}),{}):void 0;const s=typeof e=="string"?e:e==null?void 0:e.name,i=lt(n._def,t,!1)??qn(t);t.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[t.openAiAnyTypeName]||(r[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const a=s===void 0?r?{...i,[t.definitionPath]:r}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:i}};return t.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),t.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 fB=he({isSerializableSchema:()=>Or,isStandardJsonSchema:()=>ew,isStandardSchema:()=>FI});function FI(n){return(typeof n=="object"||typeof n=="function")&&n!==null&&"~standard"in n&&typeof n["~standard"]=="object"&&n["~standard"]!==null&&"validate"in n["~standard"]}function ew(n){return(typeof n=="object"||typeof n=="function")&&n!==null&&"~standard"in n&&typeof n["~standard"]=="object"&&n["~standard"]!==null&&"jsonSchema"in n["~standard"]}function Or(n){return FI(n)&&ew(n)}function Sa(n,e){const t=typeof n;if(t!==typeof e)return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;const r=n.length;if(r!==e.length)return!1;for(let s=0;s<r;s++)if(!Sa(n[s],e[s]))return!1;return!0}if(t==="object"){if(!n||!e)return n===e;const r=Object.keys(n),s=Object.keys(e);if(r.length!==s.length)return!1;for(const a of r)if(!Sa(n[a],e[a]))return!1;return!0}return n===e}function Fr(n){return encodeURI(pB(n))}function pB(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}const mB={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},gB={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},_B={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 yB=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 wi(n,e=Object.create(null),t=yB,r=""){if(n&&typeof n=="object"&&!Array.isArray(n)){const i=n.$id||n.id;if(i){const a=new URL(i,t.href);a.hash.length>1?e[a.href]=n:(a.hash="",r===""?t=a:wi(n,e,t))}}else if(n!==!0&&n!==!1)return e;const s=t.href+(r?"#"+r:"");if(e[s]!==void 0)throw new Error(`Duplicate schema URI "${s}".`);if(e[s]=n,n===!0||n===!1)return e;if(n.__absolute_uri__===void 0&&Object.defineProperty(n,"__absolute_uri__",{enumerable:!1,value:s}),n.$ref&&n.__absolute_ref__===void 0){const i=new URL(n.$ref,t.href);i.hash=i.hash,Object.defineProperty(n,"__absolute_ref__",{enumerable:!1,value:i.href})}if(n.$recursiveRef&&n.__absolute_recursive_ref__===void 0){const i=new URL(n.$recursiveRef,t.href);i.hash=i.hash,Object.defineProperty(n,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(n.$anchor){const i=new URL("#"+n.$anchor,t.href);e[i.href]=n}for(let i in n){if(_B[i])continue;const a=`${r}/${Fr(i)}`,o=n[i];if(Array.isArray(o)){if(mB[i]){const c=o.length;for(let u=0;u<c;u++)wi(o[u],e,t,`${a}/${u}`)}}else if(gB[i])for(let c in o)wi(o[c],e,t,`${a}/${Fr(c)}`);else wi(o,e,t,a)}return e}const wB=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bB=[0,31,28,31,30,31,30,31,31,30,31,30,31],vB=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,SB=/^(?=.{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,AB=/^(?:[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,TB=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,EB=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,kB=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,IB=/^(?:\/(?:[^~/]|~0|~1)*)*$/,xB=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,OB=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,CB=n=>{if(n[0]==='"')return!1;const[e,t,...r]=n.split("@");return!e||!t||r.length!==0||e.length>64||t.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(t)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:t.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},$B=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,RB=/^((([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,PB=n=>n.length>1&&n.length<80&&(/^P\d+([.,]\d+)?W$/.test(n)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(n)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(n));function rs(n){return n.test.bind(n)}const z0={date:BI,time:HI.bind(void 0,!1),"date-time":jB,duration:PB,uri:UB,"uri-reference":rs(AB),"uri-template":rs(TB),url:rs(EB),email:CB,hostname:rs(SB),ipv4:rs($B),ipv6:rs(RB),regex:FB,uuid:rs(kB),"json-pointer":rs(IB),"json-pointer-uri-fragment":rs(xB),"relative-json-pointer":rs(OB)};function NB(n){return n%4===0&&(n%100!==0||n%400===0)}function BI(n){const e=n.match(wB);if(!e)return!1;const t=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r==2&&NB(t)?29:bB[r])}function HI(n,e){const t=e.match(vB);if(!t)return!1;const r=+t[1],s=+t[2],i=+t[3],a=!!t[5];return(r<=23&&s<=59&&i<=59||r==23&&s==59&&i==60)&&(!n||a)}const MB=/t|\s/i;function jB(n){const e=n.split(MB);return e.length==2&&BI(e[0])&&HI(!0,e[1])}const LB=/\/|:/,DB=/^(?:[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 UB(n){return LB.test(n)&&DB.test(n)}const zB=/[^\\]\\Z/;function FB(n){if(zB.test(n))return!1;try{return new RegExp(n,"u"),!0}catch{return!1}}function BB(n){let e=0,t=n.length,r=0,s;for(;r<t;)e++,s=n.charCodeAt(r++),s>=55296&&s<=56319&&r<t&&(s=n.charCodeAt(r),(s&64512)==56320&&r++);return e}function Ct(n,e,t="2019-09",r=wi(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 n;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":n===null?l="null":Array.isArray(n)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:f,$recursiveAnchor:h,type:m,const:g,enum:y,required:b,not:_,anyOf:w,allOf:S,oneOf:T,if:A,then:I,else:k,format:R,properties:x,patternProperties:O,additionalProperties:U,unevaluatedProperties:B,minProperties:F,maxProperties:Y,propertyNames:Z,dependentRequired:ge,dependentSchemas:M,dependencies:K,prefixItems:se,items:oe,additionalItems:X,unevaluatedItems:ie,contains:Ee,minContains:de,maxContains:E,minItems:v,maxItems:j,uniqueItems:C,minimum:_e,maximum:xe,exclusiveMinimum:dt,exclusiveMaximum:Qe,multipleOf:yt,minLength:Ot,maxLength:Ue,pattern:Dt,__absolute_ref__:bn,__absolute_recursive_ref__:yr}=e,L=[];if(h===!0&&i===null&&(i=e),f==="#"){const ke=i===null?r[yr]:i,Te=`${o}/$recursiveRef`,Oe=Ct(n,i===null?e:i,t,r,s,ke,a,Te,c);Oe.valid||L.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:Te,error:"A subschema had errors."},...Oe.errors)}if(d!==void 0){const Te=r[bn||d];if(Te===void 0){let ne=`Unresolved $ref "${d}".`;throw bn&&bn!==d&&(ne+=` Absolute URI "${bn}".`),ne+=`
|
|
149
|
+
Known schemas:
|
|
150
|
+
- ${Object.keys(r).join(`
|
|
151
|
+
- `)}`,new Error(ne)}const Oe=`${o}/$ref`,ee=Ct(n,Te,t,r,s,i,a,Oe,c);if(ee.valid||L.push({instanceLocation:a,keyword:"$ref",keywordLocation:Oe,error:"A subschema had errors."},...ee.errors),t==="4"||t==="7")return{valid:L.length===0,errors:L}}if(Array.isArray(m)){let ke=m.length,Te=!1;for(let Oe=0;Oe<ke;Oe++)if(l===m[Oe]||m[Oe]==="integer"&&l==="number"&&n%1===0&&n===n){Te=!0;break}Te||L.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(l!=="number"||n%1||n!==n)&&L.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`}):m!==void 0&&l!==m&&L.push({instanceLocation:a,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${m}".`});if(g!==void 0&&(l==="object"||l==="array"?Sa(n,g)||L.push({instanceLocation:a,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):n!==g&&L.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(ke=>Sa(n,ke))||L.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(ke=>n===ke)||L.push({instanceLocation:a,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),_!==void 0){const ke=`${o}/not`;Ct(n,_,t,r,s,i,a,ke).valid&&L.push({instanceLocation:a,keyword:"not",keywordLocation:ke,error:'Instance matched "not" schema.'})}let vn=[];if(w!==void 0){const ke=`${o}/anyOf`,Te=L.length;let Oe=!1;for(let ee=0;ee<w.length;ee++){const ne=w[ee],Re=Object.create(c),Ce=Ct(n,ne,t,r,s,h===!0?i:null,a,`${ke}/${ee}`,Re);L.push(...Ce.errors),Oe=Oe||Ce.valid,Ce.valid&&vn.push(Re)}Oe?L.length=Te:L.splice(Te,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:ke,error:"Instance does not match any subschemas."})}if(S!==void 0){const ke=`${o}/allOf`,Te=L.length;let Oe=!0;for(let ee=0;ee<S.length;ee++){const ne=S[ee],Re=Object.create(c),Ce=Ct(n,ne,t,r,s,h===!0?i:null,a,`${ke}/${ee}`,Re);L.push(...Ce.errors),Oe=Oe&&Ce.valid,Ce.valid&&vn.push(Re)}Oe?L.length=Te:L.splice(Te,0,{instanceLocation:a,keyword:"allOf",keywordLocation:ke,error:"Instance does not match every subschema."})}if(T!==void 0){const ke=`${o}/oneOf`,Te=L.length,Oe=T.filter((ee,ne)=>{const Re=Object.create(c),Ce=Ct(n,ee,t,r,s,h===!0?i:null,a,`${ke}/${ne}`,Re);return L.push(...Ce.errors),Ce.valid&&vn.push(Re),Ce.valid}).length;Oe===1?L.length=Te:L.splice(Te,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:ke,error:`Instance does not match exactly one subschema (${Oe} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...vn),A!==void 0){const ke=`${o}/if`;if(Ct(n,A,t,r,s,i,a,ke,c).valid){if(I!==void 0){const Oe=Ct(n,I,t,r,s,i,a,`${o}/then`,c);Oe.valid||L.push({instanceLocation:a,keyword:"if",keywordLocation:ke,error:'Instance does not match "then" schema.'},...Oe.errors)}}else if(k!==void 0){const Oe=Ct(n,k,t,r,s,i,a,`${o}/else`,c);Oe.valid||L.push({instanceLocation:a,keyword:"if",keywordLocation:ke,error:'Instance does not match "else" schema.'},...Oe.errors)}}if(l==="object"){if(b!==void 0)for(const ee of b)ee in n||L.push({instanceLocation:a,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${ee}".`});const ke=Object.keys(n);if(F!==void 0&&ke.length<F&&L.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${F} properties.`}),Y!==void 0&&ke.length>Y&&L.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${Y} properties.`}),Z!==void 0){const ee=`${o}/propertyNames`;for(const ne in n){const Re=`${a}/${Fr(ne)}`,Ce=Ct(ne,Z,t,r,s,i,Re,ee);Ce.valid||L.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ee,error:`Property name "${ne}" does not match schema.`},...Ce.errors)}}if(ge!==void 0){const ee=`${o}/dependantRequired`;for(const ne in ge)if(ne in n){const Re=ge[ne];for(const Ce of Re)Ce in n||L.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:ee,error:`Instance has "${ne}" but does not have "${Ce}".`})}}if(M!==void 0)for(const ee in M){const ne=`${o}/dependentSchemas`;if(ee in n){const Re=Ct(n,M[ee],t,r,s,i,a,`${ne}/${Fr(ee)}`,c);Re.valid||L.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:ne,error:`Instance has "${ee}" but does not match dependant schema.`},...Re.errors)}}if(K!==void 0){const ee=`${o}/dependencies`;for(const ne in K)if(ne in n){const Re=K[ne];if(Array.isArray(Re))for(const Ce of Re)Ce in n||L.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${ne}" but does not have "${Ce}".`});else{const Ce=Ct(n,Re,t,r,s,i,a,`${ee}/${Fr(ne)}`);Ce.valid||L.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ee,error:`Instance has "${ne}" but does not match dependant schema.`},...Ce.errors)}}}const Te=Object.create(null);let Oe=!1;if(x!==void 0){const ee=`${o}/properties`;for(const ne in x){if(!(ne in n))continue;const Re=`${a}/${Fr(ne)}`,Ce=Ct(n[ne],x[ne],t,r,s,i,Re,`${ee}/${Fr(ne)}`);if(Ce.valid)c[ne]=Te[ne]=!0;else if(Oe=s,L.push({instanceLocation:a,keyword:"properties",keywordLocation:ee,error:`Property "${ne}" does not match schema.`},...Ce.errors),Oe)break}}if(!Oe&&O!==void 0){const ee=`${o}/patternProperties`;for(const ne in O){const Re=new RegExp(ne,"u"),Ce=O[ne];for(const Q in n){if(!Re.test(Q))continue;const Je=`${a}/${Fr(Q)}`,wt=Ct(n[Q],Ce,t,r,s,i,Je,`${ee}/${Fr(ne)}`);wt.valid?c[Q]=Te[Q]=!0:(Oe=s,L.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:ee,error:`Property "${Q}" matches pattern "${ne}" but does not match associated schema.`},...wt.errors))}}}if(!Oe&&U!==void 0){const ee=`${o}/additionalProperties`;for(const ne in n){if(Te[ne])continue;const Re=`${a}/${Fr(ne)}`,Ce=Ct(n[ne],U,t,r,s,i,Re,ee);Ce.valid?c[ne]=!0:(Oe=s,L.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:ee,error:`Property "${ne}" does not match additional properties schema.`},...Ce.errors))}}else if(!Oe&&B!==void 0){const ee=`${o}/unevaluatedProperties`;for(const ne in n)if(!c[ne]){const Re=`${a}/${Fr(ne)}`,Ce=Ct(n[ne],B,t,r,s,i,Re,ee);Ce.valid?c[ne]=!0:L.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:ee,error:`Property "${ne}" does not match unevaluated properties schema.`},...Ce.errors)}}}else if(l==="array"){j!==void 0&&n.length>j&&L.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${n.length} > ${j}).`}),v!==void 0&&n.length<v&&L.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${n.length} < ${v}).`});const ke=n.length;let Te=0,Oe=!1;if(se!==void 0){const ee=`${o}/prefixItems`,ne=Math.min(se.length,ke);for(;Te<ne;Te++){const Re=Ct(n[Te],se[Te],t,r,s,i,`${a}/${Te}`,`${ee}/${Te}`);if(c[Te]=!0,!Re.valid&&(Oe=s,L.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:ee,error:"Items did not match schema."},...Re.errors),Oe))break}}if(oe!==void 0){const ee=`${o}/items`;if(Array.isArray(oe)){const ne=Math.min(oe.length,ke);for(;Te<ne;Te++){const Re=Ct(n[Te],oe[Te],t,r,s,i,`${a}/${Te}`,`${ee}/${Te}`);if(c[Te]=!0,!Re.valid&&(Oe=s,L.push({instanceLocation:a,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...Re.errors),Oe))break}}else for(;Te<ke;Te++){const ne=Ct(n[Te],oe,t,r,s,i,`${a}/${Te}`,ee);if(c[Te]=!0,!ne.valid&&(Oe=s,L.push({instanceLocation:a,keyword:"items",keywordLocation:ee,error:"Items did not match schema."},...ne.errors),Oe))break}if(!Oe&&X!==void 0){const ne=`${o}/additionalItems`;for(;Te<ke;Te++){const Re=Ct(n[Te],X,t,r,s,i,`${a}/${Te}`,ne);c[Te]=!0,Re.valid||(Oe=s,L.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:ne,error:"Items did not match additional items schema."},...Re.errors))}}}if(Ee!==void 0)if(ke===0&&de===void 0)L.push({instanceLocation:a,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(de!==void 0&&ke<de)L.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${ke}) than minContains (${de}).`});else{const ee=`${o}/contains`,ne=L.length;let Re=0;for(let Ce=0;Ce<ke;Ce++){const Q=Ct(n[Ce],Ee,t,r,s,i,`${a}/${Ce}`,ee);Q.valid?(c[Ce]=!0,Re++):L.push(...Q.errors)}Re>=(de||0)&&(L.length=ne),de===void 0&&E===void 0&&Re===0?L.splice(ne,0,{instanceLocation:a,keyword:"contains",keywordLocation:ee,error:"Array does not contain item matching schema."}):de!==void 0&&Re<de?L.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${de} items matching schema. Only ${Re} items were found.`}):E!==void 0&&Re>E&&L.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${E} items matching schema. ${Re} items were found.`})}if(!Oe&&ie!==void 0){const ee=`${o}/unevaluatedItems`;for(Te;Te<ke;Te++){if(c[Te])continue;const ne=Ct(n[Te],ie,t,r,s,i,`${a}/${Te}`,ee);c[Te]=!0,ne.valid||L.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:ee,error:"Items did not match unevaluated items schema."},...ne.errors)}}if(C)for(let ee=0;ee<ke;ee++){const ne=n[ee],Re=typeof ne=="object"&&ne!==null;for(let Ce=0;Ce<ke;Ce++){if(ee===Ce)continue;const Q=n[Ce];(ne===Q||Re&&(typeof Q=="object"&&Q!==null)&&Sa(ne,Q))&&(L.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${ee} and ${Ce}.`}),ee=Number.MAX_SAFE_INTEGER,Ce=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(t==="4"?(_e!==void 0&&(dt===!0&&n<=_e||n<_e)&&L.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${n} is less than ${dt?"or equal to ":""} ${_e}.`}),xe!==void 0&&(Qe===!0&&n>=xe||n>xe)&&L.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${n} is greater than ${Qe?"or equal to ":""} ${xe}.`})):(_e!==void 0&&n<_e&&L.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${n} is less than ${_e}.`}),xe!==void 0&&n>xe&&L.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${n} is greater than ${xe}.`}),dt!==void 0&&n<=dt&&L.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${n} is less than ${dt}.`}),Qe!==void 0&&n>=Qe&&L.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${n} is greater than or equal to ${Qe}.`})),yt!==void 0){const ke=n%yt;Math.abs(0-ke)>=11920929e-14&&Math.abs(yt-ke)>=11920929e-14&&L.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${n} is not a multiple of ${yt}.`})}}else if(l==="string"){const ke=Ot===void 0&&Ue===void 0?0:BB(n);Ot!==void 0&&ke<Ot&&L.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${ke} < ${Ot}).`}),Ue!==void 0&&ke>Ue&&L.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${ke} > ${Ue}).`}),Dt!==void 0&&!new RegExp(Dt,"u").test(n)&&L.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),R!==void 0&&z0[R]&&!z0[R](n)&&L.push({instanceLocation:a,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${R}".`})}return{valid:L.length===0,errors:L}}class HB{constructor(e,t="2019-09",r=!0){p(this,"schema");p(this,"draft");p(this,"shortCircuit");p(this,"lookup");this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=wi(e)}validate(e){return Ct(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),wi(e,this.lookup)}}var VB=he({Validator:()=>HB,deepCompareStrict:()=>Sa,toJsonSchema:()=>At,validatesOnlyStrings:()=>Ou});const F0=new WeakMap;function At(n,e){const t=!e&&n!=null&&typeof n=="object";if(t){const s=F0.get(n);if(s)return s}let r;if(ew(n)&&!It(n))r=n["~standard"].jsonSchema.input({target:"draft-07"});else if(It(n)){const s=EI(n,!0);ws(s)?r=zg(Gh(s,!0),e):r=zg(n,e)}else Ht(n)?r=hB(n):r=n;return t&&r!=null&&typeof r=="object"&&F0.set(n,r),r}function Ou(n){if(!n||typeof n!="object"||Object.keys(n).length===0||Array.isArray(n))return!1;if("type"in n)return typeof n.type=="string"?n.type==="string":Array.isArray(n.type)?n.type.every(e=>e==="string"):!1;if("enum"in n)return Array.isArray(n.enum)&&n.enum.length>0&&n.enum.every(e=>typeof e=="string");if("const"in n)return typeof n.const=="string";if("allOf"in n&&Array.isArray(n.allOf))return n.allOf.some(e=>Ou(e));if("anyOf"in n&&Array.isArray(n.anyOf)||"oneOf"in n&&Array.isArray(n.oneOf)){const e="anyOf"in n?n.anyOf:n.oneOf;return e.length>0&&e.every(t=>Ou(t))}if("not"in n)return!1;if("$ref"in n&&typeof n.$ref=="string"){const e=n.$ref,t=wi(n);return t[e]?Ou(t[e]):!1}return!1}var ZB=he({Graph:()=>Ju});function KB(n,e){if(n!==void 0&&!wa(n))return n;if(Zy(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function WB(n){return Zy(n.data)?{type:"runnable",data:{id:n.data.lc_id,name:n.data.getName()}}:{type:"schema",data:{...At(n.data.schema),title:n.data.name}}}var Ju=class VI{constructor(e){p(this,"nodes",{});p(this,"edges",[]);this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=wa(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...WB(t)})),edges:this.edges.map(t=>{const r={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(r.data=t.data),typeof t.conditional<"u"&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const s=t??Ni(),i={id:s,data:e,name:KB(t,e),metadata:r};return this.nodes[s]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);const i={source:e.id,target:t.id,data:r,conditional:s};return this.edges.push(i),i}firstNode(){return B0(this)}lastNode(){return H0(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(c=>c.id).every(wa)&&(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&&B0(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&H0(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),t=new Map;Object.values(e).forEach(s=>{t.set(s,(t.get(s)||0)+1)});const r=s=>{const i=e[s];return wa(s)&&t.get(i)===1?i:s};return new VI({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:t,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 Qz(a.nodes,a.edges,{firstNode:o==null?void 0:o.id,lastNode:c==null?void 0:c.id,withStyles:t,curveStyle:r,nodeColors:s,wrapLabelNWords:i})}async drawMermaidPng(e){return eF(this.drawMermaid(e),{backgroundColor:e==null?void 0:e.backgroundColor})}};function B0(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function H0(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function qB(n){const e=new TextEncoder,t=new ReadableStream({async start(r){for await(const s of n)r.enqueue(e.encode(`event: data
|
|
152
|
+
data: ${JSON.stringify(s)}
|
|
153
|
+
|
|
154
|
+
`));r.enqueue(e.encode(`event: end
|
|
155
|
+
|
|
156
|
+
`)),r.close()}});return Wn.fromReadableStream(t)}function V0(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.iterator]=="function"&&typeof n.next=="function"}const GB=n=>n!=null&&typeof n=="object"&&"next"in n&&typeof n.next=="function";function Qg(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.asyncIterator]=="function"}function ZI(n){return n!=null&&typeof n=="object"&&typeof n.next=="function"}async function JB(n,e){var t;try{let r=await n.next();for(;!r.done;)await(e==null?void 0:e(r.value)),r=await n.next();return r.value}finally{await((t=n.return)==null?void 0:t.call(n,void 0))}}function*Z0(n,e){for(;;){const{value:t,done:r}=yn.runWithConfig(Ks(n),e.next.bind(e),!0);if(r)break;yield t}}async function*e_(n,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await yn.runWithConfig(Ks(n),t.next.bind(e),!0);if(s)break;yield r}}function Yt(n,e){return n&&!Array.isArray(n)&&!(n instanceof Date)&&typeof n=="object"?n:{[e]:n}}var Ge=class extends kr{constructor(){super(...arguments);p(this,"lc_runnable",!0);p(this,"name")}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new tw({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new mn({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new YI({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(rt);if(t>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:t},(s,i)=>rt(i===0?e:r))}return Array.from({length:t},()=>rt(e))}async batch(e,t,r){var o;const s=this._getOptionsList(t??{},e.length),i=new Ml({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,t){yield this.invoke(e,t)}async stream(e,t){const r=rt(t),s=new Ua({generator:this._streamIterator(e,r),config:r});return await s.setup,Wn.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=rt(e):t=rt({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,[t,r]}async _callWithConfig(e,t,r){var o;const s=rt(r),i=await((o=await dr(s))==null?void 0:o.handleChainStart(this.toJSON(),Yt(t,"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 Ts(e.call(this,t,s,i),s.signal)}catch(c){throw await(i==null?void 0:i.handleChainError(c)),c}return await(i==null?void 0:i.handleChainEnd(Yt(a,"output"))),a}async _batchWithConfig(e,t,r,s){var u;const i=this._getOptionsList(r??{},t.length),a=await Promise.all(i.map(dr)),o=await Promise.all(a.map(async(l,d)=>{const f=await(l==null?void 0:l.handleChainStart(this.toJSON(),Yt(t[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 Ts(e.call(this,t,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(Yt(c,"output")))),c}_concatOutputChunks(e,t){return Ws(e,t)}async*_transformStreamWithConfig(e,t,r){let s,i=!0,a,o=!0;const c=rt(r),u=await dr(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 _k(t.bind(this),d(),async()=>u==null?void 0:u.handleChainStart(this.toJSON(),{input:""},c.runId,c.runType,void 0,void 0,c.runName??this.getName(),void 0,{lc_defers_inputs:!0}),c.signal,c);delete c.runId,f=h.setup;const m=f==null?void 0:f.handlers.find(hD);let g=h.output;m!==void 0&&f!==void 0&&(g=m.tapOutputIterable(f.runId,g));const y=f==null?void 0:f.handlers.find(bk);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:Yt(s,"input")})),h}await(f==null?void 0:f.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Yt(s,"input")}))}getGraph(e){const t=new Ju,r=t.addNode({name:`${this.getName()}Input`,schema:L0()}),s=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:L0()});return t.addEdge(r,s),t.addEdge(s,i),t}pipe(e){return new pr({first:this,last:gn(e)})}pick(e){return this.pipe(new XI(e))}assign(e){return this.pipe(new nw(new vc({steps:e})))}async*transform(e,t){let r;for await(const s of e)r===void 0?r=s:r=this._concatOutputChunks(r,s);yield*this._streamIterator(r,rt(t))}async*streamLog(e,t,r){const s=new jg({...r,autoClose:!1,_schemaFormat:"original"}),i=rt(t);yield*this._streamLog(e,s,i)}async*_streamLog(e,t,r){const{callbacks:s}=r;if(s===void 0)r.callbacks=[t];else if(Array.isArray(s))r.callbacks=s.concat([t]);else{const c=s.copy();c.addHandler(t,!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 Ds({ops:[{op:"add",path:"/streamed_output/-",value:u}]});await t.writer.write(l)}}finally{await t.writer.close()}}const o=a();try{for await(const c of t)yield c}finally{await o}}streamEvents(e,t,r){let s;if(t.version==="v1")s=this._streamEventsV1(e,t,r);else if(t.version==="v2")s=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?qB(s):Wn.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,r){var m;const s=new fD({...r,autoClose:!1}),i=rt(t),a=i.runId??js();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")&&(m=g.data)!=null&&m.input&&delete g.data.input,yield g}}finally{c.abort(),await d}}async*_streamEventsV1(e,t,r){let s,i=!1;const a=rt(t),o=a.tags??[],c=a.metadata??{},u=a.runName??this.getName(),l=new jg({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new ED({...r}),f=this._streamLog(e,l,a);for await(const m of f){if(s?s=s.concat(m):s=Vy.fromRunLogPatch(m),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=m.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),y=[...new Set(g)];for(const _ of y){let w,S={};const T=s.state.logs[_];if(T.end_time===void 0?T.streamed_output.length>0?w="stream":w="start":w="end",w==="start")T.inputs!==void 0&&(S.input=T.inputs);else if(w==="end")T.inputs!==void 0&&(S.input=T.inputs),S.output=T.final_output;else if(w==="stream"){const A=T.streamed_output.length;if(A!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${A} instead. Encountered in: "${T.name}"`);S={chunk:T.streamed_output[0]},T.streamed_output=[]}yield{event:`on_${T.type}_${w}`,name:T.name,run_id:T.id,tags:T.tags,metadata:T.metadata,data:S}}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 S={event:`on_${b.type}_stream`,run_id:b.id,tags:o,metadata:c,name:u,data:w};d.includeEvent(S,b.type)&&(yield S)}}const h=s==null?void 0:s.state;if(h!==void 0){const m={event:`on_${h.type}_end`,name:u,run_id:h.id,tags:o,metadata:c,data:{output:h.final_output}};d.includeEvent(m,h.type)&&(yield m)}}static isRunnable(e){return Zy(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new mn({bound:this,config:{},configFactories:[s=>({callbacks:[new Ak({config:s,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return t3(this,e)}},mn=class KI extends Ge{constructor(t){super(t);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"bound");p(this,"config");p(this,"kwargs");p(this,"configFactories");this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}static lc_name(){return"RunnableBinding"}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const r=or(this.config,...t);return or(r,...this.configFactories?await Promise.all(this.configFactories.map(async s=>await s(r))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new tw({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t==null?void 0:t.stopAfterAttempt,...t})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(r,this.kwargs))}async batch(t,r,s){const i=Array.isArray(r)?await Promise.all(r.map(async a=>this._mergeConfig(rt(a),this.kwargs))):await this._mergeConfig(rt(r),this.kwargs);return this.bound.batch(t,i,s)}_concatOutputChunks(t,r){return this.bound._concatOutputChunks(t,r)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(rt(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(rt(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(rt(r),this.kwargs))}streamEvents(t,r,s){const i=this,a=async function*(){yield*i.bound.streamEvents(t,{...await i._mergeConfig(rt(r),i.kwargs),version:r.version},s)};return Wn.fromAsyncGenerator(a())}static isRunnableBinding(t){return t.bound&&Ge.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:s}){return new KI({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new Ak({config:i,onStart:t,onEnd:r,onError:s})]})]})}},YB=class WI extends Ge{constructor(t){super(t);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"bound");this.bound=t.bound}static lc_name(){return"RunnableEach"}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,s){return this.bound.batch(t,ut(r,{callbacks:s==null?void 0:s.getChild()}))}withListeners({onStart:t,onEnd:r,onError:s}){return new WI({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:s})})}},tw=class extends mn{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"maxAttemptNumber",3);p(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,t,r){const s=e>1?`retry:attempt:${e}`:void 0;return ut(t,{callbacks:r==null?void 0:r.getChild(s)})}async _invoke(e,t,r){return Lg(s=>super.invoke(e,this._patchConfigForRetry(s,t,r)),{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,s){const i={};try{await Lg(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,t==null?void 0:t[f],r==null?void 0:r[f])),l=await super.batch(c,u,{...s,returnExceptions:!0});let d;for(let f=0;f<l.length;f+=1){const h=l[f],m=o[f];h instanceof Error&&d===void 0&&(d=h,d.input=c[f]),i[m.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,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}},pr=class iu extends Ge{constructor(t){super(t);p(this,"first");p(this,"middle",[]);p(this,"last");p(this,"omitSequenceTags",!1);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain_core","runnables"]);this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){var c,u;const s=rt(r),i=await((c=await dr(s))==null?void 0:c.handleChainStart(this.toJSON(),Yt(t,"input"),s.runId,void 0,void 0,void 0,s==null?void 0:s.runName));delete s.runId;let a=t,o;try{const l=[this.first,...this.middle];for(let d=0;d<l.length;d+=1)a=await Ts(l[d].invoke(a,ut(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 Vu(s.signal);o=await this.last.invoke(a,ut(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(Yt(o,"output"))),o}async batch(t,r,s){var u;const i=this._getOptionsList(r??{},t.length),a=await Promise.all(i.map(dr)),o=await Promise.all(a.map(async(l,d)=>{const f=await(l==null?void 0:l.handleChainStart(this.toJSON(),Yt(t[d],"input"),i[d].runId,void 0,void 0,void 0,i[d].runName));return delete i[d].runId,f}));let c=t;try{for(let l=0;l<this.steps.length;l+=1)c=await Ts(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 ut(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(Yt(c,"output")))),c}_concatOutputChunks(t,r){return this.last._concatOutputChunks(t,r)}async*_streamIterator(t,r){var f;const s=await dr(r),{runId:i,...a}=r??{},o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Yt(t,"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 t}try{let h=c[0].transform(d(),ut(a,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let m=1;m<c.length;m+=1)h=await c[m].transform(h,ut(a,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:`seq:step:${m+1}`)}));for await(const m of h)if((f=r==null?void 0:r.signal)==null||f.throwIfAborted(),yield m,u)if(l===void 0)l=m;else try{l=this._concatOutputChunks(l,m)}catch{l=void 0,u=!1}}catch(h){throw await(o==null?void 0:o.handleChainError(h)),h}await(o==null?void 0:o.handleChainEnd(Yt(l,"output")))}getGraph(t){const r=new Ju;let s=null;return this.steps.forEach((i,a)=>{const o=i.getGraph(t);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(t){return iu.isRunnableSequence(t)?new iu({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new iu({first:this.first,middle:[...this.middle,this.last],last:gn(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&Ge.isRunnable(t)}static from([t,...r],s){let i={};return typeof s=="string"?i.name=s:s!==void 0&&(i=s),new iu({...i,first:gn(t),middle:r.slice(0,-1).map(gn),last:gn(r[r.length-1])})}},vc=class qI extends Ge{constructor(t){super(t);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"steps");this.steps={};for(const[r,s]of Object.entries(t.steps))this.steps[r]=gn(s)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(t){return new qI({steps:t})}async invoke(t,r){var o;const s=rt(r),i=await((o=await dr(s))==null?void 0:o.handleChainStart(this.toJSON(),{input:t},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(t,ut(s,{callbacks:i==null?void 0:i.getChild(`map:key:${u}`)}))});await Ts(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(t,r,s){const i={...this.steps},a=Hy(t,Object.keys(i).length),o=new Map(Object.entries(i).map(([c,u],l)=>{const d=u.transform(a[l],ut(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 Ts(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(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*s(){yield t}const i=rt(r),a=new Ua({generator:this.transform(s(),i),config:i});return await a.setup,Wn.fromAsyncGenerator(a)}},XB=class GI extends Ge{constructor(t){super(t);p(this,"lc_serializable",!1);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"func");if(!Fy(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){const[s]=this._getOptionsList(r??{},1),i=await dr(s);return Ts(this.func(ut(s,{callbacks:i}),t),s==null?void 0:s.signal)}async*_streamIterator(t,r){var a,o;const[s]=this._getOptionsList(r??{},1),i=await this.invoke(t,r);if(Qg(i)){for await(const c of i)(a=s==null?void 0:s.signal)==null||a.throwIfAborted(),yield c;return}if(GB(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(t){return new GI({func:t})}};function QB(n){if(Fy(n))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var an=class JI extends Ge{constructor(t){if(Fy(t.func))return XB.from(t.func);super(t);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"func");QB(t.func),this.func=t.func}static lc_name(){return"RunnableLambda"}static from(t){return new JI({func:t})}async _invoke(t,r,s){return new Promise((i,a)=>{const o=ut(r,{callbacks:s==null?void 0:s.getChild(),recursionLimit:((r==null?void 0:r.recursionLimit)??25)-1});yn.runWithConfig(Ks(o),async()=>{var c,u;try{let l=await this.func(t,{...o});if(l&&Ge.isRunnable(l)){if((r==null?void 0:r.recursionLimit)===0)throw new Error("Recursion limit reached.");l=await l.invoke(t,{...o,recursionLimit:(o.recursionLimit??25)-1})}else if(Qg(l)){let d;for await(const f of e_(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(V0(l)){let d;for(const f of Z0(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(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,s){var c,u;let i;for await(const l of t)if(i===void 0)i=l;else try{i=this._concatOutputChunks(i,l)}catch{i=l}const a=ut(s,{callbacks:r==null?void 0:r.getChild(),recursionLimit:((s==null?void 0:s.recursionLimit)??25)-1}),o=await new Promise((l,d)=>{yn.runWithConfig(Ks(a),async()=>{try{l(await this.func(i,{...a,config:a}))}catch(f){d(f)}})});if(o&&Ge.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(Qg(o))for await(const l of e_(a,o))(c=s==null?void 0:s.signal)==null||c.throwIfAborted(),yield l;else if(V0(o))for(const l of Z0(a,o))(u=s==null?void 0:s.signal)==null||u.throwIfAborted(),yield l;else yield o}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*s(){yield t}const i=rt(r),a=new Ua({generator:this.transform(s(),i),config:i});return await a.setup,Wn.fromAsyncGenerator(a)}},e3=class extends vc{},YI=class extends Ge{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"runnable");p(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=rt(t),s=await dr(r),{runId:i,...a}=r,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Yt(e,"input"),i,void 0,void 0,void 0,a==null?void 0:a.runName)),c=ut(a,{callbacks:o==null?void 0:o.getChild()});return await yn.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(Yt(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,t){var d;const r=rt(t),s=await dr(r),{runId:i,...a}=r,o=await(s==null?void 0:s.handleChainStart(this.toJSON(),Yt(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=ut(a,{callbacks:o==null?void 0:o.getChild()});try{u=e_(h,await f.stream(e,h));break}catch(m){c===void 0&&(c=m)}}if(u===void 0){const f=c??new Error("No error stored at end of fallback.");throw await(o==null?void 0:o.handleChainError(f)),f}let l;try{for await(const f of u){yield f;try{l=l===void 0?l:this._concatOutputChunks(l,f)}catch{l=void 0}}}catch(f){throw await(o==null?void 0:o.handleChainError(f)),f}await(o==null?void 0:o.handleChainEnd(Yt(l,"output")))}async batch(e,t,r){var c;if(r!=null&&r.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(t??{},e.length),i=await Promise.all(s.map(u=>dr(u))),a=await Promise.all(i.map(async(u,l)=>{const d=await(u==null?void 0:u.handleChainStart(this.toJSON(),Yt(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)=>ut(s[f],{callbacks:d==null?void 0:d.getChild()})),r);return await Promise.all(a.map((d,f)=>d==null?void 0:d.handleChainEnd(Yt(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 gn(n){if(typeof n=="function")return new an({func:n});if(Ge.isRunnable(n))return n;if(!Array.isArray(n)&&typeof n=="object"){const e={};for(const[t,r]of Object.entries(n))e[t]=gn(r);return new vc({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
157
|
+
Instead got an unsupported type.`)}var nw=class extends Ge{constructor(e){e instanceof vc&&(e={mapper:e});super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const s=this.mapper.getStepsKeys(),[i,a]=Hy(e),o=this.mapper.transform(a,ut(r,{callbacks:t==null?void 0:t.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,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=rt(t),i=new Ua({generator:this.transform(r(),s),config:s});return await i.setup,Wn.fromAsyncGenerator(i)}},XI=class extends Ge{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=rt(t),i=new Ua({generator:this.transform(r(),s),config:s});return await i.setup,Wn.fromAsyncGenerator(i)}},t_=class extends mn{constructor(e){const t=pr.from([an.from(async r=>{let s;if(Eu(r))try{s=await np(this.schema,r.args)}catch{throw new $h("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:t,config:e.config??{}});p(this,"name");p(this,"description");p(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function t3(n,e){const t=e.name??n.getName(),r=e.description??tc(e.schema);return Xy(e.schema)?new t_({name:t,description:r,schema:ap({input:ip()}).transform(s=>s.input),bound:n}):new t_({name:t,description:r,schema:e.schema,bound:n})}var Yu=class extends Ge{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,t){const r=rt(t);return this.func&&await this.func(e,r),this._callWithConfig(s=>Promise.resolve(s),e,r)}async*transform(e,t){const r=rt(t);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=Ws(s,a)}catch{s=void 0,i=!1}this.func&&s!==void 0&&await this.func(s,r)}static assign(e){return new nw(new vc({steps:e}))}},n3=class extends Ge{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"runnables");this.runnables=e.runnables}static lc_name(){return"RouterRunnable"}async invoke(e,t){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,rt(t))}async batch(e,t,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(t??{},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])),m=await Promise.all(h);l.push(m)}return l.flat()}async stream(e,t){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,t)}},r3=class extends Ge{constructor(e){super(e);p(this,"lc_namespace",["langchain_core","runnables"]);p(this,"lc_serializable",!0);p(this,"default");p(this,"branches");this.branches=e.branches,this.default=e.default}static lc_name(){return"RunnableBranch"}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const t=e.slice(0,-1).map(([s,i])=>[gn(s),gn(i)]),r=gn(e[e.length-1]);return new this({branches:t,default:r})}async _invoke(e,t,r){let s;for(let i=0;i<this.branches.length;i+=1){const[a,o]=this.branches[i];if(await a.invoke(e,ut(t,{callbacks:r==null?void 0:r.getChild(`condition:${i+1}`)}))){s=await o.invoke(e,ut(t,{callbacks:r==null?void 0:r.getChild(`branch:${i+1}`)}));break}}return s||(s=await this.default.invoke(e,ut(t,{callbacks:r==null?void 0:r.getChild("branch:default")}))),s}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){var o;const r=await((o=await dr(t))==null?void 0:o.handleChainStart(this.toJSON(),Yt(e,"input"),t==null?void 0:t.runId,void 0,void 0,void 0,t==null?void 0:t.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,ut(t,{callbacks:r==null?void 0:r.getChild(`condition:${c+1}`)}))){a=await l.stream(e,ut(t,{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=Ws(s,d)}catch{s=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,ut(t,{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=Ws(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 tf=(n,e)=>{const t=[...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=n.getType();return t.some(s=>s===r)};function s3(n,e){return Array.isArray(n)?K0(n,e):an.from(t=>K0(t,n))}function K0(n,e={}){const{includeNames:t,excludeNames:r,includeTypes:s,excludeTypes:i,includeIds:a,excludeIds:o}=e,c=[];for(const u of n)if(!(r&&u.name&&r.includes(u.name))){{if(i&&tf(u,i))continue;if(o&&u.id&&o.includes(u.id))continue}s||a||t?(t&&u.name&&t.some(l=>l===u.name)||s&&tf(u,s)||a&&u.id&&a.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function i3(n){return Array.isArray(n)?W0(n):an.from(W0)}function W0(n){if(!n.length)return[];const e=[];for(const t of n){const r=t,s=e.pop();if(!s)e.push(r);else if(r.getType()==="tool"||r.getType()!==s.getType())e.push(s,r);else{const i=Nh(s),a=Nh(r),o=i.concat(a);typeof i.content=="string"&&typeof a.content=="string"&&(o.content=`${i.content}
|
|
158
|
+
${a.content}`),e.push(c3(o))}}return e}function a3(n,e){if(Array.isArray(n)){const t=n;if(!e)throw new Error("Options parameter is required when providing messages.");return q0(t,e)}else{const t=n;return an.from(r=>q0(r,t)).withConfig({runName:"trim_messages"})}}async function q0(n,e){const{maxTokens:t,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,m)=>h+m,0):l=async f=>r(f);let d=ex;if(u&&("splitText"in u?d=u.splitText:d=async f=>u(f)),s==="first")return QI(n,{maxTokens:t,tokenCounter:l,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(s==="last")return o3(n,{maxTokens:t,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 QI(n,e){var u;const{maxTokens:t,tokenCounter:r,textSplitter:s,partialStrategy:i,endOn:a}=e;let o=[...n],c=0;for(let l=0;l<o.length;l+=1)if(await r(l>0?o.slice(0,-l):o)<=t){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 m=1;m<=f;m+=1){const g=i==="first"?h.slice(0,m):h.slice(-m),y=Object.fromEntries(Object.entries(d).filter(([w])=>w!=="type"&&!w.startsWith("lc_"))),b=rw(d.getType(),{...y,content:g}),_=[...o.slice(0,c),b];if(await r(_)<=t)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),m=h.length;i==="last"&&h.reverse();for(let g=0;g<m-1;g+=1)if(h.pop(),d.content=h.join(""),await r([...o.slice(0,c),d])<=t){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&&!tf(o[c-1],l);)c-=1}return o.slice(0,c)}async function o3(n,e){var l;const{allowPartial:t=!1,includeSystem:r=!1,endOn:s,startOn:i,...a}=e;let o=n.map(d=>{const f=Object.fromEntries(Object.entries(d).filter(([h])=>h!=="type"&&!h.startsWith("lc_")));return rw(d.getType(),f,Go(d))});if(s){const d=Array.isArray(s)?s:[s];for(;o.length>0&&!tf(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 QI(u,{...a,partialStrategy:t?"last":void 0,endOn:i}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const G0={human:{message:Dn,messageChunk:Rl},ai:{message:Ve,messageChunk:nt},system:{message:hr,messageChunk:Pi},developer:{message:hr,messageChunk:Pi},tool:{message:_n,messageChunk:Ol},function:{message:Ff,messageChunk:$l},generic:{message:ks,messageChunk:Cl},remove:{message:ya,messageChunk:ya}};function rw(n,e,t){var i;let r,s;switch(n){case"human":t?r=new Rl(e):s=new Dn(e);break;case"ai":if(t){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 nt(a)}else s=new Ve(e);break;case"system":t?r=new Pi(e):s=new hr(e);break;case"developer":t?r=new Pi({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):s=new hr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)t?r=new Ol(e):s=new _n(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(t)r=new $l(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");s=new Ff(e)}break;case"generic":if("role"in e)t?r=new Cl(e):s=new ks(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 ${n}`)}if(t&&r)return r;if(s)return s;throw new Error(`Unrecognized message type ${n}`)}function c3(n){const e=n.getType();let t;const r=Object.fromEntries(Object.entries(n).filter(([s])=>!["type","tool_call_chunks"].includes(s)&&!s.startsWith("lc_")));if(e in G0&&(t=rw(e,r)),!t)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys(G0)}`);return t}function ex(n){const e=n.split(`
|
|
159
|
+
`);return Promise.resolve([...e.slice(0,-1).map(t=>`${t}
|
|
160
|
+
`),e[e.length-1]])}const u3=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],l3=["image","video","audio","text-plain","file"],d3=["text","reasoning",...u3,...l3];var h3=he({AIMessage:()=>Ve,AIMessageChunk:()=>nt,BaseMessage:()=>Lt,BaseMessageChunk:()=>As,ChatMessage:()=>ks,ChatMessageChunk:()=>Cl,DEFAULT_MERGE_IGNORE_KEYS:()=>lE,FunctionMessage:()=>Ff,FunctionMessageChunk:()=>$l,HumanMessage:()=>Dn,HumanMessageChunk:()=>Rl,KNOWN_BLOCK_TYPES:()=>d3,RemoveMessage:()=>ya,SystemMessage:()=>hr,SystemMessageChunk:()=>Pi,ToolMessage:()=>_n,ToolMessageChunk:()=>Ol,_isMessageFieldWithRole:()=>fE,_mergeDicts:()=>En,_mergeLists:()=>qo,_mergeObj:()=>dE,_mergeStatus:()=>uE,coerceMessageLikeToMessage:()=>ys,collapseToolCallChunks:()=>bE,convertToChunk:()=>Nh,convertToOpenAIImageBlock:()=>iE,convertToProviderContentBlock:()=>xl,defaultTextSplitter:()=>ex,defaultToolCallParser:()=>Ey,filterMessages:()=>s3,getBufferString:()=>xy,iife:()=>wE,isAIMessage:()=>xr,isAIMessageChunk:()=>Ph,isBase64ContentBlock:()=>vy,isBaseMessage:()=>Rt,isBaseMessageChunk:()=>Go,isChatMessage:()=>CN,isChatMessageChunk:()=>$N,isDataContentBlock:()=>Ir,isDirectToolOutput:()=>Ty,isFunctionMessage:()=>RN,isFunctionMessageChunk:()=>PN,isHumanMessage:()=>NN,isHumanMessageChunk:()=>MN,isIDContentBlock:()=>sE,isMessage:()=>cE,isOpenAIToolCallArray:()=>dN,isPlainTextContentBlock:()=>qP,isSystemMessage:()=>jN,isSystemMessageChunk:()=>LN,isToolMessage:()=>_a,isToolMessageChunk:()=>pE,isURLContentBlock:()=>by,mapChatMessagesToStoredMessages:()=>VN,mapStoredMessageToChatMessage:()=>Oy,mapStoredMessagesToChatMessages:()=>HN,mergeContent:()=>Zs,mergeMessageRuns:()=>i3,mergeResponseMetadata:()=>gE,mergeUsageMetadata:()=>Iy,parseBase64DataUrl:()=>Gr,parseMimeType:()=>wg,trimMessages:()=>a3}),f3=class extends mn{constructor(e){let t=an.from((a,o)=>this._enterHistory(a,o??{})).withConfig({runName:"loadHistory"});const r=e.historyMessagesKey??e.inputMessagesKey;r&&(t=Yu.assign({[r]:t}).withConfig({runName:"insertHistory"}));const s=t.pipe(e.runnable.withListeners({onEnd:(a,o)=>this._exitHistory(a,o??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:s});p(this,"runnable");p(this,"inputMessagesKey");p(this,"outputMessagesKey");p(this,"historyMessagesKey");p(this,"getMessageHistory");this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!Rt(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])?t=e[r][0]:t=e[r]}else t=e;if(typeof t=="string")return[new Dn(t)];if(Array.isArray(t))return t;if(Rt(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
161
|
+
Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!Rt(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?t=e.generations[0][0].message:t=e[r]}else t=e;if(typeof t=="string")return[new Ve(t)];if(Array.isArray(t))return t;if(Rt(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){var s;const r=await((s=t==null?void 0:t.configurable)==null?void 0:s.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,t){var c;const r=(c=t.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 t=await super._mergeConfig(...e);if(!t.configurable||!t.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()
|
|
162
|
+
eg. chain.invoke(${JSON.stringify(s)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}const{sessionId:r}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(r),t}},p3=he({RouterRunnable:()=>n3,Runnable:()=>Ge,RunnableAssign:()=>nw,RunnableBinding:()=>mn,RunnableBranch:()=>r3,RunnableEach:()=>YB,RunnableLambda:()=>an,RunnableMap:()=>vc,RunnableParallel:()=>e3,RunnablePassthrough:()=>Yu,RunnablePick:()=>XI,RunnableRetry:()=>tw,RunnableSequence:()=>pr,RunnableToolLike:()=>t_,RunnableWithFallbacks:()=>YI,RunnableWithMessageHistory:()=>f3,_coerceToRunnable:()=>gn,ensureConfig:()=>rt,getCallbackManagerForConfig:()=>dr,mergeConfigs:()=>or,patchConfig:()=>ut,pickRunnableConfigKeys:()=>Ks,raceWithSignal:()=>Ts});function J0(n,e){if(n!=null){if(typeof n!="number"||Number.isNaN(n)||n<=0)throw new Error(`${e} must be greater than 0`);return n}}function n_(n){if(n==null)return;const e=typeof n=="number"?{runTimeout:n}:n,t=e.refreshOn??"auto";if(t!=="auto"&&t!=="heartbeat")throw new Error('refreshOn must be "auto" or "heartbeat"');const r=J0(e.runTimeout,"runTimeout"),s=J0(e.idleTimeout,"idleTimeout");if(!(r===void 0&&s===void 0))return{runTimeout:r,idleTimeout:s,refreshOn:t}}var pm={};const hn="__start__",bt="__end__",mi="__input__",jl="__error__",sw="__error_source_node__",mm="__pregel_ns_writes";function m3(){const n=typeof process<"u"?pm==null?void 0:pm.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT:void 0;if(n!==void 0&&n!==""){const e=Number.parseInt(n,10);if(Number.isFinite(e)&&e>0)return e}return 5e3}const Jr="__pregel_send",oc="__pregel_call",xi="__pregel_read",hs="__pregel_checkpointer",Cu="__pregel_resuming",$u="__pregel_task_id",iw="__pregel_stream",g3="__pregel_resume_value",Ru="__pregel_resume_map",Vs="__pregel_scratchpad",Pu="__pregel_previous",_3="__pregel_durability",Qi="checkpoint_id",ls="checkpoint_ns",y3="__pregel_node_finished",r_="__pregel_node_error",ar="checkpoint_map",s_="__pregel_replay_state",w3="__pregel_abort_signals",Ft="__interrupt__",bs="__resume__",aw="__no_writes__",op="__return__",nh="__previous__",Kn="langsmith:hidden",Y0="__self__",cc="__pregel_tasks",Er="__pregel_push",i_="__pregel_pull",Tr="00000000-0000-0000-0000-000000000000",b3=[Kn,mi,Ft,bs,jl,sw,aw,Jr,xi,hs,_3,iw,Cu,$u,oc,g3,Vs,Pu,ar,ls,Qi,s_],X0=Symbol.for("langgraph.command");var UT,v3=(UT=X0,class{constructor(n){p(this,UT);this[X0]=n}});function a_(n){const e=n;return e!=null&&typeof e.node=="string"&&e.args!==void 0}var Oa=class{constructor(n,e,t){p(this,"lg_name","Send");p(this,"node");p(this,"args");p(this,"timeout");this.node=n,this.args=Qu(e),this.timeout=n_(t==null?void 0:t.timeout)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args,timeout:this.timeout}}};function Gn(n){return n instanceof Oa}const ow="__overwrite__";function Xu(n){return typeof n=="object"&&n!==null&&"__overwrite__"in n?[!0,n[ow]]:[!1,void 0]}function S3(n){return Xu(n)[0]}function cw(n){return!n||typeof n!="object"||!("__interrupt__"in n)?!1:Array.isArray(n[Ft])}var mg,cr=(mg=class extends v3{constructor(e){super(e);p(this,"lg_name","Command");p(this,"lc_direct_tool_output",!0);p(this,"graph");p(this,"update");p(this,"resume");p(this,"goto",[]);this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?Qu(e.goto):[Qu(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 t;let e;return typeof this.goto=="string"?e=this.goto:Gn(this.goto)?e=this.goto.toJSON():e=(t=this.goto)==null?void 0:t.map(r=>typeof r=="string"?r:r.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}},p(mg,"PARENT","__parent__"),mg);function rn(n){return typeof n!="object"||n==null?!1:"lg_name"in n&&n.lg_name==="Command"}function A3(n){const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Qu(n,e=new Map){if(n!=null&&typeof n=="object"){if(e.has(n))return e.get(n);let t;if(Array.isArray(n))t=[],e.set(n,t),n.forEach((r,s)=>{t[s]=Qu(r,e)});else if(n instanceof cr||n instanceof Oa||!A3(n))t=n,e.set(n,t);else if(rn(n))t=new cr(n),e.set(n,t);else if(a_(n))t=new Oa(n.node,n.args,n.timeout!==void 0?{timeout:n.timeout}:void 0),e.set(n,t);else if("lc_serializable"in n&&n.lc_serializable)t=n,e.set(n,t);else{t={},e.set(n,t);for(const[r,s]of Object.entries(n))t[r]=Qu(s,e)}return t}return n}var ti=class extends Error{constructor(e,t){let r=e??"";t!=null&&t.lc_error_code&&(r=`${r}
|
|
163
|
+
|
|
164
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/
|
|
165
|
+
`);super(r);p(this,"lc_error_code");this.lc_error_code=t==null?void 0:t.lc_error_code}},uw=class extends ti{get is_bubble_up(){return!0}},T3=class extends ti{constructor(n,e){super(n,e),this.name="GraphRecursionError"}static get unminifiable_name(){return"GraphRecursionError"}},rh=class extends ti{constructor(n,e){super(n,e),this.name="GraphValueError"}static get unminifiable_name(){return"GraphValueError"}},tx=class extends uw{constructor(e="shutdown",t){super(`Graph drained: ${e}`,t);p(this,"reason");this.name="GraphDrained",this.reason=e}static get unminifiable_name(){return"GraphDrained"}};function Q0(n){return n!==void 0&&n.name===tx.unminifiable_name}var Oo=class extends uw{constructor(e,t){super(JSON.stringify(e,null,2),t);p(this,"interrupts");this.name="GraphInterrupt",this.interrupts=e??[]}static get unminifiable_name(){return"GraphInterrupt"}},nx=class extends Oo{constructor(n,e){super([{value:n}],e),this.name="NodeInterrupt"}static get unminifiable_name(){return"NodeInterrupt"}},E3=class{constructor(n,e){p(this,"node");p(this,"error");this.node=n,this.error=e}static get unminifiable_name(){return"NodeError"}},rx=class extends uw{constructor(e){super();p(this,"command");this.name="ParentCommand",this.command=e}static get unminifiable_name(){return"ParentCommand"}};function k3(n){return n!==void 0&&n.name===rx.unminifiable_name}function au(n){return n!==void 0&&n.is_bubble_up===!0}function oa(n){return n!==void 0&&[Oo.unminifiable_name,nx.unminifiable_name].includes(n.name)}var I3=class extends ti{constructor(e,t){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,t);p(this,"node");p(this,"kind");p(this,"timeout");p(this,"elapsed");p(this,"runTimeout");p(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"}},eS=class extends ti{constructor(n,e){super(n,e),this.name="EmptyInputError"}static get unminifiable_name(){return"EmptyInputError"}},on=class extends ti{constructor(n,e){const t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(n,e),Error.stackTraceLimit=t,this.name="EmptyChannelError"}static get unminifiable_name(){return"EmptyChannelError"}},vt=class extends ti{constructor(n,e){super(n,e),this.name="InvalidUpdateError"}static get unminifiable_name(){return"InvalidUpdateError"}},x3=class extends ti{constructor(n,e){super(n,e),this.name="UnreachableNodeError"}static get unminifiable_name(){return"UnreachableNodeError"}},gm=class extends ti{constructor(n,e){super(n,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"}};let _m=0,Pc=0;function sx(n){let e=Date.now();return e<=_m?(Pc+=1,Pc>=1e4&&(Pc=0,e=_m+1)):Pc=0,_m=e,SE({clockseq:n,msecs:e,nsecs:Pc})}function ca(n,e){const t=e.replace(/-/g,"").match(/.{2}/g).map(r=>parseInt(r,16));return jh(n,new Uint8Array(t))}const O3="__error__",sh="__scheduled__",C3="__interrupt__",$3="__resume__";var lw=class{constructor(n){p(this,"lg_name","DeltaSnapshot");p(this,"value");this.value=n}},tS="[...]",R3="[Circular]",nf=[],bo=[];function P3(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function N3(n,e,t,r){typeof r>"u"&&(r=P3()),o_(n,"",0,[],void 0,0,r);var s;try{bo.length===0?s=JSON.stringify(n,e,t):s=JSON.stringify(n,M3(e),t)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;nf.length!==0;){var i=nf.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return s}function ym(n,e,t,r){var s=Object.getOwnPropertyDescriptor(r,t);s.get!==void 0?s.configurable?(Object.defineProperty(r,t,{value:n}),nf.push([r,t,e,s])):bo.push([e,t,n]):(r[t]=n,nf.push([r,t,e]))}function o_(n,e,t,r,s,i,a){i+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){ym(R3,n,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){ym(tS,n,e,s);return}if(typeof a.edgesLimit<"u"&&t+1>a.edgesLimit){ym(tS,n,e,s);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)o_(n[o],o,o,r,n,i,a);else{var c=Object.keys(n);for(o=0;o<c.length;o++){var u=c[o];o_(n[u],u,o,r,n,i,a)}}r.pop()}}function M3(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(bo.length>0)for(var r=0;r<bo.length;r++){var s=bo[r];if(s[1]===e&&s[0]===t){t=s[2],bo.splice(r,1);break}}return n.call(this,e,t)}}const j3=[];var L3=he({}),D3=he({});/**
|
|
166
|
+
* [js-sha256]{@link https://github.com/emn178/js-sha256}
|
|
167
|
+
*
|
|
168
|
+
* @version 0.11.1
|
|
169
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
170
|
+
* @copyright Chen, Yi-Cyuan 2014-2025
|
|
171
|
+
* @license MIT
|
|
172
|
+
*/var me="0123456789abcdef".split(""),U3=[-2147483648,8388608,32768,128],Lr=[24,16,8,0],pd=[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],tn=[];function Xr(n,e){e?(tn[0]=tn[16]=tn[1]=tn[2]=tn[3]=tn[4]=tn[5]=tn[6]=tn[7]=tn[8]=tn[9]=tn[10]=tn[11]=tn[12]=tn[13]=tn[14]=tn[15]=0,this.blocks=tn):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n?(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=n}Xr.prototype.update=function(n){if(!this.finalized){var e,t=typeof n;if(t!=="string"){if(t==="object"){if(n===null)throw new Error(ERROR);if(ARRAY_BUFFER&&n.constructor===ArrayBuffer)n=new Uint8Array(n);else if(!Array.isArray(n)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(n)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,s=0,i,a=n.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]|=n[s]<<Lr[i++&3];else for(i=this.start;s<a&&i<64;++s)r=n.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|n.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}};Xr.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var n=this.blocks,e=this.lastByteIndex;n[16]=this.block,n[e>>>2]|=U3[e&3],this.block=n[16],e>=56&&(this.hashed||this.hash(),n[0]=this.block,n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),n[14]=this.hBytes<<3|this.bytes>>>29,n[15]=this.bytes<<3,this.hash()}};Xr.prototype.hash=function(){var n=this.h0,e=this.h1,t=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,m,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&t,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=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),y=n&e,f=y^n&t^w,g=s&i^~s&a,h=o+d+g+pd[u]+c[u],m=l+f,o=r+h<<0,r=h+m<<0),l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=r&n,f=b^r&e^y,g=a&o^~a&s,h=i+d+g+pd[u+1]+c[u+1],m=l+f,a=t+h<<0,t=h+m<<0,l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),_=t&r,f=_^t&n^b,g=i&a^~i&o,h=s+d+g+pd[u+2]+c[u+2],m=l+f,i=e+h<<0,e=h+m<<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&t,f=w^e&r^_,g=i&a^~i&o,h=s+d+g+pd[u+3]+c[u+3],m=l+f,s=n+h<<0,n=h+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+n<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<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};Xr.prototype.hex=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,c=me[n>>>28&15]+me[n>>>24&15]+me[n>>>20&15]+me[n>>>16&15]+me[n>>>12&15]+me[n>>>8&15]+me[n>>>4&15]+me[n&15]+me[e>>>28&15]+me[e>>>24&15]+me[e>>>20&15]+me[e>>>16&15]+me[e>>>12&15]+me[e>>>8&15]+me[e>>>4&15]+me[e&15]+me[t>>>28&15]+me[t>>>24&15]+me[t>>>20&15]+me[t>>>16&15]+me[t>>>12&15]+me[t>>>8&15]+me[t>>>4&15]+me[t&15]+me[r>>>28&15]+me[r>>>24&15]+me[r>>>20&15]+me[r>>>16&15]+me[r>>>12&15]+me[r>>>8&15]+me[r>>>4&15]+me[r&15]+me[s>>>28&15]+me[s>>>24&15]+me[s>>>20&15]+me[s>>>16&15]+me[s>>>12&15]+me[s>>>8&15]+me[s>>>4&15]+me[s&15]+me[i>>>28&15]+me[i>>>24&15]+me[i>>>20&15]+me[i>>>16&15]+me[i>>>12&15]+me[i>>>8&15]+me[i>>>4&15]+me[i&15]+me[a>>>28&15]+me[a>>>24&15]+me[a>>>20&15]+me[a>>>16&15]+me[a>>>12&15]+me[a>>>8&15]+me[a>>>4&15]+me[a&15];return this.is224||(c+=me[o>>>28&15]+me[o>>>24&15]+me[o>>>20&15]+me[o>>>16&15]+me[o>>>12&15]+me[o>>>8&15]+me[o>>>4&15]+me[o&15]),c};Xr.prototype.toString=Xr.prototype.hex;Xr.prototype.digest=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4,i=this.h5,a=this.h6,o=this.h7,c=[n>>>24&255,n>>>16&255,n>>>8&255,n&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&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};Xr.prototype.array=Xr.prototype.digest;Xr.prototype.arrayBuffer=function(){this.finalize();var n=new ArrayBuffer(this.is224?28:32),e=new DataView(n);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),n};const dw=(...n)=>new Xr(!1,!0).update(n.join("")).hex();var z3=he({sha256:()=>dw}),F3=he({BaseCache:()=>ax,InMemoryCache:()=>ox,defaultHashKeyEncoder:()=>ix,deserializeStoredGeneration:()=>B3,serializeGeneration:()=>H3});const ix=(...n)=>dw(n.join("_"));function B3(n){return n.message!==void 0?{text:n.text,message:Oy(n.message)}:{text:n.text}}function H3(n){const e={text:n.text};return n.message!==void 0&&(e.message=n.message.toDict()),e}var ax=class{constructor(){p(this,"keyEncoder",ix)}makeDefaultKeyEncoder(e){this.keyEncoder=e}};const V3=new Map;var ox=class cx extends ax{constructor(t){super();p(this,"cache");this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,s){this.cache.set(this.keyEncoder(t,r),s)}static global(){return new cx(V3)}},Z3=he({BaseChatMessageHistory:()=>ux,BaseListChatMessageHistory:()=>hw,InMemoryChatMessageHistory:()=>K3}),ux=class extends kr{async addMessages(n){for(const e of n)await this.addMessage(e)}},hw=class extends kr{addUserMessage(n){return this.addMessage(new Dn(n))}addAIMessage(n){return this.addMessage(new Ve(n))}async addMessages(n){for(const e of n)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},K3=class extends hw{constructor(e){super(...arguments);p(this,"lc_namespace",["langchain","stores","message","in_memory"]);p(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},Oi=class{constructor(n){p(this,"pageContent");p(this,"metadata");p(this,"id");this.pageContent=n.pageContent!==void 0?n.pageContent.toString():"",this.metadata=n.metadata??{},this.id=n.id}},lx=class extends Ge{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","documents","transformers"])}invoke(e,t){return this.transformDocuments(e)}},W3=class extends lx{async transformDocuments(n){const e=[];for(const t of n){const r=await this._transformDocument(t);e.push(r)}return e}},q3=he({BaseDocumentTransformer:()=>lx,Document:()=>Oi,MappingDocumentTransformer:()=>W3}),G3=he({BaseDocumentLoader:()=>dx}),dx=class{},J3=he({LangSmithLoader:()=>Y3}),Y3=class extends dx{constructor(e){super();p(this,"datasetId");p(this,"datasetName");p(this,"exampleIds");p(this,"asOf");p(this,"splits");p(this,"inlineS3Urls");p(this,"offset");p(this,"limit");p(this,"metadata");p(this,"filter");p(this,"contentKey");p(this,"formatContent");p(this,"client");if(e.client&&e.clientConfig)throw new Error("client and clientConfig cannot both be provided.");this.client=e.client??new ds(e==null?void 0:e.clientConfig),this.contentKey=e.contentKey?e.contentKey.split("."):[],this.formatContent=e.formatContent??X3,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 t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let r=t.inputs;for(const a of this.contentKey)r=r[a];const s=this.formatContent(r),i=t;["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 X3(n){if(typeof n=="string")return n;try{return JSON.stringify(n,null,2)}catch{return String(n)}}var Q3=he({Embeddings:()=>fw}),fw=class{constructor(e){p(this,"caller");this.caller=new Ml(e??{})}},pw=class extends kr{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","example_selectors","base"])}},hx=class{async getPromptAsync(n,e){return this.getPrompt(n).partial((e==null?void 0:e.partialVariables)??{})}},e6=class extends hx{constructor(e,t=[]){super();p(this,"defaultPrompt");p(this,"conditionals");this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(const[t,r]of this.conditionals)if(t(e))return r;return this.defaultPrompt}};function t6(n){return n._modelType()==="base_llm"}function n6(n){return n._modelType()==="base_chat_model"}function nS(n){return n.split(/\n| /).length}var r6=class fx extends pw{constructor(t){super(t);p(this,"examples",[]);p(this,"examplePrompt");p(this,"getTextLength",nS);p(this,"maxLength",2048);p(this,"exampleTextLengths",[]);this.examplePrompt=t.examplePrompt,this.maxLength=t.maxLength??2048,this.getTextLength=t.getTextLength??nS}async addExample(t){this.examples.push(t);const r=await this.examplePrompt.format(t);this.exampleTextLengths.push(this.getTextLength(r))}async calculateExampleTextLengths(t,r){if(t.length>0)return t;const{examples:s,examplePrompt:i}=r;return(await Promise.all(s.map(a=>i.format(a)))).map(a=>this.getTextLength(a))}async selectExamples(t){const r=Object.values(t).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(t,r){const s=new fx(r);return await Promise.all(t.map(i=>s.addExample(i))),s}};function wm(n){return Object.keys(n).sort().map(e=>n[e])}var s6=class px extends pw{constructor(t){super(t);p(this,"vectorStoreRetriever");p(this,"exampleKeys");p(this,"inputKeys");if(this.exampleKeys=t.exampleKeys,this.inputKeys=t.inputKeys,t.vectorStore!==void 0)this.vectorStoreRetriever=t.vectorStore.asRetriever({k:t.k??4,filter:t.filter});else if(t.vectorStoreRetriever)this.vectorStoreRetriever=t.vectorStoreRetriever;else throw new Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(t){const r=wm((this.inputKeys??Object.keys(t)).reduce((s,i)=>({...s,[i]:t[i]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new Oi({pageContent:r,metadata:t})])}async selectExamples(t){const r=wm((this.inputKeys??Object.keys(t)).reduce((i,a)=>({...i,[a]:t[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(t,r,s,i={}){const a=i.inputKeys??null,o=t.map(c=>wm(a?a.reduce((u,l)=>({...u,[l]:c[l]}),{}):c).join(" "));return new px({vectorStore:await s.fromTexts(o,t,r,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},i6=he({BaseExampleSelector:()=>pw,BasePromptSelector:()=>hx,ConditionalPromptSelector:()=>e6,LengthBasedExampleSelector:()=>r6,SemanticSimilarityExampleSelector:()=>s6,isChatModel:()=>n6,isLLM:()=>t6});const c_="10f90ea3-90a4-4962-bf75-83a0f3c1c62a";var a6=class extends kr{constructor(){super(...arguments);p(this,"lc_namespace",["langchain","recordmanagers"])}},mx=class{constructor(n){p(this,"uid");p(this,"hash_");p(this,"contentHash");p(this,"metadataHash");p(this,"pageContent");p(this,"metadata");p(this,"keyEncoder",dw);this.uid=n.uid,this.pageContent=n.pageContent,this.metadata=n.metadata}makeDefaultKeyEncoder(n){this.keyEncoder=n}calculateHashes(){const n=["hash_","content_hash","metadata_hash"];for(const t of n)if(t in this.metadata)throw new Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${n.join(", ")}]`);const e=this._hashStringToUUID(this.pageContent);try{const t=this._hashNestedDictToUUID(this.metadata);this.contentHash=e,this.metadataHash=t}catch(t){throw new Error(`Failed to hash metadata: ${t}. 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 Oi({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(n,e){const t=new this({pageContent:n.pageContent,metadata:n.metadata,uid:e||n.uid});return t.calculateHashes(),t}_hashStringToUUID(n){return jh(this.keyEncoder(n),c_)}_hashNestedDictToUUID(n){const e=JSON.stringify(n,Object.keys(n).sort());return jh(this.keyEncoder(e),c_)}};function gx(n,e){const t=[];let r=[];return e.forEach(s=>{r.push(s),r.length>=n&&(t.push(r),r=[])}),r.length>0&&t.push(r),t}function _x(n){const e=new Set,t=[];for(const r of n){if(!r.hash_)throw new Error("Hashed document does not have a hash");e.has(r.hash_)||(e.add(r.hash_),t.push(r))}return t}function yx(n){if(n===null)return e=>null;if(typeof n=="string")return e=>e.metadata[n];if(typeof n=="function")return n;throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof n}`)}const wx=n=>"load"in n&&typeof n.load=="function"&&"loadAndSplit"in n&&typeof n.loadAndSplit=="function";async function o6(n){const{docsSource:e,recordManager:t,vectorStore:r,options:s}=n,{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=wx(e)?await e.load():e,d=yx(o??null),f=await t.getTime();let h=0,m=0,g=0,y=0;const b=gx(i??100,l);for(const _ of b){const w=_x(_.map(x=>mx.fromDocument(x))),S=w.map(x=>d(x));a==="incremental"&&w.forEach((x,O)=>{if(S[O]===null)throw new Error("sourceIdKey must be provided when cleanup is incremental")});const T=await t.exists(w.map(x=>x.uid)),A=[],I=[],k=[],R=new Set;if(w.forEach((x,O)=>{if(T[O])if(u)R.add(x.uid);else{k.push(x.uid);return}A.push(x.uid),I.push(x.toDocument())}),k.length>0&&(await t.update(k,{timeAtLeast:f}),y+=k.length),I.length>0&&(await r.addDocuments(I,{ids:A}),h+=I.length-R.size,g+=R.size),await t.update(w.map(x=>x.uid),{timeAtLeast:f,groupIds:S}),a==="incremental"){S.forEach(O=>{if(!O)throw new Error("Source id cannot be null")});const x=await t.listKeys({before:f,groupIds:S});x.length>0&&(await r.delete({ids:x}),await t.deleteKeys(x),m+=x.length)}}if(a==="full"){let _=await t.listKeys({before:f,limit:c});for(;_.length>0;)await r.delete({ids:_}),await t.deleteKeys(_),m+=_.length,_=await t.listKeys({before:f,limit:c})}return{numAdded:h,numDeleted:m,numUpdated:g,numSkipped:y}}var c6=he({RecordManager:()=>a6,UUIDV5_NAMESPACE:()=>c_,_HashedDocument:()=>mx,_batch:()=>gx,_deduplicateInOrder:()=>_x,_getSourceIdAssigner:()=>yx,_isBaseDocumentLoader:()=>wx,index:()=>o6}),u6=he({BasePromptValue:()=>cp,ChatPromptValue:()=>gw,ImagePromptValue:()=>bx,StringPromptValue:()=>mw}),cp=class extends kr{},mw=class extends cp{constructor(e){super({value:e});p(this,"lc_namespace",["langchain_core","prompt_values"]);p(this,"lc_serializable",!0);p(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new Dn(this.value)]}},gw=class extends cp{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);p(this,"lc_namespace",["langchain_core","prompt_values"]);p(this,"lc_serializable",!0);p(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return xy(this.messages)}toChatMessages(){return this.messages}},bx=class extends cp{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);p(this,"lc_namespace",["langchain_core","prompt_values"]);p(this,"lc_serializable",!0);p(this,"imageUrl");p(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new Dn({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},up={};up.byteLength=h6;up.toByteArray=p6;up.fromByteArray=_6;var fs=[],Ar=[],l6=typeof Uint8Array<"u"?Uint8Array:Array,bm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Ha=0,d6=bm.length;Ha<d6;++Ha)fs[Ha]=bm[Ha],Ar[bm.charCodeAt(Ha)]=Ha;Ar[45]=62;Ar[95]=63;function vx(n){var e=n.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=n.indexOf("=");t===-1&&(t=e);var r=t===e?0:4-t%4;return[t,r]}function h6(n){var e=vx(n),t=e[0],r=e[1];return(t+r)*3/4-r}function f6(n,e,t){return(e+t)*3/4-t}function p6(n){var e,t=vx(n),r=t[0],s=t[1],i=new l6(f6(n,r,s)),a=0,o=s>0?r-4:r,c;for(c=0;c<o;c+=4)e=Ar[n.charCodeAt(c)]<<18|Ar[n.charCodeAt(c+1)]<<12|Ar[n.charCodeAt(c+2)]<<6|Ar[n.charCodeAt(c+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=Ar[n.charCodeAt(c)]<<2|Ar[n.charCodeAt(c+1)]>>4,i[a++]=e&255),s===1&&(e=Ar[n.charCodeAt(c)]<<10|Ar[n.charCodeAt(c+1)]<<4|Ar[n.charCodeAt(c+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}function m6(n){return fs[n>>18&63]+fs[n>>12&63]+fs[n>>6&63]+fs[n&63]}function g6(n,e,t){for(var r,s=[],i=e;i<t;i+=3)r=(n[i]<<16&16711680)+(n[i+1]<<8&65280)+(n[i+2]&255),s.push(m6(r));return s.join("")}function _6(n){for(var e,t=n.length,r=t%3,s=[],i=16383,a=0,o=t-r;a<o;a+=i)s.push(g6(n,a,a+i>o?o:a+i));return r===1?(e=n[t-1],s.push(fs[e>>2]+fs[e<<4&63]+"==")):r===2&&(e=(n[t-2]<<8)+n[t-1],s.push(fs[e>>10]+fs[e>>4&63]+fs[e<<2&63]+"=")),s.join("")}var y6=Object.defineProperty,w6=(n,e,t)=>e in n?y6(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,b6=(n,e,t)=>(w6(n,e+"",t),t);function v6(n,e){let t=Array.from({length:n.length},(r,s)=>({start:s,end:s+1}));for(;t.length>1;){let r=null;for(let s=0;s<t.length-1;s++){const i=n.slice(t[s].start,t[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];t[s]={start:t[s].start,end:t[s+1].end},t.splice(s+1,1)}else break}return t}function S6(n,e){return n.length===1?[e.get(n.join(","))]:v6(n,e).map(t=>e.get(n.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function A6(n){return n.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var u_=class{constructor(n,e){p(this,"specialTokens");p(this,"inverseSpecialTokens");p(this,"patStr");p(this,"textEncoder",new TextEncoder);p(this,"textDecoder",new TextDecoder("utf-8"));p(this,"rankMap",new Map);p(this,"textMap",new Map);this.patStr=n.pat_str;const t=n.bpe_ranks.split(`
|
|
173
|
+
`).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(t)){const i=up.toByteArray(r);this.rankMap.set(i.join(","),s),this.textMap.set(s,i)}this.specialTokens={...n.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,i])=>(r[i]=this.textEncoder.encode(s),r),{})}encode(n,e=[],t="all"){const r=new RegExp(this.patStr,"ug"),s=u_.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(t==="all"?Object.keys(this.specialTokens).filter(u=>!a.has(u)):t);if(o.size>0){const u=u_.specialTokenRegex([...o]),l=n.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(n),!(u==null||a.has(u[0]));)l=u.index+1;const d=(u==null?void 0:u.index)??n.length;for(const h of n.substring(c,d).matchAll(r)){const m=this.textEncoder.encode(h[0]),g=this.rankMap.get(m.join(","));if(g!=null){i.push(g);continue}i.push(...S6(m,this.rankMap))}if(u==null)break;let f=this.specialTokens[u[0]];i.push(f),c=u.index+u[0].length}return i}decode(n){const e=[];let t=0;for(let i=0;i<n.length;++i){const a=n[i],o=this.textMap.get(a)??this.inverseSpecialTokens[a];o!=null&&(e.push(o),t+=o.length)}const r=new Uint8Array(t);let s=0;for(const i of e)r.set(i,s),s+=i.length;return this.textDecoder.decode(r)}},Sx=u_;b6(Sx,"specialTokenRegex",n=>new RegExp(n.map(e=>A6(e)).join("|"),"g"));function T6(n){switch(n){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 E6=he({encodingForModel:()=>_w,getEncoding:()=>Ax});const md={},k6=new Ml({});async function Ax(n){return n in md||(md[n]=k6.fetch(`https://tiktoken.pages.dev/js/${n}.json`).then(e=>e.json()).then(e=>new Sx(e)).catch(e=>{throw delete md[n],e})),await md[n]}async function _w(n){return Ax(T6(n))}var I6=he({BaseLangChain:()=>yw,BaseLanguageModel:()=>ww,calculateMaxTokens:()=>O6,getEmbeddingContextSize:()=>x6,getModelContextSize:()=>Tx,getModelNameForTiktoken:()=>lp,isOpenAITool:()=>Sc});const lp=n=>n.startsWith("gpt-5")?"gpt-5":n.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":n.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":n.startsWith("gpt-4-32k")?"gpt-4-32k":n.startsWith("gpt-4-")?"gpt-4":n.startsWith("gpt-4o")?"gpt-4o":n,x6=n=>{switch(n){case"text-embedding-ada-002":return 8191;default:return 2046}},Tx=n=>{switch(lp(n)){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 Sc(n){return typeof n!="object"||!n?!1:!!("type"in n&&n.type==="function"&&"function"in n&&typeof n.function=="object"&&n.function&&"name"in n.function&&"parameters"in n.function)}const O6=async({prompt:n,modelName:e})=>{let t;try{t=(await _w(lp(e))).encode(n).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),t=Math.ceil(n.length/4)}return Tx(e)-t},C6=()=>!1;var yw=class extends Ge{constructor(e){super(e);p(this,"verbose");p(this,"callbacks");p(this,"tags");p(this,"metadata");this.verbose=e.verbose??C6(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.1.49")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,t){var s;const r=(s=this.metadata)==null?void 0:s.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:t}}}},ww=class extends yw{constructor({callbacks:e,callbackManager:t,...r}){const{cache:s,...i}=r;super({callbacks:e??t,...i});p(this,"caller");p(this,"cache");p(this,"_encoding");typeof s=="object"?this.cache=s:s?this.cache=ox.global():this.cache=void 0,this.caller=new Ml(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await _w("modelName"in this?lp(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(t).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 mw(e):Array.isArray(e)?new gw(e.map(ys)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_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:t,functions:r,messages:s,response_format:i,...a}=e;return a}},$6=he({applyPatch:()=>Yo,compare:()=>Zf}),Ac=class extends Ge{parseResultWithPrompt(n,e,t){return this.parseResult(n,t)}_baseMessageToString(n){return typeof n.content=="string"?n.content:this._baseMessageContentToString(n.content)}_baseMessageContentToString(n){return JSON.stringify(n)}async invoke(n,e){return typeof n=="string"?this._callWithConfig(async(t,r)=>this.parseResult([{text:t}],r==null?void 0:r.callbacks),n,{...e,runType:"parser"}):this._callWithConfig(async(t,r)=>this.parseResult([{message:t,text:this._baseMessageToString(t)}],r==null?void 0:r.callbacks),n,{...e,runType:"parser"})}},Tc=class extends Ac{parseResult(n,e){return this.parse(n[0].text,e)}async parseWithPrompt(n,e,t){return this.parse(n,t)}_type(){throw new Error("_type not implemented")}},Tn=class extends Error{constructor(e,t,r,s=!1){super(e);p(this,"llmOutput");p(this,"observation");p(this,"sendToLLM");if(this.llmOutput=t,this.observation=r,this.sendToLLM=s,s&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Il(this,"OUTPUT_PARSING_FAILURE")}},Ll=class extends Tc{async*_transform(n){for await(const e of n)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(n,e){yield*this._transformStreamWithConfig(n,this._transform.bind(this),{...e,runType:"parser"})}},Dl=class extends Ll{constructor(e){super(e);p(this,"diff",!1);this.diff=(e==null?void 0:e.diff)??this.diff}async*_transform(e){let t,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(Go(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");i=new fr({message:s,text:s.content})}else if(Rt(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");i=new fr({message:Nh(s),text:s.content})}else i=new Xo({text:s});r===void 0?r=i:r=r.concat(i);const a=await this.parsePartialResult([r]);a!=null&&!Sa(a,t)&&(this.diff?yield this._diff(t,a):yield a,t=a)}}getFormatInstructions(){return""}},R6=class extends Ll{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);p(this,"lc_serializable",!0);p(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},Ul=class extends Ll{constructor(){super(...arguments);p(this,"re")}async*_transform(e){let t="";for await(const r of e)if(typeof r=="string"?t+=r:t+=r.content,this.re){const s=[...t.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;t=t.slice(i)}}else{const s=await this.parse(t);if(s.length>1){for(const i of s.slice(0,-1))yield[i];t=s[s.length-1]}}for(const r of await this.parse(t))yield[r]}},P6=class extends Ul{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new Tn(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},N6=class extends Ul{constructor({length:e,separator:t}){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"length");p(this,"separator");this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&t.length!==this.length)throw new Tn(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===Tn.prototype?t:new Tn(`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\`)`}},M6=class extends Ul{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"lc_serializable",!0);p(this,"re",/\d+\.\s([^\n]+)/g)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
174
|
+
|
|
175
|
+
1. foo
|
|
176
|
+
|
|
177
|
+
2. bar
|
|
178
|
+
|
|
179
|
+
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},j6=class extends Ul{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","list"]);p(this,"lc_serializable",!0);p(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
180
|
+
|
|
181
|
+
1. foo
|
|
182
|
+
|
|
183
|
+
2. bar
|
|
184
|
+
|
|
185
|
+
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},L6=class extends Ll{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers","string"]);p(this,"lc_serializable",!0)}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,r)=>t+this._messageContentToString(r),"")}},bw=class extends Dl{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","output_parsers"]);p(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Zf(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return Rh(e[0].text)}async parse(e){return Rh(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}},Ex=class extends Tc{constructor(e){super();p(this,"lc_namespace",["langchain","output_parsers","standard_schema"]);p(this,"schema");this.schema=e}static lc_name(){return"StandardSchemaOutputParser"}static fromSerializableSchema(e){return new this(e)}async parse(e){try{const t=Rh(e,JSON.parse),r=await this.schema["~standard"].validate(t);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(t){throw new Tn(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}},vw=class extends Tc{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=ap(Object.fromEntries(Object.entries(e).map(([r,s])=>[r,ip().describe(s)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
186
|
+
|
|
187
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
188
|
+
|
|
189
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
190
|
+
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.
|
|
191
|
+
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.
|
|
192
|
+
|
|
193
|
+
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!
|
|
194
|
+
|
|
195
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
196
|
+
\`\`\`json
|
|
197
|
+
${JSON.stringify(At(this.schema))}
|
|
198
|
+
\`\`\`
|
|
199
|
+
`}async parse(e){var t,r;try{const s=e.trim(),i=(((t=s.match(/^```(?:json)?\s*([\s\S]*?)```/))==null?void 0:t[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 np(this.schema,JSON.parse(i))}catch(s){throw new Tn(`Failed to parse. Text: "${e}". Error: ${s}`,e)}}_baseMessageToString(e){return e.text}},kx=class extends vw{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(n){const e=(n==null?void 0:n.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:
|
|
200
|
+
\`\`\`json
|
|
201
|
+
${this._schemaToInstruction(At(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
|
|
202
|
+
\`\`\``}_schemaToInstruction(n,e=2){const t=n;if("type"in t){let r=!1,s;if(Array.isArray(t.type)){const o=t.type.findIndex(c=>c==="null");o!==-1&&(r=!0,t.type.splice(o,1)),s=t.type.join(" | ")}else s=t.type;if(t.type==="object"&&t.properties){const o=t.description?` // ${t.description}`:"";return`{
|
|
203
|
+
${Object.entries(t.properties).map(([c,u])=>{var d;const l=(d=t.required)!=null&&d.includes(c)?"":" (optional)";return`${" ".repeat(e)}"${c}": ${this._schemaToInstruction(u,e+2)}${l}`}).join(`
|
|
204
|
+
`)}
|
|
205
|
+
${" ".repeat(e-2)}}${o}`}if(t.type==="array"&&t.items){const o=t.description?` // ${t.description}`:"";return`array[
|
|
206
|
+
${" ".repeat(e)}${this._schemaToInstruction(t.items,e+2)}
|
|
207
|
+
${" ".repeat(e-2)}] ${o}`}const i=r?" (nullable)":"",a=t.description?` // ${t.description}`:"";return`${s}${a}${i}`}if("anyOf"in t)return t.anyOf.map(r=>this._schemaToInstruction(r,e)).join(`
|
|
208
|
+
${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(n){return new this(n)}static fromNamesAndDescriptions(n){const e=ap(Object.fromEntries(Object.entries(n).map(([t,r])=>[t,ip().describe(r)])));return new this(e)}},D6=class extends Tc{constructor({inputSchema:e}){super(...arguments);p(this,"structuredInputParser");this.structuredInputParser=new kx(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(r){throw new Tn(`Failed to parse. Text: "${e}". Error: ${r}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};const U6=function(){const n={};n.parser=function(E,v){return new t(E,v)},n.SAXParser=t,n.SAXStream=u,n.createStream=c,n.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];n.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function t(E,v){if(!(this instanceof t))return new t(E,v);var j=this;s(j),j.q=j.c="",j.bufferCheckPosition=n.MAX_BUFFER_LENGTH,j.opt=v||{},j.opt.lowercase=j.opt.lowercase||j.opt.lowercasetags,j.looseCase=j.opt.lowercase?"toLowerCase":"toUpperCase",j.tags=[],j.closed=j.closedRoot=j.sawRoot=!1,j.tag=j.error=null,j.strict=!!E,j.noscript=!!(E||j.opt.noscript),j.state=k.BEGIN,j.strictEntities=j.opt.strictEntities,j.ENTITIES=j.strictEntities?Object.create(n.XML_ENTITIES):Object.create(n.ENTITIES),j.attribList=[],j.opt.xmlns&&(j.ns=Object.create(m)),j.trackPosition=j.opt.position!==!1,j.trackPosition&&(j.position=j.line=j.column=0),x(j,"onready")}Object.create||(Object.create=function(E){function v(){}return v.prototype=E,new v}),Object.keys||(Object.keys=function(E){var v=[];for(var j in E)E.hasOwnProperty(j)&&v.push(j);return v});function r(E){for(var v=Math.max(n.MAX_BUFFER_LENGTH,10),j=0,C=0,_e=e.length;C<_e;C++){var xe=E[e[C]].length;if(xe>v)switch(e[C]){case"textNode":U(E);break;case"cdata":O(E,"oncdata",E.cdata),E.cdata="";break;case"script":O(E,"onscript",E.script),E.script="";break;default:F(E,"Max buffer length exceeded: "+e[C])}j=Math.max(j,xe)}E.bufferCheckPosition=n.MAX_BUFFER_LENGTH-j+E.position}function s(E){for(var v=0,j=e.length;v<j;v++)E[e[v]]=""}function i(E){U(E),E.cdata!==""&&(O(E,"oncdata",E.cdata),E.cdata=""),E.script!==""&&(O(E,"onscript",E.script),E.script="")}t.prototype={end:function(){Y(this)},write:de,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=n.EVENTS.filter(function(E){return E!=="error"&&E!=="end"});function c(E,v){return new u(E,v)}function u(E,v){if(!(this instanceof u))return new u(E,v);a.apply(this),this._parser=new t(E,v),this.writable=!0,this.readable=!0;var j=this;this._parser.onend=function(){j.emit("end")},this._parser.onerror=function(C){j.emit("error",C),j._parser.error=null},this._decoder=null,o.forEach(function(C){Object.defineProperty(j,"on"+C,{get:function(){return j._parser["on"+C]},set:function(_e){if(!_e)return j.removeAllListeners(C),j._parser["on"+C]=_e,_e;j.on(C,_e)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(a.prototype,{constructor:{value:u}}),u.prototype.write=function(E){return this._parser.write(E.toString()),this.emit("data",E),!0},u.prototype.end=function(E){return E&&E.length&&this.write(E),this._parser.end(),!0},u.prototype.on=function(E,v){var j=this;return!j._parser["on"+E]&&o.indexOf(E)!==-1&&(j._parser["on"+E]=function(){var C=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);C.splice(0,0,E),j.emit.apply(j,C)}),a.prototype.on.call(j,E,v)};var l="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:h},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(E){return E===" "||E===`
|
|
209
|
+
`||E==="\r"||E===" "}function S(E){return E==='"'||E==="'"}function T(E){return E===">"||w(E)}function A(E,v){return E.test(v)}function I(E,v){return!A(E,v)}var k=0;n.STATE={BEGIN:k++,BEGIN_WHITESPACE:k++,TEXT:k++,TEXT_ENTITY:k++,OPEN_WAKA:k++,SGML_DECL:k++,SGML_DECL_QUOTED:k++,DOCTYPE:k++,DOCTYPE_QUOTED:k++,DOCTYPE_DTD:k++,DOCTYPE_DTD_QUOTED:k++,COMMENT_STARTING:k++,COMMENT:k++,COMMENT_ENDING:k++,COMMENT_ENDED:k++,CDATA:k++,CDATA_ENDING:k++,CDATA_ENDING_2:k++,PROC_INST:k++,PROC_INST_BODY:k++,PROC_INST_ENDING:k++,OPEN_TAG:k++,OPEN_TAG_SLASH:k++,ATTRIB:k++,ATTRIB_NAME:k++,ATTRIB_NAME_SAW_WHITE:k++,ATTRIB_VALUE:k++,ATTRIB_VALUE_QUOTED:k++,ATTRIB_VALUE_CLOSED:k++,ATTRIB_VALUE_UNQUOTED:k++,ATTRIB_VALUE_ENTITY_Q:k++,ATTRIB_VALUE_ENTITY_U:k++,CLOSE_TAG:k++,CLOSE_TAG_SAW_WHITE:k++,SCRIPT:k++,SCRIPT_ENDING:k++},n.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},n.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(n.ENTITIES).forEach(function(E){var v=n.ENTITIES[E],j=typeof v=="number"?String.fromCharCode(v):v;n.ENTITIES[E]=j});for(var R in n.STATE)n.STATE[n.STATE[R]]=R;k=n.STATE;function x(E,v,j){E[v]&&E[v](j)}function O(E,v,j){E.textNode&&U(E),x(E,v,j)}function U(E){E.textNode=B(E.opt,E.textNode),E.textNode&&x(E,"ontext",E.textNode),E.textNode=""}function B(E,v){return E.trim&&(v=v.trim()),E.normalize&&(v=v.replace(/\s+/g," ")),v}function F(E,v){return U(E),E.trackPosition&&(v+=`
|
|
210
|
+
Line: `+E.line+`
|
|
211
|
+
Column: `+E.column+`
|
|
212
|
+
Char: `+E.c),v=new Error(v),E.error=v,x(E,"onerror",v),E}function Y(E){return E.sawRoot&&!E.closedRoot&&Z(E,"Unclosed root tag"),E.state!==k.BEGIN&&E.state!==k.BEGIN_WHITESPACE&&E.state!==k.TEXT&&F(E,"Unexpected end"),U(E),E.c="",E.closed=!0,x(E,"onend"),t.call(E,E.strict,E.opt),E}function Z(E,v){if(typeof E!="object"||!(E instanceof t))throw new Error("bad call to strictFail");E.strict&&F(E,v)}function ge(E){E.strict||(E.tagName=E.tagName[E.looseCase]());var v=E.tags[E.tags.length-1]||E,j=E.tag={name:E.tagName,attributes:{}};E.opt.xmlns&&(j.ns=v.ns),E.attribList.length=0,O(E,"onopentagstart",j)}function M(E,v){var j=E.indexOf(":")<0?["",E]:E.split(":"),C=j[0],_e=j[1];return v&&E==="xmlns"&&(C="xmlns",_e=""),{prefix:C,local:_e}}function K(E){if(E.strict||(E.attribName=E.attribName[E.looseCase]()),E.attribList.indexOf(E.attribName)!==-1||E.tag.attributes.hasOwnProperty(E.attribName)){E.attribName=E.attribValue="";return}if(E.opt.xmlns){var v=M(E.attribName,!0),j=v.prefix,C=v.local;if(j==="xmlns")if(C==="xml"&&E.attribValue!==f)Z(E,"xml: prefix must be bound to "+f+`
|
|
213
|
+
Actual: `+E.attribValue);else if(C==="xmlns"&&E.attribValue!==h)Z(E,"xmlns: prefix must be bound to "+h+`
|
|
214
|
+
Actual: `+E.attribValue);else{var _e=E.tag,xe=E.tags[E.tags.length-1]||E;_e.ns===xe.ns&&(_e.ns=Object.create(xe.ns)),_e.ns[C]=E.attribValue}E.attribList.push([E.attribName,E.attribValue])}else E.tag.attributes[E.attribName]=E.attribValue,O(E,"onattribute",{name:E.attribName,value:E.attribValue});E.attribName=E.attribValue=""}function se(E,v){if(E.opt.xmlns){var j=E.tag,C=M(E.tagName);j.prefix=C.prefix,j.local=C.local,j.uri=j.ns[C.prefix]||"",j.prefix&&!j.uri&&(Z(E,"Unbound namespace prefix: "+JSON.stringify(E.tagName)),j.uri=C.prefix);var _e=E.tags[E.tags.length-1]||E;j.ns&&_e.ns!==j.ns&&Object.keys(j.ns).forEach(function(vn){O(E,"onopennamespace",{prefix:vn,uri:j.ns[vn]})});for(var xe=0,dt=E.attribList.length;xe<dt;xe++){var Qe=E.attribList[xe],yt=Qe[0],Ot=Qe[1],Ue=M(yt,!0),Dt=Ue.prefix,bn=Ue.local,yr=Dt===""?"":j.ns[Dt]||"",L={name:yt,value:Ot,prefix:Dt,local:bn,uri:yr};Dt&&Dt!=="xmlns"&&!yr&&(Z(E,"Unbound namespace prefix: "+JSON.stringify(Dt)),L.uri=Dt),E.tag.attributes[yt]=L,O(E,"onattribute",L)}E.attribList.length=0}E.tag.isSelfClosing=!!v,E.sawRoot=!0,E.tags.push(E.tag),O(E,"onopentag",E.tag),v||(!E.noscript&&E.tagName.toLowerCase()==="script"?E.state=k.SCRIPT:E.state=k.TEXT,E.tag=null,E.tagName=""),E.attribName=E.attribValue="",E.attribList.length=0}function oe(E){if(!E.tagName){Z(E,"Weird empty close tag."),E.textNode+="</>",E.state=k.TEXT;return}if(E.script){if(E.tagName!=="script"){E.script+="</"+E.tagName+">",E.tagName="",E.state=k.SCRIPT;return}O(E,"onscript",E.script),E.script=""}var v=E.tags.length,j=E.tagName;E.strict||(j=j[E.looseCase]());for(var C=j;v--&&E.tags[v].name!==C;)Z(E,"Unexpected close tag");if(v<0){Z(E,"Unmatched closing tag: "+E.tagName),E.textNode+="</"+E.tagName+">",E.state=k.TEXT;return}E.tagName=j;for(var _e=E.tags.length;_e-- >v;){var xe=E.tag=E.tags.pop();E.tagName=E.tag.name,O(E,"onclosetag",E.tagName);var dt={};for(var Qe in xe.ns)dt[Qe]=xe.ns[Qe];var yt=E.tags[E.tags.length-1]||E;E.opt.xmlns&&xe.ns!==yt.ns&&Object.keys(xe.ns).forEach(function(Ot){var Ue=xe.ns[Ot];O(E,"onclosenamespace",{prefix:Ot,uri:Ue})})}v===0&&(E.closedRoot=!0),E.tagName=E.attribValue=E.attribName="",E.attribList.length=0,E.state=k.TEXT}function X(E){var v=E.entity,j=v.toLowerCase(),C,_e="";return E.ENTITIES[v]?E.ENTITIES[v]:E.ENTITIES[j]?E.ENTITIES[j]:(v=j,v.charAt(0)==="#"&&(v.charAt(1)==="x"?(v=v.slice(2),C=parseInt(v,16),_e=C.toString(16)):(v=v.slice(1),C=parseInt(v,10),_e=C.toString(10))),v=v.replace(/^0+/,""),isNaN(C)||_e.toLowerCase()!==v?(Z(E,"Invalid character entity"),"&"+E.entity+";"):String.fromCodePoint(C))}function ie(E,v){v==="<"?(E.state=k.OPEN_WAKA,E.startTagPosition=E.position):w(v)||(Z(E,"Non-whitespace before first tag."),E.textNode=v,E.state=k.TEXT)}function Ee(E,v){var j="";return v<E.length&&(j=E.charAt(v)),j}function de(E){var v=this;if(this.error)throw this.error;if(v.closed)return F(v,"Cannot write after close. Assign an onready handler.");if(E===null)return Y(v);typeof E=="object"&&(E=E.toString());for(var j=0,C="";C=Ee(E,j++),v.c=C,!!C;)switch(v.trackPosition&&(v.position++,C===`
|
|
215
|
+
`?(v.line++,v.column=0):v.column++),v.state){case k.BEGIN:if(v.state=k.BEGIN_WHITESPACE,C==="\uFEFF")continue;ie(v,C);continue;case k.BEGIN_WHITESPACE:ie(v,C);continue;case k.TEXT:if(v.sawRoot&&!v.closedRoot){for(var _e=j-1;C&&C!=="<"&&C!=="&";)C=Ee(E,j++),C&&v.trackPosition&&(v.position++,C===`
|
|
216
|
+
`?(v.line++,v.column=0):v.column++);v.textNode+=E.substring(_e,j-1)}C==="<"&&!(v.sawRoot&&v.closedRoot&&!v.strict)?(v.state=k.OPEN_WAKA,v.startTagPosition=v.position):(!w(C)&&(!v.sawRoot||v.closedRoot)&&Z(v,"Text data outside of root node."),C==="&"?v.state=k.TEXT_ENTITY:v.textNode+=C);continue;case k.SCRIPT:C==="<"?v.state=k.SCRIPT_ENDING:v.script+=C;continue;case k.SCRIPT_ENDING:C==="/"?v.state=k.CLOSE_TAG:(v.script+="<"+C,v.state=k.SCRIPT);continue;case k.OPEN_WAKA:if(C==="!")v.state=k.SGML_DECL,v.sgmlDecl="";else if(!w(C))if(A(g,C))v.state=k.OPEN_TAG,v.tagName=C;else if(C==="/")v.state=k.CLOSE_TAG,v.tagName="";else if(C==="?")v.state=k.PROC_INST,v.procInstName=v.procInstBody="";else{if(Z(v,"Unencoded <"),v.startTagPosition+1<v.position){var xe=v.position-v.startTagPosition;C=new Array(xe).join(" ")+C}v.textNode+="<"+C,v.state=k.TEXT}continue;case k.SGML_DECL:(v.sgmlDecl+C).toUpperCase()===l?(O(v,"onopencdata"),v.state=k.CDATA,v.sgmlDecl="",v.cdata=""):v.sgmlDecl+C==="--"?(v.state=k.COMMENT,v.comment="",v.sgmlDecl=""):(v.sgmlDecl+C).toUpperCase()===d?(v.state=k.DOCTYPE,(v.doctype||v.sawRoot)&&Z(v,"Inappropriately located doctype declaration"),v.doctype="",v.sgmlDecl=""):C===">"?(O(v,"onsgmldeclaration",v.sgmlDecl),v.sgmlDecl="",v.state=k.TEXT):(S(C)&&(v.state=k.SGML_DECL_QUOTED),v.sgmlDecl+=C);continue;case k.SGML_DECL_QUOTED:C===v.q&&(v.state=k.SGML_DECL,v.q=""),v.sgmlDecl+=C;continue;case k.DOCTYPE:C===">"?(v.state=k.TEXT,O(v,"ondoctype",v.doctype),v.doctype=!0):(v.doctype+=C,C==="["?v.state=k.DOCTYPE_DTD:S(C)&&(v.state=k.DOCTYPE_QUOTED,v.q=C));continue;case k.DOCTYPE_QUOTED:v.doctype+=C,C===v.q&&(v.q="",v.state=k.DOCTYPE);continue;case k.DOCTYPE_DTD:v.doctype+=C,C==="]"?v.state=k.DOCTYPE:S(C)&&(v.state=k.DOCTYPE_DTD_QUOTED,v.q=C);continue;case k.DOCTYPE_DTD_QUOTED:v.doctype+=C,C===v.q&&(v.state=k.DOCTYPE_DTD,v.q="");continue;case k.COMMENT:C==="-"?v.state=k.COMMENT_ENDING:v.comment+=C;continue;case k.COMMENT_ENDING:C==="-"?(v.state=k.COMMENT_ENDED,v.comment=B(v.opt,v.comment),v.comment&&O(v,"oncomment",v.comment),v.comment=""):(v.comment+="-"+C,v.state=k.COMMENT);continue;case k.COMMENT_ENDED:C!==">"?(Z(v,"Malformed comment"),v.comment+="--"+C,v.state=k.COMMENT):v.state=k.TEXT;continue;case k.CDATA:C==="]"?v.state=k.CDATA_ENDING:v.cdata+=C;continue;case k.CDATA_ENDING:C==="]"?v.state=k.CDATA_ENDING_2:(v.cdata+="]"+C,v.state=k.CDATA);continue;case k.CDATA_ENDING_2:C===">"?(v.cdata&&O(v,"oncdata",v.cdata),O(v,"onclosecdata"),v.cdata="",v.state=k.TEXT):C==="]"?v.cdata+="]":(v.cdata+="]]"+C,v.state=k.CDATA);continue;case k.PROC_INST:C==="?"?v.state=k.PROC_INST_ENDING:w(C)?v.state=k.PROC_INST_BODY:v.procInstName+=C;continue;case k.PROC_INST_BODY:if(!v.procInstBody&&w(C))continue;C==="?"?v.state=k.PROC_INST_ENDING:v.procInstBody+=C;continue;case k.PROC_INST_ENDING:C===">"?(O(v,"onprocessinginstruction",{name:v.procInstName,body:v.procInstBody}),v.procInstName=v.procInstBody="",v.state=k.TEXT):(v.procInstBody+="?"+C,v.state=k.PROC_INST_BODY);continue;case k.OPEN_TAG:A(y,C)?v.tagName+=C:(ge(v),C===">"?se(v):C==="/"?v.state=k.OPEN_TAG_SLASH:(w(C)||Z(v,"Invalid character in tag name"),v.state=k.ATTRIB));continue;case k.OPEN_TAG_SLASH:C===">"?(se(v,!0),oe(v)):(Z(v,"Forward-slash in opening tag not followed by >"),v.state=k.ATTRIB);continue;case k.ATTRIB:if(w(C))continue;C===">"?se(v):C==="/"?v.state=k.OPEN_TAG_SLASH:A(g,C)?(v.attribName=C,v.attribValue="",v.state=k.ATTRIB_NAME):Z(v,"Invalid attribute name");continue;case k.ATTRIB_NAME:C==="="?v.state=k.ATTRIB_VALUE:C===">"?(Z(v,"Attribute without value"),v.attribValue=v.attribName,K(v),se(v)):w(C)?v.state=k.ATTRIB_NAME_SAW_WHITE:A(y,C)?v.attribName+=C:Z(v,"Invalid attribute name");continue;case k.ATTRIB_NAME_SAW_WHITE:if(C==="=")v.state=k.ATTRIB_VALUE;else{if(w(C))continue;Z(v,"Attribute without value"),v.tag.attributes[v.attribName]="",v.attribValue="",O(v,"onattribute",{name:v.attribName,value:""}),v.attribName="",C===">"?se(v):A(g,C)?(v.attribName=C,v.state=k.ATTRIB_NAME):(Z(v,"Invalid attribute name"),v.state=k.ATTRIB)}continue;case k.ATTRIB_VALUE:if(w(C))continue;S(C)?(v.q=C,v.state=k.ATTRIB_VALUE_QUOTED):(Z(v,"Unquoted attribute value"),v.state=k.ATTRIB_VALUE_UNQUOTED,v.attribValue=C);continue;case k.ATTRIB_VALUE_QUOTED:if(C!==v.q){C==="&"?v.state=k.ATTRIB_VALUE_ENTITY_Q:v.attribValue+=C;continue}K(v),v.q="",v.state=k.ATTRIB_VALUE_CLOSED;continue;case k.ATTRIB_VALUE_CLOSED:w(C)?v.state=k.ATTRIB:C===">"?se(v):C==="/"?v.state=k.OPEN_TAG_SLASH:A(g,C)?(Z(v,"No whitespace between attributes"),v.attribName=C,v.attribValue="",v.state=k.ATTRIB_NAME):Z(v,"Invalid attribute name");continue;case k.ATTRIB_VALUE_UNQUOTED:if(!T(C)){C==="&"?v.state=k.ATTRIB_VALUE_ENTITY_U:v.attribValue+=C;continue}K(v),C===">"?se(v):v.state=k.ATTRIB;continue;case k.CLOSE_TAG:if(v.tagName)C===">"?oe(v):A(y,C)?v.tagName+=C:v.script?(v.script+="</"+v.tagName,v.tagName="",v.state=k.SCRIPT):(w(C)||Z(v,"Invalid tagname in closing tag"),v.state=k.CLOSE_TAG_SAW_WHITE);else{if(w(C))continue;I(g,C)?v.script?(v.script+="</"+C,v.state=k.SCRIPT):Z(v,"Invalid tagname in closing tag."):v.tagName=C}continue;case k.CLOSE_TAG_SAW_WHITE:if(w(C))continue;C===">"?oe(v):Z(v,"Invalid characters in closing tag");continue;case k.TEXT_ENTITY:case k.ATTRIB_VALUE_ENTITY_Q:case k.ATTRIB_VALUE_ENTITY_U:var dt,Qe;switch(v.state){case k.TEXT_ENTITY:dt=k.TEXT,Qe="textNode";break;case k.ATTRIB_VALUE_ENTITY_Q:dt=k.ATTRIB_VALUE_QUOTED,Qe="attribValue";break;case k.ATTRIB_VALUE_ENTITY_U:dt=k.ATTRIB_VALUE_UNQUOTED,Qe="attribValue";break}if(C===";")if(v.opt.unparsedEntities){var yt=X(v);v.entity="",v.state=dt,v.write(yt)}else v[Qe]+=X(v),v.entity="",v.state=dt;else A(v.entity.length?_:b,C)?v.entity+=C:(Z(v,"Invalid character in entity name"),v[Qe]+="&"+v.entity+C,v.entity="",v.state=dt);continue;default:throw new Error(v,"Unknown state: "+v.state)}return v.position>=v.bufferCheckPosition&&r(v),v}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||function(){var E=String.fromCharCode,v=Math.floor,j=function(){var C=16384,_e=[],xe,dt,Qe=-1,yt=arguments.length;if(!yt)return"";for(var Ot="";++Qe<yt;){var Ue=Number(arguments[Qe]);if(!isFinite(Ue)||Ue<0||Ue>1114111||v(Ue)!==Ue)throw RangeError("Invalid code point: "+Ue);Ue<=65535?_e.push(Ue):(Ue-=65536,xe=(Ue>>10)+55296,dt=Ue%1024+56320,_e.push(xe,dt)),(Qe+1===yt||_e.length>C)&&(Ot+=E.apply(null,_e),_e.length=0)}return Ot};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:j,configurable:!0,writable:!0}):String.fromCodePoint=j}(),n},z6=U6(),l_=`The output should be formatted as a XML file.
|
|
217
|
+
1. Output should conform to the tags below.
|
|
218
|
+
2. If tags are not given, make them on your own.
|
|
219
|
+
3. Remember to always open and close all the tags.
|
|
220
|
+
|
|
221
|
+
As an example, for the tags ["foo", "bar", "baz"]:
|
|
222
|
+
1. String "<foo>
|
|
223
|
+
<bar>
|
|
224
|
+
<baz></baz>
|
|
225
|
+
</bar>
|
|
226
|
+
</foo>" is a well-formatted instance of the schema.
|
|
227
|
+
2. String "<foo>
|
|
228
|
+
<bar>
|
|
229
|
+
</foo>" is a badly-formatted instance.
|
|
230
|
+
3. String "<foo>
|
|
231
|
+
<tag>
|
|
232
|
+
</tag>
|
|
233
|
+
</foo>" is a badly-formatted instance.
|
|
234
|
+
|
|
235
|
+
Here are the output tags:
|
|
236
|
+
\`\`\`
|
|
237
|
+
{tags}
|
|
238
|
+
\`\`\``;var F6=class extends Dl{constructor(e){super(e);p(this,"tags");p(this,"lc_namespace",["langchain_core","output_parsers"]);p(this,"lc_serializable",!0);this.tags=e==null?void 0:e.tags}static lc_name(){return"XMLOutputParser"}_diff(e,t){if(t)return e?Zf(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return d_(e[0].text)}async parse(e){return d_(e)}getFormatInstructions(){var e;return this.tags&&this.tags.length>0?l_.replace("{tags}",((e=this.tags)==null?void 0:e.join(", "))??""):l_}};const B6=n=>n.split(`
|
|
239
|
+
`).map(e=>e.replace(/^\s+/,"")).join(`
|
|
240
|
+
`).trim(),Ix=n=>{if(Object.keys(n).length===0)return{};const e={};return n.children.length>0?(e[n.name]=n.children.map(Ix),e):(e[n.name]=n.text??void 0,e)};function d_(n){const e=B6(n),t=z6.parser(!0);let r={};const s=[];t.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)},t.onclosetag=()=>{if(s.length>0){const o=s.pop();s.length===0&&o&&(r=o)}},t.ontext=o=>{if(s.length>0){const c=s[s.length-1];c.text+=o}},t.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 t.write(a).close(),r&&r.name==="?xml"&&(r=r.children[0]),Ix(r)}var H6=he({AsymmetricStructuredOutputParser:()=>D6,BaseCumulativeTransformOutputParser:()=>Dl,BaseLLMOutputParser:()=>Ac,BaseOutputParser:()=>Tc,BaseTransformOutputParser:()=>Ll,BytesOutputParser:()=>R6,CommaSeparatedListOutputParser:()=>P6,CustomListOutputParser:()=>N6,JsonMarkdownStructuredOutputParser:()=>kx,JsonOutputParser:()=>bw,ListOutputParser:()=>Ul,MarkdownListOutputParser:()=>j6,NumberedListOutputParser:()=>M6,OutputParserException:()=>Tn,StandardSchemaOutputParser:()=>Ex,StringOutputParser:()=>L6,StructuredOutputParser:()=>vw,XMLOutputParser:()=>F6,XML_FORMAT_INSTRUCTIONS:()=>l_,parseJsonMarkdown:()=>Rh,parsePartialJson:()=>Wo,parseXMLMarkdown:()=>d_}),V6=he({extendInteropZodObject:()=>TI,getInteropZodDefaultGetter:()=>Wz,getInteropZodObjectShape:()=>nc,getSchemaDescription:()=>tc,interopParse:()=>so,interopParseAsync:()=>np,interopSafeParse:()=>Zz,interopSafeParseAsync:()=>tp,interopZodObjectMakeFieldsOptional:()=>Jz,interopZodObjectPartial:()=>xu,interopZodObjectPassthrough:()=>Fg,interopZodObjectStrict:()=>Gh,interopZodTransformInputSchema:()=>EI,isInteropZodError:()=>kI,isInteropZodLiteral:()=>Vz,isInteropZodObject:()=>ir,isInteropZodSchema:()=>Xt,isShapelessZodSchema:()=>Kz,isSimpleStringZodSchema:()=>Xy,isZodArrayV4:()=>sp,isZodLiteralV3:()=>bI,isZodLiteralV4:()=>vI,isZodNullableV4:()=>AI,isZodObjectV3:()=>rp,isZodObjectV4:()=>ws,isZodOptionalV4:()=>SI,isZodSchema:()=>Hz,isZodSchemaV3:()=>Ht,isZodSchemaV4:()=>It});function dp(n,e){if(n.function===void 0)return;let t;if(e!=null&&e.partial)try{t=Wo(n.function.arguments??"{}")}catch{return}else try{t=JSON.parse(n.function.arguments)}catch(s){throw new Tn([`Function "${n.function.name}" arguments:`,"",n.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
|
|
241
|
+
`))}const r={name:n.function.name,args:t,type:"tool_call"};return e!=null&&e.returnId&&(r.id=n.id),r}function Sw(n){if(n.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.args)}}}function Nu(n,e){var t,r;return{name:(t=n.function)==null?void 0:t.name,args:(r=n.function)==null?void 0:r.arguments,id:n.id,error:e,type:"invalid_tool_call"}}var xx=class extends Dl{constructor(e){super(e);p(this,"returnId",!1);p(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);p(this,"lc_serializable",!0);this.returnId=(e==null?void 0:e.returnId)??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){var a;const r=e[0].message;let s;if(xr(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=>dp(o,{returnId:this.returnId,partial:t}))),!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}},Ox=class extends xx{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);p(this,"lc_serializable",!0);p(this,"returnId",!1);p(this,"keyName");p(this,"returnSingle",!1);p(this,"zodSchema");p(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){var r;if(this.serializableSchema!==void 0){const s=await this.serializableSchema["~standard"].validate(e);if(s.issues)throw new Tn(`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 t=await tp(this.zodSchema,e);if(t.success)return t.data;throw new Tn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify((r=t.error)==null?void 0:r.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const t=(await super.parsePartialResult(e)).filter(s=>s.type===this.keyName);let r=t;if(t.length)return this.returnId||(r=t.map(s=>s.args)),this.returnSingle?r[0]:r}async parseResult(e){const t=(await super.parsePartialResult(e,!1)).filter(s=>s.type===this.keyName);let r=t;if(t.length)return this.returnId||(r=t.map(s=>s.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(s=>this._validateResult(s)))}},Z6=he({assembleStructuredOutputPipeline:()=>Ec,createContentParser:()=>uc,createFunctionCallingParser:()=>zl});function uc(n){return Xt(n)?vw.fromZodSchema(n):Or(n)?Ex.fromSerializableSchema(n):new bw}function zl(n,e,t){const r=t??Ox;return Xt(n)?new r({returnSingle:!0,keyName:e,zodSchema:n}):Or(n)?new r({returnSingle:!0,keyName:e,serializableSchema:n}):new r({returnSingle:!0,keyName:e})}function Ec(n,e,t,r){if(!t){const c=n.pipe(e);return r?c.withConfig({runName:r}):c}const s=Yu.assign({parsed:(c,u)=>e.invoke(c.raw,u)}),i=Yu.assign({parsed:()=>null}),a=s.withFallbacks({fallbacks:[i]}),o=pr.from([{raw:n},a]);return r?o.withConfig({runName:r}):o}var K6=he({ChatModelStream:()=>rf,ReasoningContentStream:()=>Rx,TextContentStream:()=>Cx,ToolCallsStream:()=>$x,UsageMetadataStream:()=>Px}),W6=class{constructor(){p(this,"events",[]);p(this,"finished",!1);p(this,"waiters",[]);p(this,"error",null)}push(n){this.events.push(n);const e=this.waiters.splice(0);for(const t of e)t()}finish(){this.finished=!0;const n=this.waiters.splice(0);for(const e of n)e()}setError(n){this.error=n,this.finished=!0;const e=this.waiters.splice(0);for(const t of e)t()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let n=0;for(;;){for(;n<this.events.length;)yield this.events[n],n++;if(this.finished){if(this.error)throw this.error;return}await new Promise(e=>{if(n<this.events.length||this.finished){e();return}this.waiters.push(e)})}}};function q6(n,e){switch(e.type){case"text-delta":return n.type==="text"?{...n,text:(n.text??"")+e.text}:n;case"reasoning-delta":return n.type==="thinking"?{...n,thinking:(n.thinking??"")+e.reasoning}:n.type==="reasoning"?{...n,reasoning:(n.reasoning??"")+e.reasoning}:n;case"data-delta":return{...n,data:(n.data??"")+e.data};case"block-delta":return{...n,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function el(n){if(n.event!=="content-block-delta")return;if("delta"in n&&n.delta)return n.delta;const e=n.content;if(e==null||typeof e!="object")return;const t=e;if(t.type==="text"&&typeof t.text=="string")return{type:"text-delta",text:t.text};if(t.type==="reasoning"&&typeof t.reasoning=="string")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,type:t.type}}}function rS(n){if(n==null||typeof n!="object")return;const e=n;if(e.type==="reasoning"&&typeof e.reasoning=="string")return e.reasoning;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking}function gd(n){if(n==null||typeof n!="object")return!1;const e=n.type;return e==="reasoning"||e==="thinking"}function Co(n){if(n)return{...n,input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:n.total_tokens??0}}function G6(n){if(n!=null&&typeof n=="object"&&!Array.isArray(n))return n;if(typeof n!="string"||n.length===0)return{};try{const e=JSON.parse(n);return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function J6(n){const e=n;if(n.type==="tool_call"||n.type!=="tool_call_chunk"&&n.type!=="tool_use"&&n.type!=="input_json_delta")return n;const t=typeof e.name=="string"?e.name:void 0;if(t==null)return n;const r=e.args??e.input;return{...e,type:"tool_call",name:t,args:G6(r)}}var Cx=class{constructor(n){p(this,"_buffer");this._buffer=n}get full(){const n=this._buffer;return{async*[Symbol.asyncIterator](){let e="";for await(const t of n.iterate()){const r=el(t);(r==null?void 0:r.type)==="text-delta"&&(e+=r.text,yield e)}}}}[Symbol.asyncIterator](){const n=this._buffer;async function*e(){for await(const t of n.iterate()){const r=el(t);(r==null?void 0:r.type)==="text-delta"&&(yield r.text)}}return e()}then(n,e){return(async()=>{let t="";for await(const r of this)t+=r;return t})().then(n,e)}},$x=class{constructor(n){p(this,"_buffer");this._buffer=n}get full(){const n=this._buffer;return{async*[Symbol.asyncIterator](){const e=[];for await(const t of n.iterate())t.event==="content-block-finish"&&t.content.type==="tool_call"&&(e.push(t.content),yield[...e])}}}[Symbol.asyncIterator](){const n=this._buffer;async function*e(){for await(const t of n.iterate())t.event==="content-block-finish"&&t.content.type==="tool_call"&&(yield t.content)}return e()}then(n,e){return(async()=>{const t=[];for await(const r of this)t.push(r);return t})().then(n,e)}},Rx=class{constructor(n){p(this,"_buffer");this._buffer=n}get full(){const n=this._buffer;return{async*[Symbol.asyncIterator](){let e="",t=!1;for await(const r of n.iterate())if(r.event==="content-block-start"){if(!gd(r.content)){if(t)return;continue}t=!0;const s=rS(r.content);if(s==null||s.length===0)continue;e+=s,yield e}else if(r.event==="content-block-delta"){const s=el(r);if((s==null?void 0:s.type)!=="reasoning-delta")continue;t=!0;const i=s.reasoning;if(i==null||i.length===0)continue;e+=i,yield e}else{if(r.event==="content-block-finish"&&gd(r.content))return;if(r.event==="message-finish")return}}}}[Symbol.asyncIterator](){const n=this._buffer;async function*e(){let t=!1;for await(const r of n.iterate())if(r.event==="content-block-start"){if(!gd(r.content)){if(t)return;continue}t=!0;const s=rS(r.content);s!=null&&s.length>0&&(yield s)}else if(r.event==="content-block-delta"){const s=el(r);if((s==null?void 0:s.type)!=="reasoning-delta")continue;t=!0;const i=s.reasoning;i!=null&&i.length>0&&(yield i)}else{if(r.event==="content-block-finish"&&gd(r.content))return;if(r.event==="message-finish")return}}return e()}then(n,e){return(async()=>{let t="";for await(const r of this)t+=r;return t})().then(n,e)}},Px=class{constructor(n){p(this,"_buffer");this._buffer=n}[Symbol.asyncIterator](){const n=this._buffer;async function*e(){for await(const t of n.iterate())if(t.event==="usage"){const r=Co(t.usage);r&&(yield r)}else if(t.event==="message-start"&&t.usage){const r=Co(t.usage);r&&(yield r)}else if(t.event==="message-finish"&&t.usage){const r=Co(t.usage);r&&(yield r)}}return e()}then(n,e){return(async()=>{let t;for await(const r of this)t=r;return t})().then(n,e)}},rf=class{constructor(n){p(this,"_buffer");this._buffer=new W6,this._consume(n)}async _consume(n){try{for await(const e of n)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 Cx(this._buffer)}get toolCalls(){return new $x(this._buffer)}get reasoning(){return new Rx(this._buffer)}get usage(){return new Px(this._buffer)}get output(){return this._assembleMessage()}then(n,e){return this._assembleMessage().then(n,e)}async _assembleMessage(){const n=[];let e,t,r={},s;for await(const a of this._buffer.iterate())switch(a.event){case"message-start":e=a.id??e,a.usage&&(t=Co(a.usage));break;case"content-block-start":n[a.index]=a.content;break;case"content-block-delta":{const o=n[a.index],c=el(a);o&&c&&(n[a.index]=q6(o,c));break}case"content-block-finish":n[a.index]=a.content;break;case"usage":t=Co(a.usage);break;case"message-finish":s=a.reason,a.usage&&(t=Co(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break}const i=n.filter(a=>a!=null).map(J6);return new Ve({id:e,content:i,usage_metadata:t,response_metadata:{...r,...s?{finish_reason:s}:{},output_version:"v1"}})}},Y6=he({convertChunksToEvents:()=>Mx,finalizeContentBlock:()=>jx});const X6={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},Q6={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"};function sS(n){let e=0;for(const t of n.keys())t>=e&&(e=t+1);return e}function Nx(n){const e=n.additional_kwargs;return e!=null&&typeof e=="object"?e:{}}function e5(n){const e=Nx(n).tool_outputs;if(!Array.isArray(e))return[];const t=[];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?Q6[o]:void 0)??"image/png";t.push({type:"image",...typeof s.id=="string"?{id:s.id}:{},...a!=null?{url:a}:{},...i!=null?{data:i}:{},mimeType:c})}return t}function t5(n){const e=Nx(n).audio;if(e==null||typeof e!="object")return;const t=e,r=typeof t.data=="string"?t.data:void 0,s=typeof t.url=="string"?t.url:void 0,i=typeof t.transcript=="string"?t.transcript:void 0;if(r==null&&s==null&&i==null)return;const a=typeof t.mime_type=="string"?t.mime_type:typeof t.mimeType=="string"?t.mimeType:void 0,o=typeof t.format=="string"?t.format.toLowerCase():void 0,c=a??(o!=null?X6[o]:void 0)??(r!=null?"audio/wav":"audio/pcm");return{...typeof t.id=="string"?{id:t.id}:{},...r!=null?{data:r}:{},...s!=null?{url:s}:{},...i!=null?{transcript:i}:{},mimeType:c}}async function*Mx(n,e){var o;const t=new Map;let r=!1,s,i;const a=new Set;for await(const c of n){(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};nt.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(!t.has(0)){const g={type:"text",text:""};t.set(0,{type:"text",accumulated:g}),yield{event:"content-block-start",index:0,content:g}}const m=t.get(0);m.accumulated={...m.accumulated,text:(m.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 m=typeof h.index=="number"?h.index:t.size;if(!t.has(m))t.set(m,{type:h.type,accumulated:{...h}}),yield{event:"content-block-start",index:m,content:{...h}};else{const g=t.get(m),y=r5(h);g.accumulated=n5(g.accumulated,y),yield{event:"content-block-delta",index:m,delta:y}}}if(nt.isInstance(u)&&u.tool_call_chunks&&u.tool_call_chunks.length>0)for(const h of u.tool_call_chunks){const m=typeof h.index=="number"?h.index:t.size;if(!t.has(m)){const y={type:"tool_call_chunk",id:h.id,name:h.name,args:"",index:m};t.set(m,{type:"tool_call_chunk",accumulated:y}),yield{event:"content-block-start",index:m,content:y}}const g=t.get(m).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:m,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=t5(u);if(f!=null){if(i==null){const m=sS(t);i={index:m,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};t.set(m,{type:"audio",accumulated:g}),yield{event:"content-block-start",index:m,content:g}}const h=t.get(i.index);if(h!=null){const m=h.accumulated;f.id!=null&&i.id==null&&(i.id=f.id,m.id=f.id),f.transcript!=null&&(i.transcript+=f.transcript,m.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&&(m.data=(m.data??"")+f.data,yield{event:"content-block-delta",index:i.index,delta:{type:"data-delta",data:f.data,encoding:"base64"}})}}for(const h of e5(u)){const m=h,g=m.id??m.url??(m.data!=null?`${m.data.length}:${m.data.slice(0,32)}`:void 0);if(g!=null&&a.has(g))continue;g!=null&&a.add(g);const y=sS(t);t.set(y,{type:"image",accumulated:h}),yield{event:"content-block-start",index:y,content:h}}if(!l&&nt.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 t)yield{event:"content-block-finish",index:c,content:jx(u.accumulated)};yield{event:"message-finish",reason:"stop",...s?{usage:s}:{}}}function n5(n,e){switch(e.type){case"text-delta":return n.type==="text"?{...n,text:(n.text??"")+e.text}:n;case"reasoning-delta":return n.type==="thinking"?{...n,thinking:(n.thinking??"")+e.reasoning}:n.type==="reasoning"?{...n,reasoning:(n.reasoning??"")+e.reasoning}:n;case"data-delta":return{...n,data:(n.data??"")+e.data};case"block-delta":return{...n,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function r5(n){if(n.type==="text")return{type:"text-delta",text:n.text};if(n.type==="reasoning")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}};throw new Error(`Unsupported content block delta: ${JSON.stringify(n)}`)}function jx(n){if(n.type==="tool_call_chunk"){const e=n;let t;try{t=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:t}}return n}const s5=n=>n();function _d(n){const e=n.constructor;return new e({...n,content:n.contentBlocks,response_metadata:{...n.response_metadata,output_version:"v1"}})}var i5=he({BaseChatModel:()=>Is,SimpleChatModel:()=>a5});function vm(n){const e=[];for(const t of n){let r=t;if(Array.isArray(t.content))for(let s=0;s<t.content.length;s++){const i=t.content[s];(by(i)||vy(i))&&r===t&&(r=new t.constructor({...r,content:[...t.content.slice(0,s),iE(i),...t.content.slice(s+1)]}))}e.push(r)}return e}var Is=class is extends ww{constructor(t){super(t);p(this,"lc_namespace",["langchain","chat_models",this._llmType()]);p(this,"disableStreaming",!1);p(this,"outputVersion");this.outputVersion=s5(()=>{const r=t.outputVersion??Bt("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(t){const[r,s]=super._separateRunnableConfigFromCallOptions(t);return s.signal=r.signal,[r,s]}async invoke(t,r){const s=is._convertInputToPromptValue(t);return(await this.generatePrompt([s],r,r==null?void 0:r.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,r,s){throw new Error("Not implemented.")}async*_streamChatModelEvents(t,r,s){yield*Mx(this._streamResponseChunks(t,r,s),{signal:r.signal})}streamV2(t,r){const s=is._convertInputToPromptValue(t).toChatMessages(),[,i]=this._separateRunnableConfigFromCallOptionsCompat(r);return new rf(this._streamChatModelEvents(s,i))}async*_streamIterator(t,r){var s,i,a;if(this._streamResponseChunks===is.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,r);else{const o=is._convertInputToPromptValue(t).toChatMessages(),[c,u]=this._separateRunnableConfigFromCallOptionsCompat(r),l={...c.metadata,...this.getLsParamsWithDefaults(u)},d=this.invocationParams(u),f=await An.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(d)}),h={options:u,invocation_params:d,batch_size:1},m=u.outputVersion??this.outputVersion,g=await(f==null?void 0:f.handleChatModelStart(this.toJSON(),[vm(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},m==="v1"?yield _d(_.message):yield _.message,y?y=y.concat(_):y=_,Ph(_.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(t){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:r}}getLsParamsWithDefaults(t){return{...this.getLsParams(t),ls_integration:"langchain_chat_model"}}async _generateUncached(t,r,s,i){var m,g,y,b,_,w;const a=t.map(S=>S.map(ys));let o;if(i!==void 0&&i.length===a.length)o=i;else{const S={...s.metadata,...this.getLsParamsWithDefaults(r)},T=this.invocationParams(r),A=await An.configure(s.callbacks,this.callbacks,s.tags,this.tags,S,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(T)}),I={options:r,invocation_params:T,batch_size:1};o=await(A==null?void 0:A.handleChatModelStart(this.toJSON(),a.map(vm),s.runId,void 0,I,void 0,void 0,s.runName))}const c=r.outputVersion??this.outputVersion,u=[],l=[],d=!!(o!=null&&o[0].handlers.find(xE)),f=!!(o!=null&&o[0].handlers.find(Ry));if(d&&!this.disableStreaming&&a.length===1&&(this._streamChatModelEvents!==is.prototype._streamChatModelEvents||this._streamResponseChunks!==is.prototype._streamResponseChunks))try{let S=!1;const T=o==null?void 0:o[0],A=this._streamChatModelEvents(a[0],r),I=await new rf({async*[Symbol.asyncIterator](){var x;for await(const O of A){(x=r.signal)==null||x.throwIfAborted(),S=!0;const U=O.event==="message-start"&&O.id==null&&(T==null?void 0:T.runId)!=null?{...O,id:`run-${T.runId}`}:O;await(T==null?void 0:T.handleChatModelStreamEvent(U)),yield U}}});if((m=r.signal)==null||m.throwIfAborted(),!S)throw new Error("Received empty response from chat model call.");if(I.id==null){const x=(g=o==null?void 0:o.at(0))==null?void 0:g.runId;x!=null&&I._updateId(`run-${x}`)}const k={text:I.text,message:I};u.push([k]);const R=I.usage_metadata!==void 0?{tokenUsage:{promptTokens:I.usage_metadata.input_tokens,completionTokens:I.usage_metadata.output_tokens,totalTokens:I.usage_metadata.total_tokens}}:void 0;await(o==null?void 0:o[0].handleLLMEnd({generations:u,llmOutput:R}))}catch(S){throw await(o==null?void 0:o[0].handleLLMError(S)),S}else if(f&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==is.prototype._streamResponseChunks)try{const S=await this._streamResponseChunks(a[0],r,o==null?void 0:o[0]);let T,A;for await(const I of S){if((y=r.signal)!=null&&y.aborted){const k=T==null?void 0:T.message;throw new gg("Model invocation was aborted.",k)}if(I.message.id==null){const k=(b=o==null?void 0:o.at(0))==null?void 0:b.runId;k!=null&&I.message._updateId(`run-${k}`)}T===void 0?T=I:T=Ws(T,I),Ph(I.message)&&I.message.usage_metadata!==void 0&&(A={tokenUsage:{promptTokens:I.message.usage_metadata.input_tokens,completionTokens:I.message.usage_metadata.output_tokens,totalTokens:I.message.usage_metadata.total_tokens}})}if((_=r.signal)!=null&&_.aborted){const I=T==null?void 0:T.message;throw new gg("Model invocation was aborted.",I)}if(T===void 0)throw new Error("Received empty response from chat model call.");c==="v1"&&(T.message=_d(T.message)),u.push([T]),await(o==null?void 0:o[0].handleLLMEnd({generations:u,llmOutput:A}))}catch(S){throw await(o==null?void 0:o[0].handleLLMError(S)),S}else{const S=await Promise.allSettled(a.map(async(T,A)=>{const I=await this._generate(T,{...r,promptIndex:A},o==null?void 0:o[A]);if(c==="v1")for(const k of I.generations)k.message=_d(k.message);return I}));await Promise.all(S.map(async(T,A)=>{var I,k,R;if(T.status==="fulfilled"){const x=T.value;for(const O of x.generations){if(O.message.id==null){const U=(I=o==null?void 0:o.at(0))==null?void 0:I.runId;U!=null&&O.message._updateId(`run-${U}`)}O.message.response_metadata={...O.generationInfo,...O.message.response_metadata}}return x.generations.length===1&&(x.generations[0].message.response_metadata={...x.llmOutput,...x.generations[0].message.response_metadata}),u[A]=x.generations,l[A]=x.llmOutput,(k=o==null?void 0:o[A])==null?void 0:k.handleLLMEnd({generations:[x.generations],llmOutput:x.llmOutput})}else return await((R=o==null?void 0:o[A])==null?void 0:R.handleLLMError(T.reason)),Promise.reject(T.reason)}))}const h={generations:u,llmOutput:l.length?(w=this._combineLLMOutput)==null?void 0:w.call(this,...l):void 0};return Object.defineProperty(h,Ku,{value:o?{runIds:o==null?void 0:o.map(S=>S.runId)}:void 0,configurable:!0}),h}async _generateCached({messages:t,cache:r,llmStringKey:s,parsedOptions:i,handledOptions:a}){const o=t.map(_=>_.map(ys)),c={...a.metadata,...this.getLsParamsWithDefaults(i)},u=this.invocationParams(i),l=await An.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(vm),a.runId,void 0,d,void 0,void 0,a.runName)),h=[],m=(await Promise.allSettled(o.map(async(_,w)=>{const S=is._convertInputToPromptValue(_).toString(),T=await r.lookup(S,s);return T==null&&h.push(w),T}))).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(m.map(async({result:_,runManager:w},S)=>{if(_.status==="fulfilled"){const T=_.value;return y[S]=T.map(A=>("message"in A&&Rt(A.message)&&xr(A.message)&&(A.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},g==="v1"&&(A.message=_d(A.message))),A.generationInfo={...A.generationInfo,tokenUsage:{}},A)),T.length&&await(w==null?void 0:w.handleLLMNewToken(T[0].text)),w==null?void 0:w.handleLLMEnd({generations:[T]},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,Ku,{value:f?{runIds:f==null?void 0:f.map(_=>_.runId)}:void 0,configurable:!0}),b}async generate(t,r,s){let i;Array.isArray(r)?i={stop:r}:i=r;const a=t.map(g=>g.map(ys)),[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 m={};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=is._convertInputToPromptValue(a[_]).toString();return u.update(w,l,y)})),m=g.llmOutput??{}}return{generations:d,llmOutput:m}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,r,s){const i=t.map(a=>a.toChatMessages());return this.generate(i,r,s)}withStructuredOutput(t,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=t,i=r==null?void 0:r.name,a=tc(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";!Xt(s)&&!Or(s)&&"name"in s&&(u=s.name);const l=Xt(s)||Or(s)?At(s):s,d=[{type:"function",function:{name:u,description:a,parameters:l}}];return Ec(this.bindTools(d),an.from(f=>{if(!nt.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const h=f.tool_calls.find(m=>m.name===u);if(!h)throw new Error(`No tool call found with name ${u}.`);return h.args}),c,c?"StructuredOutputRunnable":"StructuredOutput")}},a5=class extends Is{async _generate(n,e,t){const r=new Ve(await this._call(n,e,t));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}]}}},o5=he({}),c5=he({BaseLLM:()=>Lx,LLM:()=>Aw}),Lx=class ou extends ww{constructor(){super(...arguments);p(this,"lc_namespace",["langchain","llms",this._llmType()])}async invoke(t,r){const s=ou._convertInputToPromptValue(t);return(await this.generatePrompt([s],r,r==null?void 0:r.callbacks)).generations[0][0].text}async*_streamResponseChunks(t,r,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(t){const[r,s]=super._separateRunnableConfigFromCallOptions(t);return s.signal=r.signal,[r,s]}async*_streamIterator(t,r){if(this._streamResponseChunks===ou.prototype._streamResponseChunks)yield this.invoke(t,r);else{const s=ou._convertInputToPromptValue(t),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(r),o=this.invocationParams(a),c=await An.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 Xo({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(t,r,s){const i=t.map(a=>a.toString());return this.generate(i,r,s)}invocationParams(t){return{}}_flattenLLMResult(t){const r=[];for(let s=0;s<t.generations.length;s+=1){const i=t.generations[s];if(s===0)r.push({generations:[i],llmOutput:t.llmOutput});else{const a=t.llmOutput?{...t.llmOutput,tokenUsage:{}}:void 0;r.push({generations:[i],llmOutput:a})}}return r}async _generateUncached(t,r,s,i){let a;if(i!==void 0&&i.length===t.length)a=i;else{const l=this.invocationParams(r),d=await An.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:t.length};a=await(d==null?void 0:d.handleLLMStart(this.toJSON(),t,s.runId,void 0,f,void 0,void 0,s==null?void 0:s.runName))}const o=!!(a!=null&&a[0].handlers.find(Ry));let c;if(o&&t.length===1&&this._streamResponseChunks!==ou.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(t[0],r,a==null?void 0:a[0]);let d;for await(const f of l)d===void 0?d=f:d=Ws(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(t,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,Ku,{value:u?{runIds:u}:void 0,configurable:!0}),c}async _generateCached({prompts:t,cache:r,llmStringKey:s,parsedOptions:i,handledOptions:a,runId:o}){const c=this.invocationParams(i),u=await An.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:t.length},d=await(u==null?void 0:u.handleLLMStart(this.toJSON(),t,o,void 0,l,void 0,void 0,a==null?void 0:a.runName)),f=[],h=(await Promise.allSettled(t.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"),m=[];await Promise.all(h.map(async({result:y,runManager:b},_)=>{if(y.status==="fulfilled"){const w=y.value;return m[_]=w.map(S=>(S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),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:m,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(g,Ku,{value:d?{runIds:d==null?void 0:d.map(y=>y.runId)}:void 0,configurable:!0}),g}async generate(t,r,s){if(!Array.isArray(t))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(t,o,a);const{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({prompts:t,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:a,runId:a.runId});let h={};if(d.length>0){const m=await this._generateUncached(d.map(g=>t[g]),o,a,f!==void 0?d.map(g=>f==null?void 0:f[g]):void 0);await Promise.all(m.generations.map(async(g,y)=>{const b=d[y];return l[b]=g,c.update(t[b],u,g)})),h=m.llmOutput??{}}return{generations:l,llmOutput:h}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Aw=class extends Lx{async _generate(n,e,t){return{generations:await Promise.all(n.map((r,s)=>this._call(r,{...e,promptIndex:s},t).then(i=>[{text:i}])))}}},u5=he({}),l5=he({BaseMemory:()=>d5,getInputValue:()=>h5,getOutputValue:()=>f5,getPromptInputKey:()=>p5}),d5=class{};const Dx=(n,e)=>{if(e!==void 0)return n[e];const t=Object.keys(n);if(t.length===1)return n[t[0]]},h5=(n,e)=>{const t=Dx(n,e);if(!t)throw new Error(`input values have ${Object.keys(n).length} keys, you must specify an input key or pass only 1 key as input`);return t},f5=(n,e)=>{const t=Dx(n,e);if(!t&&t!=="")throw new Error(`output values have ${Object.keys(n).length} keys, you must specify an output key or pass only 1 key as output`);return t};function p5(n,e){const t=Object.keys(n).filter(r=>!e.includes(r)&&r!=="stop");if(t.length!==1)throw new Error(`One input key expected, but got ${t.length}`);return t[0]}var Ux=class extends Ac{constructor(e){super();p(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);p(this,"lc_serializable",!0);p(this,"argsOnly",!0);this.argsOnly=(e==null?void 0:e.argsOnly)??this.argsOnly}static lc_name(){return"OutputFunctionsParser"}async parseResult(e){if("message"in e[0]){const t=e[0].message.additional_kwargs.function_call;if(!t)throw new Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw new Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw new Error(`No message in generations ${JSON.stringify(e)}`)}},zx=class extends Dl{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);p(this,"lc_serializable",!0);p(this,"outputParser");p(this,"argsOnly",!0);this.argsOnly=(e==null?void 0:e.argsOnly)??this.argsOnly,this.outputParser=new Ux(e)}static lc_name(){return"JsonOutputFunctionsParser"}_diff(e,t){if(t)return Zf(e??{},t)}async parsePartialResult(e){const t=e[0];if(!t.message)return;const{message:r}=t,s=r.additional_kwargs.function_call;if(s)return this.argsOnly?Wo(s.arguments):{...s,arguments:Wo(s.arguments)}}async parseResult(e){const t=await this.outputParser.parseResult(e);if(!t)throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){const t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return""}},m5=class extends Ac{constructor(e){super(e);p(this,"lc_namespace",["langchain","output_parsers","openai_functions"]);p(this,"lc_serializable",!0);p(this,"outputParser",new zx);p(this,"attrName");this.attrName=e.attrName}static lc_name(){return"JsonKeyOutputFunctionsParser"}get lc_aliases(){return{attrName:"key_name"}}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},g5=he({JsonKeyOutputFunctionsParser:()=>m5,JsonOutputFunctionsParser:()=>zx,OutputFunctionsParser:()=>Ux}),_5=he({JsonOutputKeyToolsParser:()=>Ox,JsonOutputToolsParser:()=>xx,convertLangChainToolCallToOpenAI:()=>Sw,makeInvalidToolCall:()=>Nu,parseToolCall:()=>dp}),Fl=class extends Ge{constructor(e){super(e);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);p(this,"inputVariables");p(this,"outputParser");p(this,"partialVariables");p(this,"metadata");p(this,"tags");const{inputVariables:t}=e;if(t.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 t=this.partialVariables??{},r={};for(const[s,i]of Object.entries(t))typeof i=="string"?r[s]=i:r[s]=await i();return{...r,...e}}async invoke(e,t){const r={...this.metadata,...t==null?void 0:t.metadata},s=[...this.tags??[],...(t==null?void 0:t.tags)??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...t,tags:s,metadata:r,runType:"prompt"})}},tl=class extends Fl{async formatPromptValue(n){return new mw(await this.format(n))}};/*!
|
|
242
|
+
* mustache.js - Logic-less {{mustache}} templates with JavaScript
|
|
243
|
+
* http://github.com/janl/mustache.js
|
|
244
|
+
*/var y5=Object.prototype.toString,kc=Array.isArray||function(e){return y5.call(e)==="[object Array]"};function Tw(n){return typeof n=="function"}function w5(n){return kc(n)?"array":typeof n}function Sm(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function iS(n,e){return n!=null&&typeof n=="object"&&e in n}function b5(n,e){return n!=null&&typeof n!="object"&&n.hasOwnProperty&&n.hasOwnProperty(e)}var v5=RegExp.prototype.test;function S5(n,e){return v5.call(n,e)}var A5=/\S/;function T5(n){return!S5(A5,n)}var E5={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function k5(n){return String(n).replace(/[&<>"'`=\/]/g,function(t){return E5[t]})}var I5=/\s*/,x5=/\s+/,aS=/\s*=/,O5=/\s*\}/,C5=/#|\^|\/|>|\{|&|=|!/;function $5(n,e){if(!n)return[];var t=!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 m(k){if(typeof k=="string"&&(k=k.split(x5,2)),!kc(k)||k.length!==2)throw new Error("Invalid tags: "+k);d=new RegExp(Sm(k[0])+"\\s*"),f=new RegExp("\\s*"+Sm(k[1])),h=new RegExp("\\s*"+Sm("}"+k[1]))}m(e||Jn.tags);for(var g=new Bl(n),y,b,_,w,S,T;!g.eos();){if(y=g.pos,_=g.scanUntil(d),_)for(var A=0,I=_.length;A<I;++A)w=_.charAt(A),T5(w)?(i.push(s.length),c+=w):(o=!0,t=!0,c+=" "),s.push(["text",w,y,y+1]),y+=1,w===`
|
|
245
|
+
`&&(l(),c="",u=0,t=!1);if(!g.scan(d))break;if(a=!0,b=g.scan(C5)||"name",g.scan(I5),b==="="?(_=g.scanUntil(aS),g.scan(aS),g.scanUntil(f)):b==="{"?(_=g.scanUntil(h),g.scan(O5),g.scanUntil(f),b="&"):_=g.scanUntil(f),!g.scan(f))throw new Error("Unclosed tag at "+g.pos);if(b==">"?S=[b,_,y,g.pos,c,u,t]:S=[b,_,y,g.pos],u++,s.push(S),b==="#"||b==="^")r.push(S);else if(b==="/"){if(T=r.pop(),!T)throw new Error('Unopened section "'+_+'" at '+y);if(T[1]!==_)throw new Error('Unclosed section "'+T[1]+'" at '+y)}else b==="name"||b==="{"||b==="&"?o=!0:b==="="&&m(_)}if(l(),T=r.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+g.pos);return P5(R5(s))}function R5(n){for(var e=[],t,r,s=0,i=n.length;s<i;++s)t=n[s],t&&(t[0]==="text"&&r&&r[0]==="text"?(r[1]+=t[1],r[3]=t[3]):(e.push(t),r=t));return e}function P5(n){for(var e=[],t=e,r=[],s,i,a=0,o=n.length;a<o;++a)switch(s=n[a],s[0]){case"#":case"^":t.push(s),r.push(s),t=s[4]=[];break;case"/":i=r.pop(),i[5]=s[2],t=r.length>0?r[r.length-1][4]:e;break;default:t.push(s)}return e}function Bl(n){this.string=n,this.tail=n,this.pos=0}Bl.prototype.eos=function(){return this.tail===""};Bl.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};Bl.prototype.scanUntil=function(e){var t=this.tail.search(e),r;switch(t){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=r.length,r};function lc(n,e){this.view=n,this.cache={".":this.view},this.parent=e}lc.prototype.push=function(e){return new lc(e,this)};lc.prototype.lookup=function(e){var t=this.cache,r;if(t.hasOwnProperty(e))r=t[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=iS(i,a[o])||b5(i,a[o])),i=i[a[o++]];else i=s.view[e],c=iS(s.view,e);if(c){r=i;break}s=s.parent}t[e]=r}return Tw(r)&&(r=r.call(this.view)),r};function Un(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Un.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Un.prototype.parse=function(e,t){var r=this.templateCache,s=e+":"+(t||Jn.tags).join(":"),i=typeof r<"u",a=i?r.get(s):void 0;return a==null&&(a=$5(e,t),i&&r.set(s,a)),a};Un.prototype.render=function(e,t,r,s){var i=this.getConfigTags(s),a=this.parse(e,i),o=t instanceof lc?t:new lc(t,void 0);return this.renderTokens(a,o,r,e,s)};Un.prototype.renderTokens=function(e,t,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,t,r,s,i):c==="^"?u=this.renderInverted(o,t,r,s,i):c===">"?u=this.renderPartial(o,t,r,i):c==="&"?u=this.unescapedValue(o,t):c==="name"?u=this.escapedValue(o,t,i):c==="text"&&(u=this.rawValue(o)),u!==void 0&&(a+=u);return a};Un.prototype.renderSection=function(e,t,r,s,i){var a=this,o="",c=t.lookup(e[1]);function u(f){return a.render(f,t,r,i)}if(c){if(kc(c))for(var l=0,d=c.length;l<d;++l)o+=this.renderTokens(e[4],t.push(c[l]),r,s,i);else if(typeof c=="object"||typeof c=="string"||typeof c=="number")o+=this.renderTokens(e[4],t.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(t.view,s.slice(e[3],e[5]),u),c!=null&&(o+=c)}else o+=this.renderTokens(e[4],t,r,s,i);return o}};Un.prototype.renderInverted=function(e,t,r,s,i){var a=t.lookup(e[1]);if(!a||kc(a)&&a.length===0)return this.renderTokens(e[4],t,r,s,i)};Un.prototype.indentPartial=function(e,t,r){for(var s=t.replace(/[^ \t]/g,""),i=e.split(`
|
|
246
|
+
`),a=0;a<i.length;a++)i[a].length&&(a>0||!r)&&(i[a]=s+i[a]);return i.join(`
|
|
247
|
+
`)};Un.prototype.renderPartial=function(e,t,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,t,r,l,s)}}};Un.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(r!=null)return r};Un.prototype.escapedValue=function(e,t,r){var s=this.getConfigEscape(r)||Jn.escape,i=t.lookup(e[1]);if(i!=null)return typeof i=="number"&&s===Jn.escape?String(i):s(i)};Un.prototype.rawValue=function(e){return e[1]};Un.prototype.getConfigTags=function(e){return kc(e)?e:e&&typeof e=="object"?e.tags:void 0};Un.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!kc(e))return e.escape};var Jn={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(n){nl.templateCache=n},get templateCache(){return nl.templateCache}},nl=new Un;Jn.clearCache=function(){return nl.clearCache()};Jn.parse=function(e,t){return nl.parse(e,t)};Jn.render=function(e,t,r,s){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+w5(e)+'" was given as the first argument for mustache#render(template, view, partials)');return nl.render(e,t,r,s)};Jn.escape=k5;Jn.Scanner=Bl;Jn.Context=lc;Jn.Writer=Un;function Fx(){Jn.escape=n=>n}const rl=n=>{const e=n.split(""),t=[],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]==="{")t.push({type:"literal",text:"{"}),s+=2;else if(e[s]==="}"&&s+1<e.length&&e[s+1]==="}")t.push({type:"literal",text:"}"}),s+=2;else if(e[s]==="{"){const i=r("}",s);if(i<0)throw new Error("Unclosed '{' in template.");t.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("");t.push({type:"literal",text:a}),s=i<0?e.length:i}}return t},Bx=(n,e=[])=>{const t=[];for(const r of n)if(r[0]==="name"){const s=r[1].includes(".")?r[1].split(".")[0]:r[1];t.push({type:"variable",name:s})}else if(["#","&","^",">"].includes(r[0])){if(t.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){const s=[...e,r[1]],i=Bx(r[4],s);t.push(...i)}}else t.push({type:"literal",text:r[1]});return t},sf=n=>(Fx(),Bx(Jn.parse(n))),Hx=(n,e)=>rl(n).reduce((t,r)=>{if(r.type==="variable"){if(r.name in e)return t+(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 t+r.text},""),Vx=(n,e)=>(Fx(),Jn.render(n,e)),af={"f-string":Hx,mustache:Vx},Zx={"f-string":rl,mustache:sf},Wr=(n,e,t)=>{try{return af[e](n,t)}catch(r){throw Il(r,"INVALID_PROMPT_INPUT")}},of=(n,e)=>Zx[e](n),Hl=(n,e,t)=>{if(!(e in af))throw new Error(`Invalid template format. Got \`${e}\`;
|
|
248
|
+
should be one of ${Object.keys(af)}`);try{const r=Object.fromEntries(t.map(s=>[s,"foo"]));Array.isArray(n)?n.forEach(s=>{if(s.type==="text"&&"text"in s&&typeof s.text=="string")Wr(s.text,e,r);else if(s.type==="image_url"){if(typeof s.image_url=="string")Wr(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;Wr(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(s,null,2)}`)}):Wr(n,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}};var Ci=class cu extends tl{constructor(t){super(t);p(this,"template");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);p(this,"additionalContentFields");if(t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),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))),Hl(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(t){const r=await this.mergePartialAndUserVariables(t);return Wr(this.template,this.templateFormat,r)}static fromExamples(t,r,s,i=`
|
|
249
|
+
|
|
250
|
+
`,a=""){return new cu({inputVariables:s,template:[a,...t,r].join(i)})}static fromTemplate(t,r){const{templateFormat:s="f-string",...i}=r??{},a=new Set;return of(t,s).forEach(o=>{o.type==="variable"&&a.add(o.name)}),new cu({inputVariables:[...a],templateFormat:s,template:t,...i})}async partial(t){const r=this.inputVariables.filter(i=>!(i in t)),s={...this.partialVariables??{},...t};return new cu({...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(t){if(!t.template)throw new Error("Prompt template must have a template");return new cu({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}},ih=class Kx extends Fl{constructor(t){super(t);p(this,"lc_namespace",["langchain_core","prompts","image"]);p(this,"template");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);p(this,"additionalContentFields");if(this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),Hl([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(t){const r=this.inputVariables.filter(i=>!(i in t)),s={...this.partialVariables??{},...t};return new Kx({...this,inputVariables:r,partialVariables:s})}async format(t){const r={};for(const[o,c]of Object.entries(this.template))typeof c=="string"?r[o]=Wr(c,this.templateFormat,t):r[o]=c;const s=t.url||r.url,i=t.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(t){return new bx(await this.format(t))}},h_=class extends Ge{constructor(e){const t=e.templateFormat??"f-string",r=f_(e.template,t);super({inputVariables:r,...e});p(this,"lc_namespace",["langchain_core","prompts","dict"]);p(this,"lc_serializable",!0);p(this,"template");p(this,"templateFormat");p(this,"inputVariables");this.template=e.template,this.templateFormat=t,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return p_(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}};function f_(n,e){const t=[];for(const r of Object.values(n))if(typeof r=="string")of(r,e).forEach(s=>{s.type==="variable"&&t.push(s.name)});else if(Array.isArray(r))for(const s of r)typeof s=="string"?of(s,e).forEach(i=>{i.type==="variable"&&t.push(i.name)}):typeof s=="object"&&t.push(...f_(s,e));else typeof r=="object"&&r!==null&&t.push(...f_(r,e));return Array.from(new Set(t))}function p_(n,e,t){const r={};for(const[s,i]of Object.entries(n))if(typeof i=="string")r[s]=Wr(i,t,e);else if(Array.isArray(i)){const a=[];for(const o of i)typeof o=="string"?a.push(Wr(o,t,e)):typeof o=="object"&&a.push(p_(o,e,t));r[s]=a}else typeof i=="object"&&i!==null?r[s]=p_(i,e,t):r[s]=i;return r}var hp=class extends Ge{constructor(){super(...arguments);p(this,"lc_namespace",["langchain_core","prompts","chat"]);p(this,"lc_serializable",!0)}async invoke(e,t){return this._callWithConfig(r=>this.formatMessages(r),e,{...t,runType:"prompt"})}},m_=class extends hp{constructor(e){typeof e=="string"&&(e={variableName:e});super(e);p(this,"variableName");p(this,"optional");this.variableName=e.variableName,this.optional=e.optional??!1}static lc_name(){return"MessagesPlaceholder"}get inputVariables(){return[this.variableName]}async formatMessages(e){const t=e[this.variableName];if(this.optional&&!t)return[];if(!t){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(t)?r=t.map(ys):r=[ys(t)]}catch(s){const i=typeof t=="string"?t:JSON.stringify(t,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(`
|
|
251
|
+
|
|
252
|
+
`));throw a.name="InputFormatError",a.lc_error_code=s.lc_error_code,a}return r}},Wx=class extends hp{constructor(e){"prompt"in e||(e={prompt:e});super(e);p(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Ew=class extends Fl{constructor(n){super(n)}async format(n){return(await this.formatPromptValue(n)).toString()}async formatPromptValue(n){return new gw(await this.formatMessages(n))}},qx=class extends Wx{constructor(e,t){"prompt"in e||(e={prompt:e,role:t});super(e);p(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new ks(await this.prompt.format(e),this.role)}static fromTemplate(e,t,r){return new this(Ci.fromTemplate(e,{templateFormat:r==null?void 0:r.templateFormat}),t)}};function N5(n){return n===null||typeof n!="object"||Array.isArray(n)?!1:Object.keys(n).length===1&&"text"in n&&typeof n.text=="string"}function M5(n){return n===null||typeof n!="object"||Array.isArray(n)?!1:"image_url"in n&&(typeof n.image_url=="string"||typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string")}var kw=class extends hp{constructor(e,t){"prompt"in e||(e={prompt:e});super(e);p(this,"lc_namespace",["langchain_core","prompts","chat"]);p(this,"lc_serializable",!0);p(this,"inputVariables",[]);p(this,"additionalOptions",{});p(this,"prompt");p(this,"messageClass");p(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(s=>{"inputVariables"in s&&(r=r.concat(s.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){const t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){const r=t.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,t){if(typeof e=="string")return new this(Ci.fromTemplate(e,t));const r=[];for(const s of e)if(typeof s=="string")r.push(Ci.fromTemplate(s,t));else if(s!==null)if(N5(s)){let i="";typeof s.text=="string"&&(i=s.text??"");const a={...t,additionalContentFields:s};r.push(Ci.fromTemplate(i,a))}else if(M5(s)){let i=s.image_url??"",a,o=[];if(typeof i=="string"){let c;(t==null?void 0:t.templateFormat)==="mustache"?c=sf(i):c=rl(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.
|
|
253
|
+
Got: ${u}
|
|
254
|
+
From: ${i}`);o=[u[0]]}else o=[];i={url:i},a=new ih({template:i,inputVariables:o,templateFormat:t==null?void 0:t.templateFormat,additionalContentFields:s})}else if(typeof i=="object"){if("url"in i){let c;(t==null?void 0:t.templateFormat)==="mustache"?c=sf(i.url):c=rl(i.url),o=c.flatMap(u=>u.type==="variable"?[u.name]:[])}else o=[];a=new ih({template:i,inputVariables:o,templateFormat:t==null?void 0:t.templateFormat,additionalContentFields:s})}else throw new Error("Invalid image template");r.push(a)}else typeof s=="object"&&r.push(new h_({template:s,templateFormat:t==null?void 0:t.templateFormat}));return new this({prompt:r,additionalOptions:t})}async format(e){if(this.prompt instanceof tl){const t=await this.prompt.format(e);return this.createMessage(t)}else{const t=[];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 tl){const i=await r.format(s);let a;"additionalContentFields"in r&&(a=r.additionalContentFields),i!==""&&t.push({...a,type:"text",text:i})}else if(r instanceof ih){const i=await r.format(s);let a;"additionalContentFields"in r&&(a=r.additionalContentFields),t.push({...a,type:"image_url",image_url:i})}else if(r instanceof h_){const i=await r.format(s);let a;"additionalContentFields"in r&&(a=r.additionalContentFields),t.push({...a,...i})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},Iw=class extends kw{static _messageClass(){return Dn}static lc_name(){return"HumanMessagePromptTemplate"}},Gx=class extends kw{static _messageClass(){return Ve}static lc_name(){return"AIMessagePromptTemplate"}},Jx=class extends kw{static _messageClass(){return hr}static lc_name(){return"SystemMessagePromptTemplate"}};function j5(n){return typeof n.formatMessages=="function"}function L5(n,e){if(j5(n)||Rt(n))return n;if(Array.isArray(n)&&n[0]==="placeholder"){const s=n[1];if((e==null?void 0:e.templateFormat)==="mustache"&&typeof s=="string"&&s.slice(0,2)==="{{"&&s.slice(-2)==="}}")return new m_({variableName:s.slice(2,-2),optional:!0});if(typeof s=="string"&&s[0]==="{"&&s[s.length-1]==="}")return new m_({variableName:s.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${(e==null?void 0:e.templateFormat)??'"f-string"'}: "${n[1]}". Expected a variable name surrounded by ${(e==null?void 0:e.templateFormat)==="mustache"?"double":"single"} curly braces.`)}const t=ys(n);let r;if(typeof t.content=="string"?r=t.content:r=t.content.map(s=>"text"in s?{...s,text:s.text}:"image_url"in s?{...s,image_url:s.image_url}:s),t._getType()==="human")return Iw.fromTemplate(r,e);if(t._getType()==="ai")return Gx.fromTemplate(r,e);if(t._getType()==="system")return Jx.fromTemplate(r,e);if(ks.isInstance(t))return qx.fromTemplate(t.content,t.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${t._getType()}".`)}function D5(n){return n.constructor.lc_name()==="MessagesPlaceholder"}var xw=class ah extends Ew{constructor(t){super(t);p(this,"promptMessages");p(this,"validateTemplate",!0);p(this,"templateFormat","f-string");if(t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){const r=new Set;for(const c of this.promptMessages)if(!(c instanceof Lt))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(t,r){return typeof t.content=="string"||(t.content=await Promise.all(t.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 Ci.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}))),t}async formatMessages(t){const r=await this.mergePartialAndUserVariables(t);let s=[];for(const i of this.promptMessages)if(i instanceof Lt)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)&&!(D5(i)&&i.optional))throw Il(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(t){const r=this.inputVariables.filter(i=>!(i in t)),s={...this.partialVariables??{},...t};return new ah({...this,inputVariables:r,partialVariables:s})}static fromTemplate(t,r){const s=new Iw({prompt:Ci.fromTemplate(t,r)});return this.fromMessages([s])}static fromMessages(t,r){const s=t.reduce((o,c)=>o.concat(c instanceof ah?c.promptMessages:[L5(c,r)]),[]),i=t.reduce((o,c)=>c instanceof ah?Object.assign(o,c.partialVariables):o,Object.create(null)),a=new Set;for(const o of s)if(!(o instanceof Lt))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})}},U5=class g_ extends tl{constructor(t){super(t);p(this,"lc_serializable",!1);p(this,"examples");p(this,"exampleSelector");p(this,"examplePrompt");p(this,"suffix","");p(this,"exampleSeparator",`
|
|
255
|
+
|
|
256
|
+
`);p(this,"prefix","");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);if(Object.assign(this,t),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))),Hl(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){const r=this.inputVariables.filter(i=>!(i in t)),s={...this.partialVariables??{},...t};return new g_({...this,inputVariables:r,partialVariables:s})}async format(t){const r=await this.mergePartialAndUserVariables(t),s=await this.getExamples(r),i=await Promise.all(s.map(a=>this.examplePrompt.format(a)));return Wr([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(t){const{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");const s=await Ci.deserialize(r);let i;if(Array.isArray(t.examples))i=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new g_({inputVariables:t.input_variables,examplePrompt:s,examples:i,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},z5=class Yx extends Ew{constructor(t){super(t);p(this,"lc_serializable",!0);p(this,"examples");p(this,"exampleSelector");p(this,"examplePrompt");p(this,"suffix","");p(this,"exampleSeparator",`
|
|
257
|
+
|
|
258
|
+
`);p(this,"prefix","");p(this,"templateFormat","f-string");p(this,"validateTemplate",!0);if(this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
|
|
259
|
+
|
|
260
|
+
`,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.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))),Hl(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){const r=await this.mergePartialAndUserVariables(t);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(t){const r=await this.mergePartialAndUserVariables(t),s=await this.getExamples(r),i=(await Promise.all(s.map(a=>this.examplePrompt.formatMessages(a)))).flat().map(a=>a.content);return Wr([this.prefix,...i,this.suffix].join(this.exampleSeparator),this.templateFormat,r)}async partial(t){const r=this.inputVariables.filter(i=>!(i in t)),s={...this.partialVariables??{},...t};return new Yx({...this,inputVariables:r,partialVariables:s})}},F5=class oh extends Fl{constructor(t){super({...t,inputVariables:[]});p(this,"pipelinePrompts");p(this,"finalPrompt");this.pipelinePrompts=t.pipelinePrompts,this.finalPrompt=t.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){const t=this.pipelinePrompts.map(s=>s.name),r=this.pipelinePrompts.map(s=>s.prompt.inputVariables.filter(i=>!t.includes(i))).flat();return[...new Set(r)]}static extractRequiredInputValues(t,r){return r.reduce((s,i)=>(s[i]=t[i],s),{})}async formatPipelinePrompts(t){const r=await this.mergePartialAndUserVariables(t);for(const{name:s,prompt:i}of this.pipelinePrompts){const a=oh.extractRequiredInputValues(r,i.inputVariables);i instanceof xw?r[s]=await i.formatMessages(a):r[s]=await i.format(a)}return oh.extractRequiredInputValues(r,this.finalPrompt.inputVariables)}async formatPromptValue(t){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(t))}async format(t){return this.finalPrompt.format(await this.formatPipelinePrompts(t))}async partial(t){const r={...this};return r.inputVariables=this.inputVariables.filter(s=>!(s in t)),r.partialVariables={...this.partialVariables??{},...t},new oh(r)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}};function oS(n){return typeof n=="object"&&n!=null&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function"}function B5(n){return typeof n=="object"&&n!=null&&"lc_id"in n&&Array.isArray(n.lc_id)&&n.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var H5=class Xx extends xw{constructor(t){super(t);p(this,"schema");p(this,"method");p(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=t.schema,this.method=t.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(t){if(oS(t))return super.pipe(t.withStructuredOutput(this.schema));if(B5(t)&&oS(t.bound))return super.pipe(new mn({bound:t.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:t.kwargs??{},config:t.config,configFactories:t.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(t,r,s){return Xx.fromMessages(t,{schema:r,method:s})}},V5=he({AIMessagePromptTemplate:()=>Gx,BaseChatPromptTemplate:()=>Ew,BaseMessagePromptTemplate:()=>hp,BaseMessageStringPromptTemplate:()=>Wx,BasePromptTemplate:()=>Fl,BaseStringPromptTemplate:()=>tl,ChatMessagePromptTemplate:()=>qx,ChatPromptTemplate:()=>xw,DEFAULT_FORMATTER_MAPPING:()=>af,DEFAULT_PARSER_MAPPING:()=>Zx,DictPromptTemplate:()=>h_,FewShotChatMessagePromptTemplate:()=>z5,FewShotPromptTemplate:()=>U5,HumanMessagePromptTemplate:()=>Iw,ImagePromptTemplate:()=>ih,MessagesPlaceholder:()=>m_,PipelinePromptTemplate:()=>F5,PromptTemplate:()=>Ci,StructuredPrompt:()=>H5,SystemMessagePromptTemplate:()=>Jx,checkValidTemplate:()=>Hl,interpolateFString:()=>Hx,interpolateMustache:()=>Vx,parseFString:()=>rl,parseMustache:()=>sf,parseTemplate:()=>of,renderTemplate:()=>Wr}),Z5=he({BaseDocumentCompressor:()=>K5}),K5=class{static isBaseDocumentCompressor(n){return(n==null?void 0:n.compressDocuments)!==void 0}},W5=he({BaseRetriever:()=>Ow}),Ow=class extends Ge{constructor(e){super(e);p(this,"callbacks");p(this,"tags");p(this,"metadata");p(this,"verbose");this.callbacks=e==null?void 0:e.callbacks,this.tags=(e==null?void 0:e.tags)??[],this.metadata=(e==null?void 0:e.metadata)??{},this.verbose=(e==null?void 0:e.verbose)??!1}_getRelevantDocuments(e,t){throw new Error("Not implemented!")}async invoke(e,t){var i;const r=rt(Pl(t)),s=await((i=await An.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}}},q5=he({BaseStore:()=>Qx,InMemoryStore:()=>G5}),Qx=class extends kr{},G5=class extends Qx{constructor(){super(...arguments);p(this,"lc_namespace",["langchain","storage"]);p(this,"store",{})}async mget(e){return e.map(t=>this.store[t])}async mset(e){for(const[t,r]of e)this.store[t]=r}async mdelete(e){for(const t of e)delete this.store[t]}async*yieldKeys(e){const t=Object.keys(this.store);for(const r of t)(e===void 0||r.startsWith(e))&&(yield r)}};const bi={and:"and",or:"or",not:"not"},tt={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"};var eO=class{},Cw=class{accept(n){if(this.exprName==="Operation")return n.visitOperation(this);if(this.exprName==="Comparison")return n.visitComparison(this);if(this.exprName==="StructuredQuery")return n.visitStructuredQuery(this);throw new Error("Unknown Expression type")}},$w=class extends Cw{},J5=class extends $w{constructor(e,t,r){super();p(this,"exprName","Comparison");this.comparator=e,this.attribute=t,this.value=r}},Y5=class extends $w{constructor(e,t){super();p(this,"exprName","Operation");this.operator=e,this.args=t}},X5=class extends Cw{constructor(e,t){super();p(this,"exprName","StructuredQuery");this.query=e,this.filter=t}};function tO(n){return n&&typeof n=="object"&&!Array.isArray(n)}function Zr(n){return n?typeof n=="string"&&n.length>0||typeof n=="function"?!1:tO(n)&&Object.keys(n).length===0:!0}function nO(n){if(typeof n=="number")return n%1===0;if(typeof n=="string"){const e=parseInt(n,10);return!Number.isNaN(e)&&e%1===0&&e.toString()===n}return!1}function rO(n){if(typeof n=="number")return n%1!==0;if(typeof n=="string"){const e=parseFloat(n);return!Number.isNaN(e)&&e%1!==0&&e.toString()===n}return!1}function sO(n){return typeof n=="string"&&(Number.isNaN(parseFloat(n))||parseFloat(n).toString()!==n)}function iO(n){return typeof n=="boolean"}function Rw(n){let e;if(sO(n))e=n;else if(nO(n))e=parseInt(n,10);else if(rO(n))e=parseFloat(n);else if(iO(n))e=!!n;else throw new Error("Unsupported value type");return e}var Pw=class extends eO{},Q5=class extends Pw{constructor(e){super();p(this,"allowedOperators");p(this,"allowedComparators");this.allowedOperators=(e==null?void 0:e.allowedOperators)??[bi.and,bi.or],this.allowedComparators=(e==null?void 0:e.allowedComparators)??[tt.eq,tt.ne,tt.gt,tt.gte,tt.lt,tt.lte]}formatFunction(e){if(e in tt){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 bi){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 t=(r=e.args)==null?void 0:r.map(s=>s.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:Rw(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,r="and",s=!1){if(!(Zr(e)&&Zr(t))){if(Zr(e)||r==="replace")return Zr(t)?void 0:t;if(Zr(t))return s?e:r==="and"?void 0:e;if(r==="and")return{$and:[e,t]};if(r==="or")return{$or:[e,t]};throw new Error("Unknown merge type")}}},e9=class extends Pw{constructor(){super(...arguments);p(this,"allowedOperators",[bi.and,bi.or]);p(this,"allowedComparators",[tt.eq,tt.ne,tt.gt,tt.gte,tt.lt,tt.lte])}formatFunction(){throw new Error("Not implemented")}getAllowedComparatorsForType(e){switch(e){case"string":return[tt.eq,tt.ne,tt.gt,tt.gte,tt.lt,tt.lte];case"number":return[tt.eq,tt.ne,tt.gt,tt.gte,tt.lt,tt.lte];case"boolean":return[tt.eq,tt.ne];default:throw new Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case tt.eq:return(t,r)=>t===r;case tt.ne:return(t,r)=>t!==r;case tt.gt:return(t,r)=>t>r;case tt.gte:return(t,r)=>t>=r;case tt.lt:return(t,r)=>t<r;case tt.lte:return(t,r)=>t<=r;default:throw new Error("Unknown comparator")}}getOperatorFunction(e){switch(e){case bi.and:return(t,r)=>t&&r;case bi.or:return(t,r)=>t||r;default:throw new Error("Unknown operator")}}visitOperation(e){const{operator:t,args:r}=e;if(this.allowedOperators.includes(t)){const s=this.getOperatorFunction(t);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:t,attribute:r,value:s}=e,i=[tt.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof s).includes(t))throw new Error(`'${t}' comparator not allowed to be used with ${typeof s}`);const a=this.getComparatorFunction(t);return o=>{const c=o.metadata[r];return c===void 0?!!i.includes(t):a(c,Rw(s))}}else throw new Error("Comparator not allowed")}visitStructuredQuery(e){var r;if(!e.filter)return{};const t=(r=e.filter)==null?void 0:r.accept(this);if(typeof t!="function")throw new Error("Structured query filter is not a function");return{filter:t}}mergeFilters(e,t,r="and"){if(!(Zr(e)&&Zr(t))){if(Zr(e)||r==="replace")return Zr(t)?void 0:t;if(Zr(t))return r==="and"?void 0:e;if(r==="and")return s=>e(s)&&t(s);if(r==="or")return s=>e(s)||t(s);throw new Error("Unknown merge type")}}},t9=he({BaseTranslator:()=>Pw,BasicTranslator:()=>Q5,Comparators:()=>tt,Comparison:()=>J5,Expression:()=>Cw,FilterDirective:()=>$w,FunctionalTranslator:()=>e9,Operation:()=>Y5,Operators:()=>bi,StructuredQuery:()=>X5,Visitor:()=>eO,castValue:()=>Rw,isBoolean:()=>iO,isFilterEmpty:()=>Zr,isFloat:()=>rO,isInt:()=>nO,isObject:()=>tO,isString:()=>sO});function sl(n){return Lt.isInstance(n)?n.constructor.name||n.type:typeof n}function fp(n,e){return function(t,r){const{isNot:s,utils:i}=this;if(!e(t))return{pass:!1,message:()=>`${i.matcherHint(`toBe${n}`,void 0,void 0)}
|
|
261
|
+
|
|
262
|
+
Expected: ${s?"not ":""}${n}
|
|
263
|
+
Received: ${sl(t)}`,actual:sl(t),expected:n};if(r===void 0)return{pass:!0,message:()=>`${i.matcherHint(`toBe${n}`,void 0,void 0)}
|
|
264
|
+
|
|
265
|
+
Expected: not ${n}
|
|
266
|
+
Received: ${n}`};const a=t;return typeof r=="string"?{pass:a.content===r,message:()=>`${i.matcherHint(`toBe${n}`,void 0,void 0)}
|
|
267
|
+
|
|
268
|
+
Expected: ${n} with content ${i.printExpected(r)}
|
|
269
|
+
Received: ${n} 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${n}`,void 0,void 0)}
|
|
270
|
+
|
|
271
|
+
Expected: ${n} matching ${i.printExpected(r)}
|
|
272
|
+
Received: ${n} with ${i.printReceived(o)}`},actual:(()=>{const o={};for(const c of Object.keys(r))o[c]=a[c];return o})(),expected:r}}}const aO=fp("HumanMessage",Dn.isInstance),oO=fp("AIMessage",Ve.isInstance),cO=fp("SystemMessage",hr.isInstance),uO=fp("ToolMessage",_n.isInstance);function lO(n,e){const{isNot:t,utils:r}=this;if(!Ve.isInstance(n))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
|
|
273
|
+
|
|
274
|
+
Expected: AIMessage
|
|
275
|
+
Received: ${sl(n)}`};const s=n.tool_calls??[];if(s.length!==e.length)return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCalls")}
|
|
276
|
+
|
|
277
|
+
Expected ${t?"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")}
|
|
278
|
+
|
|
279
|
+
Could not find matching tool call(s) for:
|
|
280
|
+
${r.printExpected(i)}
|
|
281
|
+
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")}
|
|
282
|
+
|
|
283
|
+
Expected AIMessage not to have matching tool calls`}}function dO(n,e){var i;const{isNot:t,utils:r}=this;if(!Ve.isInstance(n))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolCallCount")}
|
|
284
|
+
|
|
285
|
+
Expected: AIMessage
|
|
286
|
+
Received: ${sl(n)}`};const s=((i=n.tool_calls)==null?void 0:i.length)??0;return{pass:s===e,message:()=>`${r.matcherHint("toHaveToolCallCount")}
|
|
287
|
+
|
|
288
|
+
Expected ${t?"not ":""}${e} tool call(s)
|
|
289
|
+
Received: ${s}`,actual:s,expected:e}}function hO(n,e){const{isNot:t,utils:r}=this;if(!Ve.isInstance(n))return{pass:!1,message:()=>`${r.matcherHint("toContainToolCall")}
|
|
290
|
+
|
|
291
|
+
Expected: AIMessage
|
|
292
|
+
Received: ${sl(n)}`};const s=n.tool_calls??[];return{pass:s.some(i=>Object.entries(e).every(([a,o])=>this.equals(i[a],o))),message:()=>`${r.matcherHint("toContainToolCall")}
|
|
293
|
+
|
|
294
|
+
Expected AIMessage ${t?"not ":""}to contain a tool call matching ${r.printExpected(e)}
|
|
295
|
+
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 fO(n,e){const{isNot:t,utils:r}=this;if(!Array.isArray(n))return{pass:!1,message:()=>`${r.matcherHint("toHaveToolMessages")}
|
|
296
|
+
|
|
297
|
+
Expected an array of messages
|
|
298
|
+
Received: ${typeof n}`};const s=n.filter(_n.isInstance);if(s.length!==e.length)return{pass:!1,message:()=>`${r.matcherHint("toHaveToolMessages")}
|
|
299
|
+
|
|
300
|
+
Expected ${t?"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")}
|
|
301
|
+
|
|
302
|
+
Tool message at index ${i} did not match:
|
|
303
|
+
Expected: ${r.printExpected(e[i])}
|
|
304
|
+
Received: ${r.printReceived(a)}`},actual:s[i],expected:e[i]};return{pass:!0,message:()=>`${r.matcherHint("toHaveToolMessages")}
|
|
305
|
+
|
|
306
|
+
Expected messages not to contain matching tool messages`}}function pO(n,e){var a;const{isNot:t,utils:r}=this,s=n==null?void 0:n.__interrupt__;if(!(Array.isArray(s)&&s.length>0))return{pass:!1,message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
|
|
307
|
+
|
|
308
|
+
Expected result ${t?"not ":""}to have been interrupted
|
|
309
|
+
Received __interrupt__: ${r.printReceived(s)}`};if(e===void 0)return{pass:!0,message:()=>`${r.matcherHint("toHaveBeenInterrupted")}
|
|
310
|
+
|
|
311
|
+
Expected result not to have been interrupted
|
|
312
|
+
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")}
|
|
313
|
+
|
|
314
|
+
Expected interrupt value: ${r.printExpected(e)}
|
|
315
|
+
Received interrupt value: ${r.printReceived(i)}`,actual:i,expected:e}}function mO(n,e){const{isNot:t,utils:r}=this,s=n==null?void 0:n.structuredResponse;return s===void 0?{pass:!1,message:()=>`${r.matcherHint("toHaveStructuredResponse")}
|
|
316
|
+
|
|
317
|
+
Expected result ${t?"not ":""}to have a structured response
|
|
318
|
+
Received structuredResponse: undefined`}:e===void 0?{pass:!0,message:()=>`${r.matcherHint("toHaveStructuredResponse")}
|
|
319
|
+
|
|
320
|
+
Expected result not to have a structured response`}:{pass:Object.entries(e).every(([i,a])=>this.equals(s[i],a)),message:()=>`${r.matcherHint("toHaveStructuredResponse")}
|
|
321
|
+
|
|
322
|
+
Expected structured response: ${r.printExpected(e)}
|
|
323
|
+
Received structured response: ${r.printReceived(s)}`,actual:s,expected:e}}const n9={toBeHumanMessage:aO,toBeAIMessage:oO,toBeSystemMessage:cO,toBeToolMessage:uO,toHaveToolCalls:lO,toHaveToolCallCount:dO,toContainToolCall:hO,toHaveToolMessages:fO,toHaveBeenInterrupted:pO,toHaveStructuredResponse:mO};function r9(n){return n.map(e=>e.text).filter(Boolean).join("-")}let cS=0;function s9(){return cS+=1,`fake_tc_${cS}`}var gO=class _O extends Is{constructor(){super({});p(this,"queue",[]);p(this,"_alwaysThrowError");p(this,"_structuredResponseValue");p(this,"_tools",[]);p(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(t){return typeof t=="function"?this.queue.push({kind:"factory",factory:t}):Lt.isInstance(t)?this.queue.push({kind:"message",message:t}):this.queue.push({kind:"error",error:t}),this}respondWithTools(t){return this.queue.push({kind:"toolCalls",toolCalls:t.map(r=>({name:r.name,args:r.args,id:r.id??s9(),type:"tool_call"}))}),this}alwaysThrow(t){return this._alwaysThrowError=t,this}structuredResponse(t){return this._structuredResponseValue=t,this}bindTools(t){const r=[...this._tools,...t],s=new _O;return s.queue=this.queue,s._alwaysThrowError=this._alwaysThrowError,s._structuredResponseValue=this._structuredResponseValue,s._tools=r,s._state=this._state,s.withConfig({})}withStructuredOutput(t,r){const{_structuredResponseValue:s}=this;return an.from(async()=>s)}async _generate(t,r,s){this._state.calls.push({messages:[...t],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(t);if(!Lt.isInstance(c))throw c;return{generations:[{text:"",message:c}]}}if(a.kind==="message")return{generations:[{text:"",message:a.message}]};const o=r9(t);return{generations:[{text:o,message:new Ve({content:o,id:i.toString(),tool_calls:a.toolCalls.length>0?a.toolCalls.map(c=>({...c,type:"tool_call"})):void 0})}],llmOutput:{}}}};function i9(){return new gO}var a9=he({FakeBuiltModel:()=>gO,fakeModel:()=>i9,langchainMatchers:()=>n9,toBeAIMessage:()=>oO,toBeHumanMessage:()=>aO,toBeSystemMessage:()=>cO,toBeToolMessage:()=>uO,toContainToolCall:()=>hO,toHaveBeenInterrupted:()=>pO,toHaveStructuredResponse:()=>mO,toHaveToolCallCount:()=>dO,toHaveToolCalls:()=>lO,toHaveToolMessages:()=>fO});function Nw(n){return n!==void 0&&Array.isArray(n.lc_namespace)}function Mw(n){return n!==void 0&&Ge.isRunnable(n)&&"lc_name"in n.constructor&&typeof n.constructor.lc_name=="function"&&n.constructor.lc_name()==="RunnableToolLike"}function jw(n){return!!n&&typeof n=="object"&&"name"in n&&"schema"in n&&(Xt(n.schema)||n.schema!=null&&typeof n.schema=="object"&&"type"in n.schema&&typeof n.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(n.schema.type))}function Ys(n){return jw(n)||Mw(n)||Nw(n)}const o9=z("ZodISODateTime",(n,e)=>{J4.init(n,e),Nt.init(n,e)});function c9(n){return nz(o9,n)}const u9=z("ZodISODate",(n,e)=>{Y4.init(n,e),Nt.init(n,e)});function l9(n){return rz(u9,n)}const d9=z("ZodISOTime",(n,e)=>{X4.init(n,e),Nt.init(n,e)});function h9(n){return sz(d9,n)}const f9=z("ZodISODuration",(n,e)=>{Q4.init(n,e),Nt.init(n,e)});function p9(n){return iz(f9,n)}const m9=(n,e)=>{$k.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>zD(n,t)},flatten:{value:t=>UD(n,t)},addIssue:{value:t=>{n.issues.push(t),n.message=JSON.stringify(n.issues,Dg,2)}},addIssues:{value:t=>{n.issues.push(...t),n.message=JSON.stringify(n.issues,Dg,2)}},isEmpty:{get(){return n.issues.length===0}}})},$r=z("ZodError",m9,{Parent:Error}),g9=qf($r),_9=Jf($r),y9=Yf($r),w9=Xf($r),b9=ZD($r),v9=KD($r),S9=WD($r),A9=qD($r),T9=GD($r),E9=JD($r),k9=YD($r),I9=XD($r),uS=new WeakMap;function Vl(n,e,t){const r=Object.getPrototypeOf(n);let s=uS.get(r);if(s||(s=new Set,uS.set(r,s)),!s.has(e)){s.add(e);for(const i in t){const a=t[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const o=a.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}const xt=z("ZodType",(n,e)=>(Et.init(n,e),Object.assign(n["~standard"],{jsonSchema:{input:qh(n,"input"),output:qh(n,"output")}}),n.toJSONSchema=kz(n,{}),n.def=e,n.type=e.type,Object.defineProperty(n,"_def",{value:e}),n.parse=(t,r)=>g9(n,t,r,{callee:n.parse}),n.safeParse=(t,r)=>y9(n,t,r),n.parseAsync=async(t,r)=>_9(n,t,r,{callee:n.parseAsync}),n.safeParseAsync=async(t,r)=>w9(n,t,r),n.spa=n.safeParseAsync,n.encode=(t,r)=>b9(n,t,r),n.decode=(t,r)=>v9(n,t,r),n.encodeAsync=async(t,r)=>S9(n,t,r),n.decodeAsync=async(t,r)=>A9(n,t,r),n.safeEncode=(t,r)=>T9(n,t,r),n.safeDecode=(t,r)=>E9(n,t,r),n.safeEncodeAsync=async(t,r)=>k9(n,t,r),n.safeDecodeAsync=async(t,r)=>I9(n,t,r),Vl(n,"ZodType",{check(...t){const r=this.def;return this.clone(Bi(r,{checks:[...r.checks??[],...t.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,r){return pn(this,t,r)},brand(){return this},register(t,r){return t.add(this,r),this},refine(t,r){return this.check(SH(t,r))},superRefine(t,r){return this.check(AH(t,r))},overwrite(t){return this.check(bc(t))},optional(){return fS(this)},exactOptional(){return lH(this)},nullable(){return pS(this)},nullish(){return fS(pS(this))},nonoptional(t){return gH(this,t)},array(){return Ca(this)},or(t){return Zl([this,t])},and(t){return rH(this,t)},transform(t){return mS(this,cH(t))},default(t){return fH(this,t)},prefault(t){return mH(this,t)},catch(t){return yH(this,t)},pipe(t){return mS(this,t)},readonly(){return vH(this)},describe(t){const r=this.clone();return sn.add(r,{description:t}),r},meta(...t){if(t.length===0)return sn.get(this);const r=this.clone();return sn.add(r,t[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t){return t(this)}}),Object.defineProperty(n,"description",{get(){var t;return(t=sn.get(n))==null?void 0:t.description},configurable:!0}),n)),yO=z("_ZodString",(n,e)=>{Jy.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(r,s,i)=>Yk(n,r,s);const t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,Vl(n,"_ZodString",{regex(...r){return this.check(lz(...r))},includes(...r){return this.check(fz(...r))},startsWith(...r){return this.check(pz(...r))},endsWith(...r){return this.check(mz(...r))},min(...r){return this.check(Vh(...r))},max(...r){return this.check(Gk(...r))},length(...r){return this.check(Jk(...r))},nonempty(...r){return this.check(Vh(1,...r))},lowercase(r){return this.check(dz(r))},uppercase(r){return this.check(hz(r))},trim(){return this.check(_z())},normalize(...r){return this.check(gz(...r))},toLowerCase(){return this.check(yz())},toUpperCase(){return this.check(wz())},slugify(){return this.check(bz())}})}),x9=z("ZodString",(n,e)=>{Jy.init(n,e),yO.init(n,e),n.email=t=>n.check(MU(O9,t)),n.url=t=>n.check(zU(C9,t)),n.jwt=t=>n.check(tz(Z9,t)),n.emoji=t=>n.check(FU($9,t)),n.guid=t=>n.check(f0(lS,t)),n.uuid=t=>n.check(jU(yd,t)),n.uuidv4=t=>n.check(LU(yd,t)),n.uuidv6=t=>n.check(DU(yd,t)),n.uuidv7=t=>n.check(UU(yd,t)),n.nanoid=t=>n.check(BU(R9,t)),n.guid=t=>n.check(f0(lS,t)),n.cuid=t=>n.check(HU(P9,t)),n.cuid2=t=>n.check(VU(N9,t)),n.ulid=t=>n.check(ZU(M9,t)),n.base64=t=>n.check(XU(B9,t)),n.base64url=t=>n.check(QU(H9,t)),n.xid=t=>n.check(KU(j9,t)),n.ksuid=t=>n.check(WU(L9,t)),n.ipv4=t=>n.check(qU(D9,t)),n.ipv6=t=>n.check(GU(U9,t)),n.cidrv4=t=>n.check(JU(z9,t)),n.cidrv6=t=>n.check(YU(F9,t)),n.e164=t=>n.check(ez(V9,t)),n.datetime=t=>n.check(c9(t)),n.date=t=>n.check(l9(t)),n.time=t=>n.check(h9(t)),n.duration=t=>n.check(p9(t))});function Xe(n){return NU(x9,n)}const Nt=z("ZodStringFormat",(n,e)=>{$t.init(n,e),yO.init(n,e)}),O9=z("ZodEmail",(n,e)=>{F4.init(n,e),Nt.init(n,e)}),lS=z("ZodGUID",(n,e)=>{U4.init(n,e),Nt.init(n,e)}),yd=z("ZodUUID",(n,e)=>{z4.init(n,e),Nt.init(n,e)}),C9=z("ZodURL",(n,e)=>{B4.init(n,e),Nt.init(n,e)}),$9=z("ZodEmoji",(n,e)=>{H4.init(n,e),Nt.init(n,e)}),R9=z("ZodNanoID",(n,e)=>{V4.init(n,e),Nt.init(n,e)}),P9=z("ZodCUID",(n,e)=>{Z4.init(n,e),Nt.init(n,e)}),N9=z("ZodCUID2",(n,e)=>{K4.init(n,e),Nt.init(n,e)}),M9=z("ZodULID",(n,e)=>{W4.init(n,e),Nt.init(n,e)}),j9=z("ZodXID",(n,e)=>{q4.init(n,e),Nt.init(n,e)}),L9=z("ZodKSUID",(n,e)=>{G4.init(n,e),Nt.init(n,e)}),D9=z("ZodIPv4",(n,e)=>{eU.init(n,e),Nt.init(n,e)}),U9=z("ZodIPv6",(n,e)=>{tU.init(n,e),Nt.init(n,e)}),z9=z("ZodCIDRv4",(n,e)=>{nU.init(n,e),Nt.init(n,e)}),F9=z("ZodCIDRv6",(n,e)=>{rU.init(n,e),Nt.init(n,e)}),B9=z("ZodBase64",(n,e)=>{sU.init(n,e),Nt.init(n,e)}),H9=z("ZodBase64URL",(n,e)=>{aU.init(n,e),Nt.init(n,e)}),V9=z("ZodE164",(n,e)=>{oU.init(n,e),Nt.init(n,e)}),Z9=z("ZodJWT",(n,e)=>{uU.init(n,e),Nt.init(n,e)}),wO=z("ZodNumber",(n,e)=>{Fk.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(r,s,i)=>Xk(n,r,s),Vl(n,"ZodNumber",{gt(r,s){return this.check(m0(r,s))},gte(r,s){return this.check(um(r,s))},min(r,s){return this.check(um(r,s))},lt(r,s){return this.check(p0(r,s))},lte(r,s){return this.check(cm(r,s))},max(r,s){return this.check(cm(r,s))},int(r){return this.check(dS(r))},safe(r){return this.check(dS(r))},positive(r){return this.check(m0(0,r))},nonnegative(r){return this.check(um(0,r))},negative(r){return this.check(p0(0,r))},nonpositive(r){return this.check(cm(0,r))},multipleOf(r,s){return this.check(g0(r,s))},step(r,s){return this.check(g0(r,s))},finite(){return this}});const t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});function gt(n){return az(wO,n)}const K9=z("ZodNumberFormat",(n,e)=>{lU.init(n,e),wO.init(n,e)});function dS(n){return oz(K9,n)}const W9=z("ZodBoolean",(n,e)=>{dU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>Qk(n,t,r)});function q9(n){return cz(W9,n)}const G9=z("ZodAny",(n,e)=>{hU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>tI()});function wd(){return uz(G9)}const J9=z("ZodUnknown",(n,e)=>{Bk.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>nI()});function cf(){return Wk(J9)}const Y9=z("ZodNever",(n,e)=>{Hk.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>eI(n,t,r)});function X9(n){return qk(Y9,n)}const Q9=z("ZodArray",(n,e)=>{fU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>oI(n,t,r,s),n.element=e.element,Vl(n,"ZodArray",{min(t,r){return this.check(Vh(t,r))},nonempty(t){return this.check(Vh(1,t))},max(t,r){return this.check(Gk(t,r))},length(t,r){return this.check(Jk(t,r))},unwrap(){return this.element}})});function Ca(n,e){return vz(Q9,n,e)}const eH=z("ZodObject",(n,e)=>{mU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>cI(n,t,r,s),pt(n,"shape",()=>e.shape),Vl(n,"ZodObject",{keyof(){return mp(Object.keys(this._zod.def.shape))},catchall(t){return this.clone({...this._zod.def,catchall:t})},passthrough(){return this.clone({...this._zod.def,catchall:cf()})},loose(){return this.clone({...this._zod.def,catchall:cf()})},strict(){return this.clone({...this._zod.def,catchall:X9()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(t){return xk(this,t)},safeExtend(t){return MD(this,t)},merge(t){return jD(this,t)},pick(t){return PD(this,t)},omit(t){return ND(this,t)},partial(...t){return Ok(vO,this,t[0])},required(...t){return LD(SO,this,t[0])}})});function Me(n,e){const t={type:"object",shape:n??{},...Ae(e)};return new eH(t)}const bO=z("ZodUnion",(n,e)=>{Kk.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>uI(n,t,r,s),n.options=e.options});function Zl(n,e){return new bO({type:"union",options:n,...Ae(e)})}const tH=z("ZodDiscriminatedUnion",(n,e)=>{bO.init(n,e),gU.init(n,e)});function pp(n,e,t){return new tH({type:"union",options:e,discriminator:n,...Ae(t)})}const nH=z("ZodIntersection",(n,e)=>{_U.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>lI(n,t,r,s)});function rH(n,e){return new nH({type:"intersection",left:n,right:e})}const sH=z("ZodTuple",(n,e)=>{yU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>dI(n,t,r,s),n.rest=t=>n.clone({...n._zod.def,rest:t})});function Lw(n,e,t){const r=e instanceof Et,s=r?t:e,i=r?e:null;return new sH({type:"tuple",items:n,rest:i,...Ae(s)})}const hS=z("ZodRecord",(n,e)=>{wU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>hI(n,t,r,s),n.keyType=e.keyType,n.valueType=e.valueType});function iH(n,e,t){return!e||!e._zod?new hS({type:"record",keyType:Xe(),valueType:n,...Ae(e)}):new hS({type:"record",keyType:n,valueType:e,...Ae(t)})}const __=z("ZodEnum",(n,e)=>{bU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(r,s,i)=>rI(n,r,s),n.enum=e.entries,n.options=Object.values(e.entries);const t=new Set(Object.keys(e.entries));n.extract=(r,s)=>{const i={};for(const a of r)if(t.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new __({...e,checks:[],...Ae(s),entries:i})},n.exclude=(r,s)=>{const i={...e.entries};for(const a of r)if(t.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new __({...e,checks:[],...Ae(s),entries:i})}});function mp(n,e){const t=Array.isArray(n)?Object.fromEntries(n.map(r=>[r,r])):n;return new __({type:"enum",entries:t,...Ae(e)})}const aH=z("ZodLiteral",(n,e)=>{vU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>sI(n,t,r),n.values=new Set(e.values),Object.defineProperty(n,"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 Ze(n,e){return new aH({type:"literal",values:Array.isArray(n)?n:[n],...Ae(e)})}const oH=z("ZodTransform",(n,e)=>{SU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>aI(n,t),n._zod.parse=(t,r)=>{if(r.direction==="backward")throw new Tk(n.constructor.name);t.addIssue=i=>{if(typeof i=="string")t.issues.push(qu(i,t.value,e));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=t.value),a.inst??(a.inst=n),t.issues.push(qu(a))}};const s=e.transform(t.value,t);return s instanceof Promise?s.then(i=>(t.value=i,t.fallback=!0,t)):(t.value=s,t.fallback=!0,t)}});function cH(n){return new oH({type:"transform",transform:n})}const vO=z("ZodOptional",(n,e)=>{ep.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>Yy(n,t,r,s),n.unwrap=()=>n._zod.def.innerType});function fS(n){return new vO({type:"optional",innerType:n})}const uH=z("ZodExactOptional",(n,e)=>{AU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>Yy(n,t,r,s),n.unwrap=()=>n._zod.def.innerType});function lH(n){return new uH({type:"optional",innerType:n})}const dH=z("ZodNullable",(n,e)=>{TU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>fI(n,t,r,s),n.unwrap=()=>n._zod.def.innerType});function pS(n){return new dH({type:"nullable",innerType:n})}const hH=z("ZodDefault",(n,e)=>{EU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>mI(n,t,r,s),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});function fH(n,e){return new hH({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():Ik(e)}})}const pH=z("ZodPrefault",(n,e)=>{kU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>gI(n,t,r,s),n.unwrap=()=>n._zod.def.innerType});function mH(n,e){return new pH({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():Ik(e)}})}const SO=z("ZodNonOptional",(n,e)=>{IU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>pI(n,t,r,s),n.unwrap=()=>n._zod.def.innerType});function gH(n,e){return new SO({type:"nonoptional",innerType:n,...Ae(e)})}const _H=z("ZodCatch",(n,e)=>{xU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>_I(n,t,r,s),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});function yH(n,e){return new _H({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}const wH=z("ZodPipe",(n,e)=>{OU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>yI(n,t,r,s),n.in=e.in,n.out=e.out});function mS(n,e){return new wH({type:"pipe",in:n,out:e})}const bH=z("ZodReadonly",(n,e)=>{CU.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>wI(n,t,r,s),n.unwrap=()=>n._zod.def.innerType});function vH(n){return new bH({type:"readonly",innerType:n})}const AO=z("ZodCustom",(n,e)=>{$U.init(n,e),xt.init(n,e),n._zod.processJSONSchema=(t,r,s)=>iI(n,t)});function y_(n,e){return Sz(AO,()=>!0,e)}function SH(n,e={}){return Az(AO,n,e)}function AH(n,e){return Tz(n,e)}var TH=he({BaseToolkit:()=>EH,DynamicStructuredTool:()=>kO,DynamicTool:()=>EO,StructuredTool:()=>gp,Tool:()=>TO,ToolInputParsingException:()=>$h,isLangChainTool:()=>Ys,isRunnableToolLike:()=>Mw,isStructuredTool:()=>Nw,isStructuredToolParams:()=>jw,tool:()=>li}),gp=class extends yw{constructor(e){super(e??{});p(this,"extras");p(this,"returnDirect",!1);p(this,"verboseParsingErrors",!1);p(this,"responseFormat","content");p(this,"defaultConfig");this.verboseParsingErrors=(e==null?void 0:e.verboseParsingErrors)??this.verboseParsingErrors,this.responseFormat=(e==null?void 0:e.responseFormat)??this.responseFormat,this.defaultConfig=(e==null?void 0:e.defaultConfig)??this.defaultConfig,this.metadata=(e==null?void 0:e.metadata)??this.metadata,this.extras=(e==null?void 0:e.extras)??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,t){let r,s=rt(or(this.defaultConfig,t));return Eu(e)?(r=e.args,s={...s,toolCall:e}):r=e,this.call(r,s)}async call(e,t,r){const s=Eu(e)?e.args:e;let i;if(Xt(this.schema))try{i=await np(this.schema,s)}catch(m){let g="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(g=`${g}
|
|
324
|
+
Details: ${m.message}`),kI(m)&&(g=`${g}
|
|
325
|
+
|
|
326
|
+
${BD(m)}`),new $h(g,JSON.stringify(e))}else{const m=Ct(s,this.schema);if(!m.valid){let g="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(g=`${g}
|
|
327
|
+
Details: ${m.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
|
|
328
|
+
`)}`),new $h(g,JSON.stringify(e))}i=s}const a=Pl(t),o=An.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose});let c;Eu(e)&&(c=e.id),!c&&NP(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 m=await this._call(i,u,a);l=ZI(m)?await JB(m,async g=>{try{await(u==null?void 0:u.handleToolEvent(g))}catch(y){await(u==null?void 0:u.handleToolError(y))}}):m}catch(m){throw await(u==null?void 0:u.handleToolError(m)),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[d,f]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
|
|
329
|
+
Result: ${JSON.stringify(l)}`);else d=l;const h=kH({content:d,artifact:f,toolCallId:c,name:this.name,metadata:this.metadata});return await(u==null?void 0:u.handleToolEnd(h)),h}},TO=class extends gp{constructor(e){super(e);p(this,"schema",ap({input:ip().optional()}).transform(e=>e.input))}call(e,t){const r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},EO=class extends TO{constructor(e){super(e);p(this,"name");p(this,"description");p(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,t){const r=Pl(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,t,r){return this.func(e,t,r)}},kO=class extends gp{constructor(e){super(e);p(this,"description");p(this,"func");p(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,t,r){const s=Pl(t);return s.runName===void 0&&(s.runName=this.name),super.call(e,s,r)}_call(e,t,r){return this.func(e,t,r)}},EH=class{getTools(){return this.tools}};function li(n,e){var a;const t=Xy(e.schema),r=Ou(e.schema);if(!e.schema||t||r)return new EO({...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=ut(u,{callbacks:c==null?void 0:c.getChild()});yn.runWithConfig(Ks(f),async()=>{try{l(n(o,f))}catch(h){d(h)}})})});const s=e.schema,i=e.description??e.schema.description??`${e.name} tool`;return new kO({...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(Vu(u.signal))},u.signal.addEventListener("abort",f,{once:!0}));const m=ut(u,{callbacks:c==null?void 0:c.getChild()});yn.runWithConfig(Ks(m),async()=>{var g;try{const y=await n(o,m);if(ZI(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 kH(n){const{content:e,artifact:t,toolCallId:r,metadata:s}=n;return r&&!Ty(e)?typeof e=="string"||Array.isArray(e)&&e.every(i=>typeof i=="object")?new _n({status:"success",content:e,artifact:t,tool_call_id:r,name:n.name,metadata:s}):new _n({status:"success",content:IH(e),artifact:t,tool_call_id:r,name:n.name,metadata:s}):e}function IH(n){try{return JSON.stringify(n)??""}catch{return`${n}`}}var xH=he({RunCollectorCallbackHandler:()=>OH}),OH=class extends ei{constructor({exampleId:e}={}){super({_awaitHandler:!0});p(this,"name","run_collector");p(this,"exampleId");p(this,"tracedRuns");this.exampleId=e,this.tracedRuns=[]}async persistRun(e){const t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},CH=he({}),$H=he({chunkArray:()=>RH});const RH=(n,e)=>n.reduce((t,r,s)=>{const i=Math.floor(s/e);return t[i]=(t[i]||[]).concat([r]),t},[]);var PH=he({context:()=>NH});function NH(n,...e){const t=n.raw;let r="";for(let s=0;s<t.length;s++){const i=t[s].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(r+=i,s<e.length){const a=MH(e[s],r);r+=typeof a=="string"?a:JSON.stringify(a)}}return r=jH(r),r=r.trim(),r=r.replace(/\\n/g,`
|
|
330
|
+
`),r}function MH(n,e){if(typeof n!="string"||!n.includes(`
|
|
331
|
+
`))return n;const t=e.slice(e.lastIndexOf(`
|
|
332
|
+
`)+1).match(/^(\s+)/);if(t){const r=t[1];return n.replace(/\n/g,`
|
|
333
|
+
${r}`)}return n}function jH(n){const e=n.split(`
|
|
334
|
+
`);let t=null;for(const r of e){const s=r.match(/^(\s+)\S+/);if(s){const i=s[1].length;t===null?t=i:t=Math.min(t,i)}}return t===null?n:e.map(r=>r[0]===" "||r[0]===" "?r.slice(t):r).join(`
|
|
335
|
+
`)}var LH=he({EventStreamContentType:()=>DH,convertEventStreamToIterableReadableDataStream:()=>zH,getBytes:()=>IO,getLines:()=>xO,getMessages:()=>OO});const DH="text/event-stream";async function IO(n,e){if(n instanceof ReadableStream){const t=n.getReader();for(;;){const r=await t.read();if(r.done){e(new Uint8Array,!0);break}e(r.value)}}else try{for await(const t of n)e(new Uint8Array(t));e(new Uint8Array,!0)}catch(t){throw new Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${t.message}`].join(`
|
|
336
|
+
`))}}function xO(n){let e,t,r,s=!1;return function(a,o){if(o){n(a,0,!0);return}e===void 0?(e=a,t=0,r=-1):e=UH(e,a);const c=e.length;let u=0;for(;t<c;){s&&(e[t]===10&&(u=++t),s=!1);let l=-1;for(;t<c&&l===-1;++t)switch(e[t]){case 58:r===-1&&(r=t-u);break;case 13:s=!0;case 10:l=t;break}if(l===-1)break;n(e.subarray(u,l),r),u=t,r=-1}u===c?e=void 0:u!==0&&(e=e.subarray(u),t-=u)}}function OO(n,e,t){let r=Am();const s=new TextDecoder;return function(a,o,c){if(c){FH(r)||(n==null||n(r),r=Am());return}if(a.length===0)n==null||n(r),r=Am();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+`
|
|
337
|
+
`+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)||t==null||t(r.retry=f);break}}}}}function UH(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Am(){return{data:"",event:"",id:"",retry:void 0}}function zH(n,e){const t=new ReadableStream({async start(r){const s=OO(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 IO(n,xO((a,o,c)=>{s(a,o,c),c&&r.close()}))}});return Wn.fromReadableStream(t)}function FH(n){return n.data===""&&n.event===""&&n.id===""&&n.retry===void 0}var BH=he({}),HH=he({convertToOpenAIFunction:()=>CO,convertToOpenAITool:()=>uf,isLangChainTool:()=>Ys,isRunnableToolLike:()=>Mw,isStructuredTool:()=>Nw,isStructuredToolParams:()=>jw});function CO(n,e){const t=typeof e=="number"?void 0:e;return{name:n.name,description:n.description,parameters:At(n.schema),...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}}function uf(n,e){const t=typeof e=="number"?void 0:e;let r;return Ys(n)?r={type:"function",function:CO(n)}:r=n,(t==null?void 0:t.strict)!==void 0&&(r.function.strict=t.strict),r}function $O(n,e){let t=0,r=0,s=0;for(let i=0;i<n.length;i++)t+=n[i]*e[i],r+=n[i]*n[i],s+=e[i]*e[i];return t/(Math.sqrt(r)*Math.sqrt(s))}function VH(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function ZH(n,e){let t=0;for(let r=0;r<n.length;r++)t+=(n[r]-e[r])*(n[r]-e[r]);return t}function KH(n,e){return Math.sqrt(ZH(n,e))}var WH=he({cosineSimilarity:()=>w_,euclideanDistance:()=>JH,innerProduct:()=>GH,matrixFunc:()=>_p,maximalMarginalRelevance:()=>YH,normalize:()=>qH});function _p(n,e,t){if(n.length===0||n[0].length===0||e.length===0||e[0].length===0)return[[]];if(n[0].length!==e[0].length)throw new Error(`Number of columns in X and Y must be the same. X has shape ${[n.length,n[0].length]} and Y has shape ${[e.length,e[0].length]}.`);return n.map(r=>e.map(s=>t(r,s)).map(s=>Number.isNaN(s)?0:s))}function qH(n,e=!1){const t=XH(n);return n.map(r=>r.map(s=>e?1-s/t:s/t))}function w_(n,e){return _p(n,e,$O)}function GH(n,e){return _p(n,e,VH)}function JH(n,e){return _p(n,e,KH)}function YH(n,e,t=.5,r=4){if(Math.min(r,e.length)<=0)return[];const s=w_(Array.isArray(n[0])?n:[n],e)[0],i=RO(s).maxIndex,a=[e[i]],o=[i];for(;o.length<Math.min(r,e.length);){let c=-1/0,u=-1;const l=w_(e,a);s.forEach((d,f)=>{if(o.includes(f))return;const h=Math.max(...l[f]),m=t*d-(1-t)*h;m>c&&(c=m,u=f)}),a.push(e[u]),o.push(u)}return o}function RO(n){if(n.length===0)return{maxIndex:-1,maxValue:NaN};let e=n[0],t=0;for(let r=1;r<n.length;r+=1)n[r]>e&&(t=r,e=n[r]);return{maxIndex:t,maxValue:e}}function XH(n){return n.reduce((e,t)=>Math.max(e,RO(t).maxValue),0)}var QH=he({isCloudMetadata:()=>b_,isLocalhost:()=>v_,isPrivateIp:()=>LO,isSafeUrl:()=>o8,isSameOrigin:()=>c8,validateSafeUrl:()=>DO});const e8=["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"],t8=["169.254.169.254","169.254.170.2","100.100.100.200"],n8=["metadata.google.internal","metadata","instance-data"],r8=["localhost","localhost.localdomain"],s8=/^(?:(?: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 PO(n){return s8.test(n)}function yp(n){return jO(n)!==null}function NO(n){return PO(n)||yp(n)}function MO(n){if(PO(n))return n.split(".").map(e=>parseInt(e,10));if(yp(n)){const e=jO(n);if(!e)return null;const t=e.split(":"),r=[];for(const s of t)r.push(parseInt(s,16));return r}return null}function jO(n){if(!n||typeof n!="string"||!n.includes(":")||!/^[0-9a-fA-F:]+$/.test(n))return null;let e=n;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 t=e.split(":");if(t.length!==8)return null;for(const r of t)if(r.length===0||r.length>4||!/^[0-9a-fA-F]+$/.test(r))return null;return t.map(r=>r.padStart(4,"0").toLowerCase()).join(":")}function i8(n){const[e,t]=n.split("/");if(!e||!t)return null;const r=MO(e);if(!r)return null;const s=parseInt(t,10);if(isNaN(s))return null;const i=yp(e);return i&&s>128||!i&&s>32?null:{addr:r,prefixLen:s,isIpv6:i}}function a8(n,e){const t=MO(n);if(!t)return!1;const r=i8(e);if(!r)return!1;const s=yp(n);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((t[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((t[o]&c)!==(i[o]&c))return!1}return!0}function LO(n){if(!NO(n))return!1;for(const e of e8)if(a8(n,e))return!0;return!1}function b_(n,e){if(t8.includes(e||""))return!0;const t=n.toLowerCase();return!!n8.includes(t)}function v_(n,e){if(e&&(e==="127.0.0.1"||e==="::1"||e==="0.0.0.0"||e.startsWith("127.")))return!0;const t=n.toLowerCase();return!!r8.includes(t)}function DO(n,e){const t=(e==null?void 0:e.allowPrivate)??!1,r=(e==null?void 0:e.allowHttp)??!1;try{let s;try{s=new URL(n)}catch{throw new Error(`Invalid URL: ${n}`)}const i=s.hostname;if(!i)throw new Error("URL missing hostname.");if(b_(i))throw new Error(`URL points to cloud metadata endpoint: ${i}`);if(v_(i)){if(!t)throw new Error(`URL points to localhost: ${i}`);return n}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(NO(i)){const o=i;if(v_(i,o)){if(!t)throw new Error(`URL points to localhost: ${i}`);return n}if(b_(i,o))throw new Error(`URL resolves to cloud metadata IP: ${o} (${i})`);if(LO(o)&&!t)throw new Error(`URL resolves to private IP: ${o} (${i}). Set allowPrivate: true to allow.`);return n}return n}catch(s){throw s&&typeof s=="object"&&"message"in s?s:new Error(`URL validation failed: ${s}`)}}function o8(n,e){try{return DO(n,e),!0}catch{return!1}}function c8(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}var u8=he({SaveableVectorStore:()=>l8,VectorStore:()=>Dw,VectorStoreRetriever:()=>ch}),ch=class extends Ow{constructor(e){super(e);p(this,"vectorStore");p(this,"k",4);p(this,"searchType","similarity");p(this,"searchKwargs");p(this,"filter");this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType==="mmr"&&(this.searchKwargs=e.searchKwargs)}static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}_vectorstoreType(){return this.vectorStore._vectorstoreType()}async _getRelevantDocuments(e,t){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},t==null?void 0:t.getChild("vectorstore"))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t==null?void 0:t.getChild("vectorstore"))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Dw=class extends kr{constructor(e,t){super(t);p(this,"lc_namespace",["langchain","vectorstores",this._vectorstoreType()]);p(this,"embeddings");this.embeddings=e}async delete(e){throw new Error("Not implemented.")}async similaritySearch(e,t=4,r=void 0,s=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)).map(i=>i[0])}async similaritySearchWithScore(e,t=4,r=void 0,s=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,r)}static fromTexts(e,t,r,s){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(e,t,r){throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(e,t,r,s,i,a){if(typeof e=="number")return new ch({vectorStore:this,k:e,filter:t,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 ch({...o,searchKwargs:e.searchKwargs}):new ch({...o})}}},l8=class extends Dw{static load(n,e){throw new Error("Not implemented")}},d8=class extends Is{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(n,e,t){var s;if((s=e==null?void 0:e.stop)!=null&&s.length)return{generations:[{message:new Ve(e.stop[0]),text:e.stop[0]}]};const r=n.map(i=>typeof i.content=="string"?i.content:JSON.stringify(i.content,null,2)).join(`
|
|
338
|
+
`);return await(t==null?void 0:t.handleLLMNewToken(r)),{generations:[{message:new Ve(r),text:r}],llmOutput:{}}}},h8=class UO extends Is{constructor({sleep:t=50,responses:r=[],chunks:s=[],toolStyle:i="openai",thrownErrorString:a,...o}){super(o);p(this,"sleep",50);p(this,"responses",[]);p(this,"chunks",[]);p(this,"toolStyle","openai");p(this,"thrownErrorString");p(this,"tools",[]);this.sleep=t,this.responses=r,this.chunks=s,this.toolStyle=i,this.thrownErrorString=a}_llmType(){return"fake"}bindTools(t){const r=[...this.tools,...t],s=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:At(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:At(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:At(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:At(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:s}]:s,a=new UO({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(t,r,s){var i,a,o,c;if(this.thrownErrorString)throw new Error(this.thrownErrorString);return{generations:[{text:"",message:new Ve({content:((a=(i=this.responses)==null?void 0:i[0])==null?void 0:a.content)??t[0].content??"",tool_calls:(c=(o=this.chunks)==null?void 0:o[0])==null?void 0:c.tool_calls})}]}}async*_streamResponseChunks(t,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 fr({message:new nt({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 Ve(typeof t[0].content=="string"?t[0].content:""),a=typeof i.content=="string"?i.content:"";for(const f of a){await new Promise(m=>setTimeout(m,this.sleep));const h=new fr({message:new nt({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}))}}},f8=class zO extends Is{constructor(t){super(t);p(this,"lc_serializable",!0);p(this,"responses");p(this,"i",0);p(this,"sleep");p(this,"emitCustomEvent",!1);p(this,"generationInfo");p(this,"tools",[]);p(this,"toolStyle","openai");const{responses:r,sleep:s,emitCustomEvent:i,generationInfo:a}=t;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(t,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(t){return{message:new Ve(t),text:t}}async*_streamResponseChunks(t,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(t=>{setTimeout(()=>t(),this.sleep)})}_createResponseChunk(t,r){return new fr({message:new nt({content:t}),text:t,generationInfo:r})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){const r=[...this.tools,...t],s=r.map(o=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:o.name,description:o.description,parameters:At(o.schema)}};case"anthropic":return{name:o.name,description:o.description,input_schema:At(o.schema)};case"bedrock":return{toolSpec:{name:o.name,description:o.description,inputSchema:At(o.schema)}};case"google":return{name:o.name,description:o.description,parameters:At(o.schema)};default:throw new Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle==="google"?[{functionDeclarations:s}]:s,a=new zO({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(t,r){return an.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")})}},p8=class extends fw{constructor(e){super(e??{});p(this,"vectorSize");this.vectorSize=(e==null?void 0:e.vectorSize)??4}async embedDocuments(e){return Promise.all(e.map(t=>this.embedQuery(t)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,"");const r=t.length%this.vectorSize,s=r===0?0:this.vectorSize-r,i=t.length+s;t=t.padEnd(i," ");const a=t.length/this.vectorSize,o=[];for(let c=0;c<t.length;c+=a)o.push(t.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})}},m8=class extends fw{constructor(n){super(n??{})}embedDocuments(n){return Promise.resolve(n.map(()=>[.1,.2,.3,.4]))}embedQuery(n){return Promise.resolve([.1,.2,.3,.4])}},g8=class extends Aw{constructor(e){super(e);p(this,"response");p(this,"thrownErrorString");this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e,t,r){if(this.thrownErrorString)throw new Error(this.thrownErrorString);const s=this.response??e;return await(r==null?void 0:r.handleLLMNewToken(s)),s}},_8=class extends Aw{constructor(e){super(e);p(this,"sleep",50);p(this,"responses");p(this,"thrownErrorString");this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return"fake"}async _call(e){var r,s;if(this.thrownErrorString)throw new Error(this.thrownErrorString);const t=(r=this.responses)==null?void 0:r[0];return this.responses=(s=this.responses)==null?void 0:s.slice(1),t??e}async*_streamResponseChunks(e,t,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))}},y8=class extends ux{constructor(){super();p(this,"lc_namespace",["langchain_core","message","fake"]);p(this,"messages",[])}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new Dn(e))}async addAIMessage(e){this.messages.push(new Ve(e))}async clear(){this.messages=[]}},w8=class extends hw{constructor(){super();p(this,"lc_namespace",["langchain_core","message","fake"]);p(this,"messages",[])}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},b8=class extends ei{constructor(){super();p(this,"name","fake_tracer");p(this,"runs",[])}persistRun(e){return this.runs.push(e),Promise.resolve()}},v8=class extends Tc{constructor(){super(...arguments);p(this,"lc_namespace",["tests","fake"])}getFormatInstructions(){return""}async parse(e){return e.split(",").map(t=>t.trim())}},S8=class extends Ow{constructor(e){super();p(this,"lc_namespace",["test","fake"]);p(this,"output",[new Oi({pageContent:"foo"}),new Oi({pageContent:"bar"})]);this.output=(e==null?void 0:e.output)??this.output}async _getRelevantDocuments(e){return this.output}},A8=class extends Ge{constructor(e){super(e);p(this,"lc_namespace",["tests","fake"]);p(this,"returnOptions");this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},T8=class extends gp{constructor(e){super(e);p(this,"name");p(this,"description");p(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},E8=class extends ei{constructor(){super();p(this,"runPromiseResolver");p(this,"runPromise");p(this,"name","single_run_extractor");this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},k8=class FO extends Dw{constructor(t,{similarity:r,...s}={}){super(t,s);p(this,"memoryVectors",[]);p(this,"similarity");this.similarity=r??$O}_vectorstoreType(){return"memory"}async addDocuments(t){const r=t.map(({pageContent:s})=>s);return this.addVectors(await this.embeddings.embedDocuments(r),t)}async addVectors(t,r){const s=t.map((i,a)=>({content:r[a].pageContent,embedding:i,metadata:r[a].metadata}));this.memoryVectors=this.memoryVectors.concat(s)}async similaritySearchVectorWithScore(t,r,s){const i=o=>s?s(new Oi({metadata:o.metadata,pageContent:o.content})):!0,a=this.memoryVectors.filter(i);return a.map((o,c)=>({similarity:this.similarity(t,o.embedding),index:c})).sort((o,c)=>o.similarity>c.similarity?-1:0).slice(0,r).map(o=>[new Oi({metadata:a[o.index].metadata,pageContent:a[o.index].content}),o.similarity])}static async fromTexts(t,r,s,i){const a=[];for(let o=0;o<t.length;o+=1){const c=Array.isArray(r)?r[o]:r,u=new Oi({pageContent:t[o],metadata:c});a.push(u)}return FO.fromDocuments(a,s,i)}static async fromDocuments(t,r,s){const i=new this(r,s);return await i.addDocuments(t),i}static async fromExistingIndex(t,r){return new this(t,r)}},I8=he({FakeChatMessageHistory:()=>y8,FakeChatModel:()=>d8,FakeEmbeddings:()=>m8,FakeLLM:()=>g8,FakeListChatMessageHistory:()=>w8,FakeListChatModel:()=>f8,FakeRetriever:()=>S8,FakeRunnable:()=>A8,FakeSplitIntoListParser:()=>v8,FakeStreamingChatModel:()=>h8,FakeStreamingLLM:()=>_8,FakeTool:()=>T8,FakeTracer:()=>b8,FakeVectorStore:()=>k8,SingleRunExtractor:()=>E8,SyntheticEmbeddings:()=>p8}),x8=he({agents:()=>D3,caches:()=>F3,callbacks__base:()=>wM,callbacks__manager:()=>qL,callbacks__promises:()=>VL,chat_history:()=>Z3,document_loaders__base:()=>G3,document_loaders__langsmith:()=>J3,documents:()=>q3,embeddings:()=>Q3,errors:()=>PP,example_selectors:()=>i6,index:()=>L3,indexing:()=>c6,language_models__base:()=>I6,language_models__chat_models:()=>i5,language_models__compat:()=>Y6,language_models__event:()=>o5,language_models__llms:()=>c5,language_models__profile:()=>u5,language_models__stream:()=>K6,language_models__structured_output:()=>Z6,load__serializable:()=>KP,memory:()=>l5,messages:()=>h3,messages__tool:()=>mN,output_parsers:()=>H6,output_parsers__openai_functions:()=>g5,output_parsers__openai_tools:()=>_5,outputs:()=>dD,prompt_values:()=>u6,prompts:()=>V5,retrievers:()=>W5,retrievers__document_compressors:()=>Z5,runnables:()=>p3,runnables__graph:()=>ZB,singletons:()=>YL,stores:()=>q5,structured_query:()=>t9,testing:()=>a9,tools:()=>TH,tracers__base:()=>CL,tracers__console:()=>RL,tracers__log_stream:()=>uD,tracers__run_collector:()=>xH,tracers__tracer_langchain:()=>DL,types__stream:()=>CH,utils__async_caller:()=>SD,utils__chunk_array:()=>$H,utils__context:()=>PH,utils__env:()=>yM,utils__event_source_parse:()=>LH,utils__format:()=>BH,utils__function_calling:()=>HH,utils__hash:()=>z3,utils__json_patch:()=>$6,utils__json_schema:()=>VB,utils__math:()=>WH,utils__ssrf:()=>QH,utils__standard_schema:()=>fB,utils__stream:()=>tD,utils__testing:()=>I8,utils__tiktoken:()=>E6,utils__types:()=>V6,utils__uuid:()=>dM,vectorstores:()=>u8});const O8=50;function C8(n){const e={};for(let t=n;t&&t.prototype;t=Object.getPrototypeOf(t))Object.assign(e,Reflect.get(t.prototype,"lc_aliases"));return Object.entries(e).reduce((t,[r,s])=>(t[s]=r,t),{})}async function uh(n){const{optionalImportsMap:e,optionalImportEntrypoints:t,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 n!="object"||n==null)return n;if(Array.isArray(n))return Promise.all(n.map((f,h)=>uh.call({...this,path:[...a,`${h}`],depth:o+1},f)));const l=n;if(nE(l))return yg(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=Bt(f);if(h)return h}throw new Error(`Missing secret "${f}" at ${u}`)}if("lc"in l&&"type"in l&&"id"in l&&l.lc===1&&l.type==="not_implemented"){const f=JSON.stringify(l);throw new Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${f}`)}if("lc"in l&&"type"in l&&"id"in l&&"kwargs"in l&&l.lc===1&&l.type==="constructor"){const f=l,h=JSON.stringify(f),[m,...g]=f.id.slice().reverse(),y=g.reverse(),b={langchain_core:x8,langchain:r};let _=null;const w=[y.join("/")];y[0]==="langchain_community"&&w.push(["langchain",...y.slice(1)].join("/"));const S=w.find(I=>I in e);if(j3.concat(t).includes(y.join("/"))||S)if(S!==void 0)_=await e[S];else throw new Error(`Missing key "${y.join("/")}" for ${u} in load(optionalImportsMap={})`);else{let I;if(y[0]==="langchain"||y[0]==="langchain_core")I=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 k;do{if(k=y.join("__"),k in I)break;y.pop()}while(y.length>0);k in I&&(_=I[k])}if(typeof _!="object"||_===null)throw new Error(`Invalid namespace: ${u} -> ${h}`);const T=_[m]??Object.values(_).find(I=>typeof I=="function"&&zf(I)===m);if(typeof T!="function")throw new Error(`Invalid identifer: ${u} -> ${h}`);const A=new T(eE(await uh.call({...this,path:[...a,"kwargs"],depth:o+1},f.kwargs),FP,C8(T)));return Object.defineProperty(A.constructor,"name",{value:m}),A}const d={};for(const[f,h]of Object.entries(l))d[f]=await uh.call({...this,path:[...a,f],depth:o+1},h);return d}async function $8(n,e){const t=JSON.parse(n),r={optionalImportsMap:{},optionalImportEntrypoints:[],secretsMap:{},secretsFromEnv:!1,importMap:{},path:["$"],depth:0,maxDepth:O8};return uh.call(r,t)}function R8(n){return n!==null&&n.lc===1&&n.type==="constructor"&&Array.isArray(n.id)}async function S_(n){if(n&&typeof n=="object"){if(Array.isArray(n))return await Promise.all(n.map(e=>S_(e)));{const e={};for(const[t,r]of Object.entries(n))e[t]=await S_(r);if(e.lc===2&&e.type==="undefined")return;if(e.lc===2&&e.type==="delta_snapshot")return new lw(e.value);if(e.lc===2&&e.type==="constructor"&&Array.isArray(e.id))try{const t=e.id[e.id.length-1];let r;switch(t){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(R8(e))return $8(JSON.stringify(e));return e}}return n}function bd(n,e,t,r){return{lc:2,type:"constructor",id:[n.name],method:e??null,args:t??[],kwargs:r??{}}}function P8(n){return n===void 0?{lc:2,type:"undefined"}:n instanceof lw?{lc:2,type:"delta_snapshot",value:n.value}:n instanceof Set||n instanceof Map?bd(n.constructor,void 0,[Array.from(n)]):n instanceof RegExp?bd(RegExp,void 0,[n.source,n.flags]):n instanceof Error?bd(n.constructor,void 0,[n.message]):(n==null?void 0:n.lg_name)==="Send"?{node:n.node,args:n.args,...n.timeout!==void 0?{timeout:n.timeout}:{}}:n instanceof Uint8Array?bd(Uint8Array,"from",[Array.from(n)]):n}var N8=class{_dumps(n){return new TextEncoder().encode(N3(n,(e,t)=>P8(t)))}async dumpsTyped(n){return n instanceof Uint8Array?["bytes",n]:["json",this._dumps(n)]}async _loads(n){return S_(JSON.parse(n))}async loadsTyped(n,e){if(n==="bytes")return typeof e=="string"?new TextEncoder().encode(e):e;if(n==="json")return this._loads(typeof e=="string"?e:new TextDecoder().decode(e));throw new Error(`Unknown serialization type: ${n}`)}};function BO(n){if(typeof n!="object"||n===null)return n;const e=Array.isArray(n)?[]:{};for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=BO(n[t]));return e}function A_(){return{v:4,id:sx(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function lf(n){return{v:n.v,id:n.id,ts:n.ts,channel_values:{...n.channel_values},channel_versions:{...n.channel_versions},versions_seen:BO(n.versions_seen)}}function HO(n,e){return typeof n=="number"&&typeof e=="number"?Math.sign(n-e):String(n).localeCompare(String(e))}function M8(...n){return n.reduce((e,t,r)=>r===0?t:HO(e,t)>=0?e:t)}const j8={[O3]:-1,[sh]:-2,[C3]:-3,[$3]:-4};var Nc=class extends Error{constructor(n){super(n),this.name="InvalidNamespaceError"}};function L8(n){if(n.length===0)throw new Nc("Namespace cannot be empty.");for(const e of n){if(typeof e!="string")throw new Nc(`Invalid namespace label '${e}' found in ${n}. Namespace labels must be strings, but got ${typeof e}.`);if(e.includes("."))throw new Nc(`Invalid namespace label '${e}' found in ${n}. Namespace labels cannot contain periods ('.').`);if(e==="")throw new Nc(`Namespace labels cannot be empty strings. Got ${e} in ${n}`)}if(n[0]==="langgraph")throw new Nc(`Root label for namespace cannot be "langgraph". Got: ${n}`)}var D8=class{async get(n,e){return(await this.batch([{namespace:n,key:e}]))[0]}async search(n,e={}){const{filter:t,limit:r=10,offset:s=0,query:i}=e;return(await this.batch([{namespacePrefix:n,filter:t,limit:r,offset:s,query:i}]))[0]}async put(n,e,t,r){L8(n),await this.batch([{namespace:n,key:e,value:t,index:r}])}async delete(n,e){await this.batch([{namespace:n,key:e,value:null}])}async listNamespaces(n={}){const{prefix:e,suffix:t,maxDepth:r,limit:s=100,offset:i=0}=n,a=[];return e&&a.push({matchType:"prefix",path:e}),t&&a.push({matchType:"suffix",path:t}),(await this.batch([{matchConditions:a.length?a:void 0,maxDepth:r,limit:s,offset:i}]))[0]}start(){}stop(){}};const U8=n=>"lg_name"in n&&n.lg_name==="AsyncBatchedStore"?n.store:n;var z8=class extends D8{constructor(e){super();p(this,"lg_name","AsyncBatchedStore");p(this,"store");p(this,"queue",new Map);p(this,"nextKey",0);p(this,"running",!1);p(this,"processingTask",null);this.store=U8(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,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){const{filter:r,limit:s=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:r,limit:s,offset:i,query:a})}async put(e,t,r){return this.enqueueOperation({namespace:e,key:t,value:r})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,r)=>{const s=this.nextKey;this.nextKey+=1,this.queue.set(s,{operation:e,resolve:t,reject:r})})}async processBatchQueue(){for(;this.running;){if(await new Promise(t=>{setTimeout(t,0)}),this.queue.size===0)continue;const e=new Map(this.queue);this.queue.clear();try{const t=Array.from(e.values()).map(({operation:s})=>s),r=await this.store.batch(t);e.forEach(({resolve:s},i)=>{s(r[Array.from(e.keys()).indexOf(i)])})}catch(t){e.forEach(({reject:r})=>{r(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}},F8=class{constructor(n){p(this,"serde",new N8);this.serde=n||this.serde}};function vi(n){return n!=null&&n.lc_graph_name==="DeltaChannel"}function VO(n){return n!=null&&n.lg_is_channel===!0}var Hi=class{constructor(){p(this,"ValueType");p(this,"UpdateType");p(this,"lg_is_channel",!0)}consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(n){if(n.name===on.unminifiable_name)return!1;throw n}}equals(n){return this===n}};const T_=Symbol.for("LG_IS_ONLY_BASE_CHANNEL");function wp(n){if(n[T_]===!0)return n;const e={};for(const t in n){if(!Object.prototype.hasOwnProperty.call(n,t))continue;const r=n[t];VO(r)&&(e[t]=r)}return Object.assign(e,{[T_]:!0}),e}function ZO(n,e){const t=wp(n),r={};for(const s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;const i=e.channel_values[s];r[s]=t[s].fromCheckpoint(i)}return Object.assign(r,{[T_]:!0}),r}function gS(n,e){const t=new Set,r=m3();for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const i=n[s];if(!vi(i)||!i.isAvailable())continue;const[a,o]=e[s]??[0,0];(a>=i.snapshotFrequency||o>=r)&&t.add(s)}return t}function sa(n,e,t,r){const s=(r==null?void 0:r.channelsToSnapshot)??new Set,{updatedChannels:i,getNextVersion:a}=r??{};let o,c=n.channel_versions;if(e===void 0)o=n.channel_values;else{o={},c={...n.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 lw(l.get());continue}if(!vi(l))try{o[u]=l.checkpoint()}catch(d){if(d.name!==on.unminifiable_name)throw d}}}return{v:4,id:(r==null?void 0:r.id)??sx(t),ts:new Date().toISOString(),channel_values:o,channel_versions:c,versions_seen:n.versions_seen}}async function E_(n,e,t){const r=ZO(n,e),{saver:s,config:i}=t??{},a=wp(n),o=[];for(const u in a)Object.prototype.hasOwnProperty.call(a,u)&&vi(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 bp=class KO extends Hi{constructor(t){super();p(this,"lc_graph_name","LastValue");p(this,"value",[]);this.initialValueFactory=t,t&&(this.value=[t()])}fromCheckpoint(t){const r=new KO(this.initialValueFactory);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0)return!1;if(t.length!==1)throw new vt("LastValue can only receive one value per step.",{lc_error_code:"INVALID_CONCURRENT_GRAPH_UPDATE"});return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new on;return this.value[0]}checkpoint(){if(this.value.length===0)throw new on;return this.value[0]}isAvailable(){return this.value.length!==0}},B8=class WO extends Hi{constructor(){super(...arguments);p(this,"lc_graph_name","LastValueAfterFinish");p(this,"value",[]);p(this,"finished",!1)}fromCheckpoint(t){const r=new WO;if(typeof t<"u"){const[s,i]=t;r.value=[s],r.finished=i}return r}update(t){return t.length===0?!1:(this.finished=!1,this.value=[t[t.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new on;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 H8=n=>n!=null&&n.lc_graph_name==="BinaryOperatorAggregate";var df=class qO extends Hi{constructor(t,r){super();p(this,"lc_graph_name","BinaryOperatorAggregate");p(this,"value");p(this,"operator");p(this,"initialValueFactory");this.operator=t,this.initialValueFactory=r,this.value=r==null?void 0:r()}fromCheckpoint(t){const r=new qO(this.operator,this.initialValueFactory);return typeof t<"u"&&(r.value=t),r}update(t){let r=t;if(!r.length)return!1;if(this.value===void 0){const i=r[0],[a,o]=Xu(i);a?this.value=o:this.value=i,r=r.slice(1)}let s=!1;for(const i of r)if(S3(i)){if(s)throw new vt("Can receive only one Overwrite value per step.");const[,a]=Xu(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 on;return this.value}checkpoint(){if(this.value===void 0)throw new on;return this.value}isAvailable(){return this.value!==void 0}equals(t){return this===t?!0:H8(t)?this.operator===t.operator:!1}},k_=class{constructor(n){p(this,"lc_graph_name","AnnotationRoot");p(this,"spec");this.spec=n}static isInstance(n){return typeof n=="object"&&n!==null&&"lc_graph_name"in n&&n.lc_graph_name==="AnnotationRoot"}};const Aa=function(n){return n?I_(n):new bp};Aa.Root=n=>new k_(n);function I_(n){return typeof n=="object"&&n&&"reducer"in n&&n.reducer?new df(n.reducer,n.default):typeof n=="object"&&n&&"value"in n&&n.value?new df(n.value,n.default):new bp}const V8=["tags","metadata","callbacks","configurable"],Z8=["tags","metadata","callbacks","runName","maxConcurrency","recursionLimit","configurable","runId","outputKeys","streamMode","store","writer","interrupt","context","interruptBefore","interruptAfter","checkpointDuring","durability","signal","heartbeat","executionInfo","serverInfo","control"],K8=25,W8=new Set(["thread_id","checkpoint_id","checkpoint_ns","task_id","run_id","assistant_id","graph_id"]);function q8(n,e){if(!n)return e;const t=e??{};for(const r of W8){if(r in t)continue;const s=n[r];s!==void 0&&(t[r]=s)}return t}function GO(...n){const e={tags:[],metadata:{},callbacks:void 0,recursionLimit:K8,configurable:{}},t=yn.getRunnableConfig();if(t!==void 0){for(const[r,s]of Object.entries(t))if(s!==void 0)if(V8.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 n)if(r!==void 0)for(const[s,i]of Object.entries(r))i!==void 0&&Z8.includes(s)&&(e[s]=i);return e.metadata=q8(e.configurable,e.metadata)??{},e}function G8(){return yn.getRunnableConfig()}function Tm(n){return n.split("|").filter(e=>!e.match(/^\d+$/)).map(e=>e.split(":")[0]).join("|")}function J8(n){const e=n.split("|");for(;e.length>1&&e[e.length-1].match(/^\d+$/);)e.pop();return e.slice(0,-1).join("|")}var vs=class extends Ge{constructor(e){super();p(this,"lc_namespace",["langgraph"]);p(this,"func");p(this,"tags");p(this,"config");p(this,"trace",!0);p(this,"recurse",!0);this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,r){return new Promise((s,i)=>{const a=ut(t,{callbacks:r==null?void 0:r.getChild()});yn.runWithConfig(a,async()=>{try{s(await this.func(e,a))}catch(o){i(o)}})})}async invoke(e,t){let r;const s=GO(t),i=or(this.config,s);return this.trace?r=await this._callWithConfig(this._tracedInvoke,e,i):r=await yn.runWithConfig(i,async()=>this.func(e,i)),Ge.isRunnable(r)&&this.recurse?await yn.runWithConfig(i,async()=>r.invoke(e,i)):r}};function*xs(n,e){if(e===void 0)yield*n;else for(const t of n)yield[e,t]}async function gi(n){const e=[];for await(const t of await n)e.push(t);return e}function ao(n){const e=[];for(const t of n)e.push(t);return e}function Va(n,e){return n?"configurable"in n?{...n,configurable:{...n.configurable,...e}}:{...n,configurable:e}:{configurable:e}}function Y8(n){return typeof n=="object"&&(n==null?void 0:n[Symbol.for("LG_SKIP_WRITE")])!==void 0}const Ta={[Symbol.for("LG_PASSTHROUGH")]:!0};function vd(n){return typeof n=="object"&&(n==null?void 0:n[Symbol.for("LG_PASSTHROUGH")])!==void 0}const Em=Symbol("IS_WRITER");var Ln=class x_ extends vs{constructor(t,r){const s=`ChannelWrite<${t.map(i=>Gn(i)?i.node:"channel"in i?i.channel:"...").join(",")}>`;super({writes:t,name:s,tags:r,trace:!1,func:async(i,a)=>this._write(i,a??{})});p(this,"writes");this.writes=t}async _write(t,r){const s=this.writes.map(i=>km(i)&&vd(i.value)?{mapper:i.mapper,value:t}:lh(i)&&vd(i.value)?{channel:i.channel,value:t,skipNone:i.skipNone,mapper:i.mapper}:i);return await x_.doWrite(r,s),t}static async doWrite(t,r){var a;for(const o of r){if(lh(o)){if(o.channel==="__pregel_tasks")throw new vt("Cannot write to the reserved channel TASKS");if(vd(o.value))throw new vt("PASSTHROUGH value must be replaced")}if(km(o)&&vd(o.value))throw new vt("PASSTHROUGH value must be replaced")}const s=[];for(const o of r)if(Gn(o))s.push([cc,o]);else if(km(o)){const c=await o.mapper.invoke(o.value,t);c!=null&&c.length>0&&s.push(...c)}else if(lh(o)){const c=o.mapper!==void 0?await o.mapper.invoke(o.value,t):o.value;if(Y8(c)||o.skipNone&&c===void 0)continue;s.push([o.channel,c])}else throw new Error(`Invalid write entry: ${JSON.stringify(o)}`);((a=t.configurable)==null?void 0:a[Jr])(s)}static isWriter(t){return t instanceof x_||Em in t&&!!t[Em]}static registerWriter(t){return Object.defineProperty(t,Em,{value:!0})}};function lh(n){return n!==void 0&&typeof n.channel=="string"}function km(n){return n!==void 0&&!lh(n)&&Ge.isRunnable(n.mapper)}var X8=class JO extends vs{constructor(t,r,s=!1){super({trace:!1,func:(i,a)=>JO.doRead(a,this.channel,this.fresh,this.mapper)});p(this,"lc_graph_name","ChannelRead");p(this,"channel");p(this,"fresh",!1);p(this,"mapper");this.fresh=s,this.mapper=r,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(",")}>`:`ChannelRead<${t}>`}static doRead(t,r,s,i){var o;const a=(o=t.configurable)==null?void 0:o[xi];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 Za=new Yu;var il=class uu extends mn{constructor(t){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:m,ends:g,isErrorHandler:y,errorHandlerNode:b}=t,_=[...(w=t.config)!=null&&w.tags?t.config.tags:[],...h??[]];super({...t,bound:t.bound??Za,config:{...t.config?t.config:{},tags:_}});p(this,"lc_graph_name","PregelNode");p(this,"channels");p(this,"triggers",[]);p(this,"mapper");p(this,"writers",[]);p(this,"bound",Za);p(this,"kwargs",{});p(this,"metadata",{});p(this,"tags",[]);p(this,"retryPolicy");p(this,"cachePolicy");p(this,"timeout");p(this,"subgraphs");p(this,"ends");p(this,"isErrorHandler");p(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=m,this.ends=g,this.isErrorHandler=y,this.errorHandlerNode=b}getWriters(){var r;const t=[...this.writers];for(;t.length>1&&t[t.length-1]instanceof Ln&&t[t.length-2]instanceof Ln;){const s=t.slice(-2),i=s[0].writes.concat(s[1].writes);t[t.length-2]=new Ln(i,(r=s[0].config)==null?void 0:r.tags),t.pop()}return t}getNode(){const t=this.getWriters();if(!(this.bound===Za&&t.length===0))return this.bound===Za&&t.length===1?t[0]:this.bound===Za?new pr({first:t[0],middle:t.slice(1,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):t.length>0?new pr({first:this.bound,middle:t.slice(0,t.length-1),last:t[t.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))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 uu({channels:{...this.channels,...Object.fromEntries(t.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(t){return Ln.isWriter(t)?new uu({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===Za?new uu({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:gn(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new uu({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function Uw(n){const e=typeof n[hn];if(e==="number")return 0;if(e==="string")return"";for(const t in n){if(!Object.prototype.hasOwnProperty.call(n,t))continue;const r=typeof n[t];if(r==="number")return 0;if(r==="string")return"";break}}function dh(n,e){if(Object.keys(n).length>0){const t=Uw(e);return Object.fromEntries(Object.entries(e).filter(([r,s])=>s>(n[r]??t)))}else return e}function Q8(n,e){return n&&!Array.isArray(n)&&!(n instanceof Date)&&typeof n=="object"?n:{[e]:n}}function Mn(n,e){return n===null?{configurable:e}:(n==null?void 0:n.configurable)===void 0?{...n,configurable:e}:{...n,configurable:{...n.configurable,...e}}}function Ki(n,e){var r,s;const t=(e==null?void 0:e.parents)??{};return Object.keys(t).length>0?Mn(n,{[ar]:{...t,[((r=n.configurable)==null?void 0:r.checkpoint_ns)??""]:(s=n.configurable)==null?void 0:s.checkpoint_id}}):n}function al(...n){const e=[...new Set(n.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 t=new AbortController,r=()=>{var a;const i=(a=e.find(o=>o.aborted))==null?void 0:a.reason;t.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&&t.abort(s.reason),{signal:t.signal,dispose:()=>{e.forEach(i=>i.removeEventListener("abort",r))}}}const eV=(n,e)=>{if(!(!n&&!e))return n?e?Array.isArray(n)&&Array.isArray(e)?[...n,...e]:Array.isArray(n)?[...n,e]:Array.isArray(e)?[n,...e]:[n,e]:n:e};function tV(n){return"steps"in n&&Array.isArray(n.steps)}function zw(n){return"lg_is_pregel"in n&&n.lg_is_pregel===!0}function YO(n){const e=[n];for(const t of e){if(zw(t))return t;tV(t)&&e.push(...t.steps)}}var dc=class XO extends Hi{constructor(t=!0){super();p(this,"lc_graph_name","EphemeralValue");p(this,"guard");p(this,"value",[]);this.guard=t}fromCheckpoint(t){const r=new XO(this.guard);return typeof t<"u"&&(r.value=[t]),r}update(t){if(t.length===0){const r=this.value.length>0;return this.value=[],r}if(t.length!==1&&this.guard)throw new vt("EphemeralValue can only receive one value per step.");return this.value=[t[t.length-1]],!0}get(){if(this.value.length===0)throw new on;return this.value[0]}checkpoint(){if(this.value.length===0)throw new on;return this.value[0]}isAvailable(){return this.value.length!==0}},No,zT,nV=(zT=class{constructor(){et(this,No)}requestDrain(n="shutdown"){_t(this,No,n)}get drainRequested(){return re(this,No)!==void 0}get drainReason(){return re(this,No)}},No=new WeakMap,zT);const q=n=>BigInt(n),mt=(n,e=0)=>new DataView(n.buffer,n.byteOffset+e,n.byteLength-e),QO=q("0x9E3779B1"),eC=q("0x85EBCA77"),rV=q("0xC2B2AE3D"),Di=q("0x9E3779B185EBCA87"),$a=q("0xC2B2AE3D27D4EB4F"),tC=q("0x165667B19E3779F9"),Fw=q("0x85EBCA77C2B2AE63"),sV=q("0x27D4EB2F165667C5"),iV=q("0x165667919E3779F9"),aV=q("0x9FB21C651E98DF25"),oV=n=>{const e=n.length;if(e%2!==0)throw new Error("String should have an even number of characters");const t=e/2,r=new Uint8Array(t);let s=0,i=0;for(;i<t;){const a=n.slice(s,s+=2);r[i]=Number.parseInt(a,16),i+=1}return mt(r)},os=oV("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),$o=(q(1)<<q(128))-q(1),He=(q(1)<<q(64))-q(1),hf=(q(1)<<q(32))-q(1),Us=64,nC=Us/8,cV=8,Sd=4;function hc(n){if(!n)throw new Error("Assert failed")}function uV(n){const e=new DataView(new ArrayBuffer(8));return e.setBigUint64(0,n,!0),e.getBigUint64(0,!1)}function lV(n){let e=n;return e=(e&q(65535))<<q(16)|(e&q(4294901760))>>q(16),e=(e&q(16711935))<<q(8)|(e&q(4278255360))>>q(8),e}function dV(n,e){return(n&hf)*(e&hf)&He}function hV(n,e){return(n<<e|n>>q(32)-e)&hf}function rC(n,e,t){for(let r=0;r<nC;r+=1){const s=e.getBigUint64(r*8,!0),i=s^t.getBigUint64(r*8,!0);n[r^1]+=s,n[r]+=dV(i,i>>q(32))}return n}function _S(n,e,t,r){for(let s=0;s<r;s+=1)rC(n,mt(e,s*Us),mt(t,s*8));return n}function fV(n,e){for(let t=0;t<nC;t+=1){const r=e.getBigUint64(t*8,!0);let s=n[t];s=O_(s,q(47)),s^=r,s*=QO,n[t]=s&He}return n}function Ad(n,e){return sC(n[0]^e.getBigUint64(0,!0),n[1]^e.getBigUint64(cV,!0))}function yS(n,e,t){let r=t;return r+=Ad(n.slice(0),mt(e,0*Sd)),r+=Ad(n.slice(2),mt(e,4*Sd)),r+=Ad(n.slice(4),mt(e,8*Sd)),r+=Ad(n.slice(6),mt(e,12*Sd)),ms(r&He)}function pV(n,e,t,r,s){let i=n;const a=Math.floor((t.byteLength-Us)/8),o=Us*a,c=Math.floor((e.byteLength-1)/o);for(let u=0;u<c;u+=1)i=_S(i,mt(e,u*o),t,a),i=s(i,mt(t,t.byteLength-Us));{const u=Math.floor((e.byteLength-1-o*c)/Us);i=_S(i,mt(e,c*o),t,u),i=r(i,mt(e,e.byteLength-Us),mt(t,t.byteLength-Us-7))}return i}function mV(n,e){let t=new BigUint64Array([rV,Di,$a,tC,Fw,eC,sV,QO]);hc(n.byteLength>128),t=pV(t,n,e,rC,fV),hc(t.length*8===64);{const r=yS(t,mt(e,11),q(n.byteLength)*Di&He);return yS(t,mt(e,e.byteLength-Us-11),~(q(n.byteLength)*$a)&He)<<q(64)|r}}function sC(n,e){const t=n*e&$o;return t&He^t>>q(64)}function wS(n,e,t){return sC((n.getBigUint64(0,!0)^e.getBigUint64(0,!0)+t)&He,(n.getBigUint64(8,!0)^e.getBigUint64(8,!0)-t)&He)}function hh(n,e,t,r,s){let i=n&He,a=n>>q(64)&He;return i+=wS(e,r,s),i^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),i&=He,a+=wS(t,mt(r,16),s),a^=e.getBigUint64(0,!0)+e.getBigUint64(8,!0),a&=He,a<<q(64)|i}function ms(n){let e=n;return e^=e>>q(37),e*=iV,e&=He,e^=e>>q(32),e}function ff(n){let e=n;return e^=e>>q(33),e*=$a,e&=He,e^=e>>q(29),e*=tC,e&=He,e^=e>>q(32),e}function gV(n,e,t){const r=n.byteLength;hc(r>0&&r<=3);const s=q(n.getUint8(r-1))|q(r<<8)|q(n.getUint8(0)<<16)|q(n.getUint8(r>>1)<<24),i=(s^(q(e.getUint32(0,!0))^q(e.getUint32(4,!0)))+t)&He,a=(q(e.getUint32(8,!0))^q(e.getUint32(12,!0)))-t;return(ff((hV(lV(s),q(13))^a)&He)&He)<<q(64)|ff(i)}function O_(n,e){return n^n>>e}function _V(n,e,t){const r=n.byteLength;hc(r>=4&&r<=8);{const s=n.getUint32(0,!0),i=n.getUint32(r-4,!0);let a=((q(s)|q(i)<<q(32))^(e.getBigUint64(16,!0)^e.getBigUint64(24,!0))+t&He)*(Di+(q(r)<<q(2)))&$o;return a+=(a&He)<<q(65),a&=$o,a^=a>>q(67),O_(O_(a&He,q(35))*aV&He,q(28))|ms(a>>q(64))<<q(64)}}function yV(n,e,t){const r=n.byteLength;hc(r>=9&&r<=16);{const s=(e.getBigUint64(32,!0)^e.getBigUint64(40,!0))+t&He,i=(e.getBigUint64(48,!0)^e.getBigUint64(56,!0))-t&He,a=n.getBigUint64(0,!0);let o=n.getBigUint64(r-8,!0),c=(a^o^s)*Di;const u=(c&He)+(q(r-1)<<q(54));c=c&($o^He)|u,o^=i,c+=o+(o&hf)*(eC-q(1))<<q(64),c&=$o,c^=uV(c>>q(64));let l=(c&He)*$a;return l+=(c>>q(64))*$a<<q(64),l&=$o,ms(l&He)|ms(l>>q(64))<<q(64)}}function wV(n,e){const t=n.byteLength;return hc(t<=16),t>8?yV(n,os,e):t>=4?_V(n,os,e):t>0?gV(n,os,e):ff(e^os.getBigUint64(64,!0)^os.getBigUint64(72,!0))|ff(e^os.getBigUint64(80,!0)^os.getBigUint64(88,!0))<<q(64)}function C_(n){return~n+q(1)&He}function bV(n,e,t){let r=q(n.byteLength)*Di&He,s=q(n.byteLength-1)/q(32);for(;s>=0;){const o=Number(s);r=hh(r,mt(n,16*o),mt(n,n.byteLength-16*(o+1)),mt(e,32*o),t),s-=q(1)}let i=r+(r>>q(64))&He;i=ms(i);let a=(r&He)*Di+(r>>q(64))*Fw+(q(n.byteLength)-t&He)*$a;return a&=He,a=C_(ms(a)),i|a<<q(64)}function vV(n,e,t){let r=q(n.byteLength)*Di&He;for(let a=32;a<160;a+=32)r=hh(r,mt(n,a-32),mt(n,a-16),mt(e,a-32),t);r=ms(r&He)|ms(r>>q(64))<<q(64);for(let a=160;a<=n.byteLength;a+=32)r=hh(r,mt(n,a-32),mt(n,a-16),mt(e,3+a-160),t);r=hh(r,mt(n,n.byteLength-16),mt(n,n.byteLength-32),mt(e,103),C_(t));let s=r+(r>>q(64))&He;s=ms(s);let i=(r&He)*Di+(r>>q(64))*Fw+(q(n.byteLength)-t&He)*$a;return i&=He,i=C_(ms(i)),s|i<<q(64)}function hi(n,e=q(0)){const t=new TextEncoder,r=mt(typeof n=="string"?t.encode(n):n),s=r.byteLength,i=a=>a.toString(16).padStart(32,"0");return s<=16?i(wV(r,e)):s<=128?i(bV(r,os,e)):s<=240?i(vV(r,os,e)):i(mV(r,os))}function iC(n){return/^[0-9a-f]{32}$/.test(n)}function Ro(n,e,t=!0,r=!1){try{return n[e].get()}catch(s){if(s.name===on.unminifiable_name){if(r)return s;if(t)return null}throw s}}function Ra(n,e,t=!0){if(Array.isArray(e)){const r={};for(const s of e)try{r[s]=Ro(n,s,!t)}catch(i){if(i.name===on.unminifiable_name)continue}return r}else return Ro(n,e)}function*SV(n,e){if(n.graph===cr.PARENT)throw new vt("There is no parent graph.");if(n.goto){let t;Array.isArray(n.goto)?t=n.goto:t=[n.goto];for(const r of t)if(Gn(r))yield[Tr,cc,r];else if(typeof r=="string")yield[Tr,`branch:to:${r}`,"__start__"];else throw new Error(`In Command.send, expected Send or string, got ${typeof r}`)}if(n.resume)if(typeof n.resume=="object"&&Object.keys(n.resume).length&&Object.keys(n.resume).every(iC))for(const[t,r]of Object.entries(n.resume)){const s=e.filter(i=>i[0]===t&&i[1]==="__resume__").map(i=>i[2]).slice(0,1)??[];s.push(r),yield[t,bs,s]}else yield[Tr,bs,n.resume];if(n.update){if(typeof n.update!="object"||!n.update)throw new Error("Expected cmd.update to be a dict mapping channel names to update values");if(Array.isArray(n.update))for(const[t,r]of n.update)yield[Tr,t,r];else for(const[t,r]of Object.entries(n.update))yield[Tr,t,r]}}function*aC(n,e){if(e!=null)if(Array.isArray(n)&&typeof e=="object"&&!Array.isArray(e))for(const t in e)n.includes(t)&&(yield[t,e[t]]);else{if(Array.isArray(n))throw new Error('Input chunk must be an object when "inputChannels" is an array');yield[n,e]}}function*Im(n,e,t){Array.isArray(n)?(e===!0||e.find(([r,s])=>n.includes(r)))&&(yield Ra(t,n)):(e===!0||e.some(([r,s])=>r===n))&&(yield Ro(t,n))}function*AV(n,e,t){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===op).map(([c,u])=>[o.name,u])):Array.isArray(n)?s=r.flatMap(([o])=>{const{writes:c}=o,u={};for(const[l]of c)n.includes(l)&&(u[l]=(u[l]||0)+1);return Object.values(u).some(l=>l>1)?c.filter(([l])=>n.includes(l)).map(([l,d])=>[o.name,{[l]:d}]):[[o.name,Object.fromEntries(c.filter(([l])=>n.includes(l)))]]}):s=r.flatMap(([o])=>o.writes.filter(([c,u])=>c===n).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];t&&(a.__metadata__={cached:t}),yield a}var TV=class{constructor({func:n,name:e,input:t,retry:r,cache:s,timeout:i,callbacks:a}){p(this,"func");p(this,"name");p(this,"input");p(this,"retry");p(this,"cache");p(this,"timeout");p(this,"callbacks");p(this,"__lg_type","call");this.func=n,this.name=e,this.input=t,this.retry=r,this.cache=s,this.timeout=i,this.callbacks=a}};function EV(n){return typeof n=="object"&&n!==null&&"__lg_type"in n&&n.__lg_type==="call"}function kV(n,e){return new pr({name:n,first:new vs({func:t=>e(...t),name:n,trace:!1,recurse:!1}),last:new Ln([{channel:op,value:Ta}],[Kn])})}const IV=n=>n!==void 0?n+1:1;function xV(n,e){if(e==null)return!1;for(const t of n)if(e[t])return!0;return!1}function OV(n){let e;for(const t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e==null?e=n[t]:e=M8(e,n[t]));return e}function Td(n,e,t){const r=Uw(n.channel_versions),s=n.versions_seen.__interrupt__??{};let i=!1;if((n.channel_versions.__start__??r)>(s.__start__??r))i=!0;else for(const o in n.channel_versions)if(Object.prototype.hasOwnProperty.call(n.channel_versions,o)&&n.channel_versions[o]>(s[o]??r)){i=!0;break}const a=t.some(o=>{var c,u;return e==="*"?!((u=(c=o.config)==null?void 0:c.tags)!=null&&u.includes(Kn)):e.includes(o.name)});return i&&a}function Mu(n,e,t,r,s=!1){let i=new Set;if(Array.isArray(r))i=new Set(r.filter(o=>t.writes.some(([c,u])=>c===o)));else{for(const[o]of t.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];vi(f)&&f.isAvailable()&&c.add(d)}const u=sa(n,o,-1,{channelsToSnapshot:c}),l=ZO(o,u);sr(lf(u),l,[t],void 0,void 0),a=Ra({...e,...l},r)}else a=Ra(e,r);return a}function fh(n,e,t){for(const[r,s]of t)if(["__pregel_push","__pregel_tasks"].includes(r)&&s!=null){if(!Gn(s))throw new vt(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(s)}`);if(!(s.node in e))throw new vt(`Invalid node name "${s.node}" in Send packet`)}n(t)}const CV=new Set([aw,Er,bs,Ft,op,jl,sw]),$V=new Set(b3);function sr(n,e,t,r,s){var h,m,g;const i=new Map;for(const y of t)i.set(y,((h=y.path)==null?void 0:h.slice(0,3))||[]);t.sort((y,b)=>{const _=i.get(y),w=i.get(b);for(let S=0;S<Math.min(_.length,w.length);S+=1){if(_[S]<w[S])return-1;if(_[S]>w[S])return 1}return _.length-w.length});const a=wp(e);let o=!1;const c=new Set;for(const y of t){y.triggers.length>0&&(o=!0),(m=n.versions_seen)[g=y.name]??(m[g]={});for(const b of y.triggers)b in n.channel_versions&&(n.versions_seen[y.name][b]=n.channel_versions[b]),$V.has(b)||c.add(b)}let u=OV(n.channel_versions),l=!1;for(const y of c)y in a&&a[y].consume()&&r!==void 0&&(n.channel_versions[y]=r(u),l=!0);const d={};for(const y of t)for(const[b,_]of y.writes)CV.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(S){if(S.name===vt.unminifiable_name){const T=new vt(`Invalid update for channel "${y}" with values ${JSON.stringify(b)}: ${S.message}`);throw T.lc_error_code=S.lc_error_code,T}else throw S}w&&r!==void 0&&(n.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&&(n.channel_versions[y]=r(u),b.isAvailable()&&f.add(y))}if(o&&!xV(f,s))for(const y in a){if(!Object.prototype.hasOwnProperty.call(a,y))continue;const b=a[y];b.finish()&&r!==void 0&&(n.channel_versions[y]=r(u),b.isAvailable()&&f.add(y))}return f}function*RV(n,e,t){if(t.updatedChannels!=null&&t.triggerToNodes!=null){const r=new Set;for(const s of t.updatedChannels){const i=t.triggerToNodes[s];for(const a of i??[])r.add(a)}yield*[...r].sort();return}if(!(()=>{for(const r in n.channel_versions)if(n.channel_versions[r]!==null)return!1;return!0})())for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(yield r)}function PV(n){let e;const t=new Map,r=new Set;if(n)for(const[s,i,a]of n){if(s==="00000000-0000-0000-0000-000000000000"&&i==="__resume__"&&e===void 0&&(e=a),i==="__resume__"&&s!=="00000000-0000-0000-0000-000000000000"){let o=t.get(s);o||(o=[],t.set(s,o)),o.push(a)}i!=="__error__"&&r.add(s)}return{nullResume:e,resumeByTaskId:t,successfulWriteTaskIds:r}}function vo(n,e,t,r,s,i,a){const o={},c=a.pendingWritesIndex?a:{...a,pendingWritesIndex:PV(e)},u=r[cc];if(u!=null&&u.isAvailable()){const l=u.get().length;for(let d=0;d<l;d+=1){const f=$_([Er,d],n,e,t,r,s,i,c);f!==void 0&&(o[f.id]=f)}}for(const l of RV(n,t,c)){const d=$_([i_,l],n,e,t,r,s,i,c);d!==void 0&&(o[d.id]=d)}return o}function $_(n,e,t,r,s,i,a,o){var h,m,g,y;const{step:c,checkpointer:u,manager:l}=o,d=i.configurable??{},f=d.checkpoint_ns??"";if(n[0]==="__pregel_push"&&EV(n[n.length-1])){const b=n[n.length-1],_=kV(b.name,b.func),w=[Er],S=f===""?b.name:`${f}|${b.name}`,T=ca(JSON.stringify([S,c.toString(),b.name,Er,n[1],n[2]]),e.id),A=`${S}:${T}`,I=[...n.slice(0,3),!0],k={langgraph_step:c,langgraph_node:b.name,langgraph_triggers:w,langgraph_path:I,langgraph_checkpoint_ns:A,checkpoint_ns:A};if(a){const R=[],x={checkpointId:e.id,checkpointNs:A,taskId:T,threadId:d.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:b.name,input:b.input,proc:_,writes:R,config:{...ut(or(i,{metadata:k,store:o.store??i.store}),{runName:b.name,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[$u]:T,[Jr]:O=>fh(U=>R.push(...U),r,O),[xi]:(O,U=!1)=>Mu(e,s,{name:b.name,writes:R,triggers:w,path:I},O,U),[hs]:u??d.__pregel_checkpointer,[ar]:{...d[ar],[f]:e.id},[Vs]:ph({pendingWrites:t??[],taskId:T,currentTaskInput:b.input,resumeMap:(h=i.configurable)==null?void 0:h[Ru],namespaceHash:hi(A),pendingWritesIndex:o.pendingWritesIndex}),[Pu]:e.channel_values[nh],checkpoint_id:void 0,checkpoint_ns:A}}),executionInfo:x},triggers:w,retry_policy:b.retry,cache_key:b.cache?{key:hi((b.cache.keyFunc??JSON.stringify)([b.input])),ns:[mm,b.name??"__dynamic__"],ttl:b.cache.ttl}:void 0,id:T,path:I,writers:[],timeout:b.timeout}}else return{id:T,name:b.name,interrupts:[],path:I}}else if(n[0]==="__pregel_push"){const b=typeof n[1]=="number"?n[1]:parseInt(n[1],10);if(!((m=s.__pregel_tasks)!=null&&m.isAvailable()))return;const _=s[cc].get();if(b<0||b>=_.length)return;const w=a_(_[b])&&!Gn(_[b])?new Oa(_[b].node,_[b].args,_[b].timeout!==void 0?{timeout:_[b].timeout}:void 0):_[b];if(!a_(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 S=[Er],T=f===""?w.node:`${f}|${w.node}`,A=ca(JSON.stringify([T,c.toString(),w.node,Er,b.toString()]),e.id),I=`${T}:${A}`;let k={langgraph_step:c,langgraph_node:w.node,langgraph_triggers:S,langgraph_path:n.slice(0,3),langgraph_checkpoint_ns:I,checkpoint_ns:I};if(a){const R=r[w.node],x=R.getNode();if(x!==void 0){R.metadata!==void 0&&(k={...k,...R.metadata});const O=[],U={checkpointId:e.id,checkpointNs:I,taskId:A,threadId:d.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:w.node,input:w.args,proc:x,subgraphs:R.subgraphs,writes:O,config:{...ut(or(i,{metadata:k,tags:R.tags,store:o.store??i.store}),{runName:w.node,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[$u]:A,[Jr]:B=>fh(F=>O.push(...F),r,B),[xi]:(B,F=!1)=>Mu(e,s,{name:w.node,writes:O,triggers:S,path:n},B,F),[hs]:u??d.__pregel_checkpointer,[ar]:{...d[ar],[f]:e.id},[Vs]:ph({pendingWrites:t??[],taskId:A,currentTaskInput:w.args,resumeMap:(g=i.configurable)==null?void 0:g[Ru],namespaceHash:hi(I),pendingWritesIndex:o.pendingWritesIndex}),[Pu]:e.channel_values[nh],checkpoint_id:void 0,checkpoint_ns:I}}),executionInfo:U},triggers:S,retry_policy:R.retryPolicy,cache_key:R.cachePolicy?{key:hi((R.cachePolicy.keyFunc??JSON.stringify)([w.args])),ns:[mm,R.name??"__dynamic__",w.node],ttl:R.cachePolicy.ttl}:void 0,id:A,path:n,writers:R.getWriters(),timeout:w.timeout??R.timeout}}}else return{id:A,name:w.node,interrupts:[],path:n}}else if(n[0]==="__pregel_pull"){const b=n[1].toString(),_=r[b];if(_===void 0)return;if(t!=null&&t.length){const A=f===""?b:`${f}|${b}`,I=ca(JSON.stringify([A,c.toString(),b,i_,b]),e.id);if(o.pendingWritesIndex?o.pendingWritesIndex.successfulWriteTaskIds.has(I):t.some(k=>k[0]===I&&k[1]!=="__error__"))return}const w=Uw(e.channel_versions);if(w===void 0)return;const S=e.versions_seen[b]??{},T=_.triggers.find(A=>s[A].isAvailable()?(e.channel_versions[A]??w)>(S[A]??w):!1);if(T!==void 0){const A=MV(_,s,a);if(A===void 0)return;const I=f===""?b:`${f}|${b}`,k=ca(JSON.stringify([I,c.toString(),b,i_,[T]]),e.id),R=`${I}:${k}`;let x={langgraph_step:c,langgraph_node:b,langgraph_triggers:[T],langgraph_path:n,langgraph_checkpoint_ns:R,checkpoint_ns:R};if(a){const O=_.getNode();if(O!==void 0){_.metadata!==void 0&&(x={...x,..._.metadata});const U=[],B={checkpointId:e.id,checkpointNs:R,taskId:k,threadId:d.thread_id,runId:i.runId!=null?String(i.runId):void 0,nodeAttempt:1};return{name:b,input:A,proc:O,subgraphs:_.subgraphs,writes:U,config:{...ut(or(i,{metadata:x,tags:_.tags,store:o.store??i.store}),{runName:b,callbacks:l==null?void 0:l.getChild(`graph:step:${c}`),configurable:{[$u]:k,[Jr]:F=>fh(Y=>{U.push(...Y)},r,F),[xi]:(F,Y=!1)=>Mu(e,s,{name:b,writes:U,triggers:[T],path:n},F,Y),[hs]:u??d.__pregel_checkpointer,[ar]:{...d[ar],[f]:e.id},[Vs]:ph({pendingWrites:t??[],taskId:k,currentTaskInput:A,resumeMap:(y=i.configurable)==null?void 0:y[Ru],namespaceHash:hi(R),pendingWritesIndex:o.pendingWritesIndex}),[Pu]:e.channel_values[nh],checkpoint_id:void 0,checkpoint_ns:R}}),executionInfo:B},triggers:[T],retry_policy:_.retryPolicy,cache_key:_.cachePolicy?{key:hi((_.cachePolicy.keyFunc??JSON.stringify)([A])),ns:[mm,_.name??"__dynamic__",b],ttl:_.cachePolicy.ttl}:void 0,id:k,path:n,writers:_.getWriters(),timeout:_.timeout}}}else return{id:k,name:b,interrupts:[],path:n}}}}function NV(n,e,t,r,s,i,a,o,c){var k;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 m=o.configurable??{},g=m.checkpoint_ns??"",y=[Er],b=g===""?e:`${g}|${e}`,_=ca(JSON.stringify([b,u.toString(),e,Er,"node_error_handler",n.id]),r.id),w=`${b}:${_}`,S=[Er,String(n.name),e,!1];let T={langgraph_step:u,langgraph_node:e,langgraph_triggers:y,langgraph_path:S,langgraph_checkpoint_ns:w,checkpoint_ns:w};f.metadata!==void 0&&(T={...T,...f.metadata});const A=[],I={checkpointId:r.id,checkpointNs:w,taskId:_,threadId:m.thread_id,runId:o.runId!=null?String(o.runId):void 0,nodeAttempt:1};return{name:e,input:n.input,proc:h,subgraphs:f.subgraphs,writes:A,config:{...ut(or(o,{metadata:T,tags:f.tags,store:c.store??o.store}),{runName:e,callbacks:d==null?void 0:d.getChild(`graph:step:${u}`),configurable:{[$u]:_,[Jr]:R=>fh(x=>A.push(...x),i,R),[xi]:(R,x=!1)=>Mu(r,a,{name:e,writes:A,triggers:y,path:S},R,x),[hs]:l??m.__pregel_checkpointer,[ar]:{...m[ar],[g]:r.id},[Vs]:ph({pendingWrites:s??[],taskId:_,currentTaskInput:n.input,resumeMap:(k=o.configurable)==null?void 0:k[Ru],namespaceHash:hi(w)}),[Pu]:r.channel_values[nh],[r_]:new E3(String(n.name),t),checkpoint_id:void 0,checkpoint_ns:w}}),executionInfo:I},triggers:y,retry_policy:f.retryPolicy,cache_key:void 0,id:_,path:S,writers:f.getWriters()}}function MV(n,e,t){let r;if(typeof n.channels=="object"&&!Array.isArray(n.channels)){r={};for(const[s,i]of Object.entries(n.channels))if(n.triggers.includes(i))try{r[s]=Ro(e,i,!1)}catch(a){if(a.name===on.unminifiable_name)return;throw a}else if(i in e)try{r[s]=Ro(e,i,!1)}catch(a){if(a.name===on.unminifiable_name)continue;throw a}}else if(Array.isArray(n.channels)){let s=!1;for(const i of n.channels)try{r=Ro(e,i,!1),s=!0;break}catch(a){if(a.name===on.unminifiable_name)continue;throw a}if(!s)return}else throw new Error(`Invalid channels type, expected list or dict, got ${n.channels}`);return t&&n.mapper!==void 0&&(r=n.mapper(r)),r}function jV(n,e){if(typeof n.args!="object"||n.args===null)return n;const t={};for(const[r,s]of Object.entries(n.args)){const i=e[r];(!i||i.lc_graph_name!=="UntrackedValue")&&(t[r]=s)}return new Oa(n.node,t)}function ph({pendingWrites:n,taskId:e,currentTaskInput:t,resumeMap:r,namespaceHash:s,pendingWritesIndex:i}){var c;const a=i?i.nullResume:(c=n.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():n.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:t,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,n.splice(n.findIndex(([u,l])=>u==="00000000-0000-0000-0000-000000000000"&&l==="__resume__"),1),a}};return o}const ol={blue:{start:"\x1B[34m",end:"\x1B[0m"},green:{start:"\x1B[32m",end:"\x1B[0m"},yellow:{start:"\x1B[33;1m",end:"\x1B[0m"}},cl=(n,e)=>`${n.start}${e}${n.end}`;function*xm(n){var e;for(const{id:t,name:r,input:s,config:i,triggers:a,writes:o}of n)(e=i==null?void 0:i.tags)!=null&&e.includes("langsmith:hidden")||(yield{id:t,name:r,input:s,triggers:a,interrupts:o.filter(([c,u])=>c===t&&u==="__interrupt__").map(([,c])=>c)})}function LV(n){return typeof n!="object"||n===null?!1:"$writes"in n&&Array.isArray(n.$writes)}function oC(n){const e={};for(const[t,r]of n){const s=String(t);if(s in e){const i=LV(e[s])?e[s].$writes:[e[s]];i.push(r),e[s]={$writes:i}}else e[s]=r}return e}function*DV(n,e){var t;for(const[{id:r,name:s,config:i},a]of n)(t=i==null?void 0:i.tags)!=null&&t.includes("langsmith:hidden")||(yield{id:r,name:s,result:oC(a.filter(([o])=>Array.isArray(e)?e.includes(o):o===e)),interrupts:a.filter(o=>o[0]===Ft).map(o=>o[1])})}function*UV(n,e,t,r,s,i,a,o){var d,f,h;function c(m){const g={};return m.callbacks!=null&&(g.callbacks=m.callbacks),m.configurable!=null&&(g.configurable=m.configurable),m.maxConcurrency!=null&&(g.max_concurrency=m.maxConcurrency),m.metadata!=null&&(g.metadata=m.metadata),m.recursionLimit!=null&&(g.recursion_limit=m.recursionLimit),m.runId!=null&&(g.run_id=m.runId),m.runName!=null&&(g.run_name=m.runName),m.tags!=null&&(g.tags=m.tags),g}const u=(d=n.configurable)==null?void 0:d.checkpoint_ns,l={};for(const m of s){if(!((f=m.subgraphs)!=null&&f.length?m.subgraphs:[m.proc]).find(YO))continue;let g=`${m.name}:${m.id}`;u&&(g=`${u}|${g}`),l[m.id]={configurable:{thread_id:(h=n.configurable)==null?void 0:h.thread_id,checkpoint_ns:g}}}yield{config:c(n),values:Ra(e,t),metadata:r,next:s.map(m=>m.name),tasks:cC(s,i,l,o),parentConfig:a?c(a):void 0}}function cC(n,e,t,r){return n.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,m])=>h===s.id&&r.includes(m)).map(([,h,m])=>[h,m]);return f.length?oC(f):void 0}})();if(i)return{id:s.id,name:s.name,path:s.path,error:i,interrupts:a,result:o};const c=t==null?void 0:t[s.id];return{id:s.id,name:s.name,path:s.path,interrupts:a,...c!==void 0?{state:c}:{},result:o}})}function zV(n,e,t){console.log([`${cl(ol.blue,`[${n}:checkpoint]`)}`,`\x1B[1m State at the end of step ${n}:\x1B[0m
|
|
339
|
+
`,JSON.stringify(Ra(e,t),null,2)].join(""))}function R_(n,e){const t=e.length;console.log([`${cl(ol.blue,`[${n}:tasks]`)}`,`\x1B[1m Starting step ${n} with ${t} task${t===1?"":"s"}:\x1B[0m
|
|
340
|
+
`,e.map(r=>`- ${cl(ol.green,String(r.name))} -> ${JSON.stringify(r.input,null,2)}`).join(`
|
|
341
|
+
`)].join(""))}function FV(n,e,t){const r={};for(const[s,i]of e)t.includes(s)&&(r[s]||(r[s]=[]),r[s].push(i));console.log([`${cl(ol.blue,`[${n}:writes]`)}`,`\x1B[1m Finished step ${n} with writes to ${Object.keys(r).length} channel${Object.keys(r).length!==1?"s":""}:\x1B[0m
|
|
342
|
+
`,Object.entries(r).map(([s,i])=>`- ${cl(ol.yellow,s)} -> ${i.map(a=>JSON.stringify(a)).join(", ")}`).join(`
|
|
343
|
+
`)].join(""))}const BV=["values","updates","messages","tools","custom","tasks"];function Bw(n){if(n==null||typeof n!="object")return!1;const e=n;return typeof e.id=="string"&&("source"in e||typeof e.step=="number")&&!("values"in e)&&!("config"in e)}function HV(n){if(!Array.isArray(n)||n.length!==2)return{data:n};const[e,t]=n;if(t==null||typeof t!="object")return{data:n};const r=t,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 VV({namespace:n,mode:e,payload:t,seq:r}){const s=Date.now(),i={type:"event"};switch(e){case"messages":{const{data:a,node:o}=HV(t);return[{...i,seq:r,method:"messages",params:{namespace:n,timestamp:s,...o?{node:o}:{},data:a}}]}case"tools":return[{...i,seq:r,method:"tools",params:{namespace:n,timestamp:s,data:ZV(t)}}];case"checkpoints":return Bw(t)?[{...i,seq:r,method:"checkpoints",params:{namespace:n,timestamp:s,data:t}}]:[];case"values":return[{...i,seq:r,method:"values",params:{namespace:n,timestamp:s,data:t}}];case"updates":{const a=KV(t);return[{...i,seq:r,method:"updates",params:{namespace:n,timestamp:s,...typeof a.node=="string"?{node:a.node}:{},data:a}}]}case"custom":{const a=typeof t=="object"&&t!==null&&!Array.isArray(t)&&"name"in t?t:{payload:t};return[{...i,seq:r,method:"custom",params:{namespace:n,timestamp:s,data:a}}]}case"tasks":return[{...i,seq:r,method:"tasks",params:{namespace:n,timestamp:s,data:t}}];default:return[]}}function ZV(n){if(typeof n!="object"||n===null)return{event:"tool-error",tool_call_id:"",message:"Unexpected tools payload shape"};const e=n,t=String(e.toolCallId??"");switch(e.event){case"on_tool_start":return{event:"tool-started",tool_call_id:t,tool_name:String(e.name??"unknown"),input:e.input};case"on_tool_event":return{event:"tool-output-delta",tool_call_id:t,delta:typeof e.data=="string"?e.data:JSON.stringify(e.data??"")};case"on_tool_end":return{event:"tool-finished",tool_call_id:t,output:e.output};case"on_tool_error":{const r=e.error;return{event:"tool-error",tool_call_id:t,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 KV(n){if(typeof n!="object"||n===null)return{values:{}};const e=Object.entries(n);if(e.length===0)return{values:{}};const[t,r]=e[0];return{node:t,values:typeof r=="object"&&r!==null?r:{value:r}}}var Om=class extends Wn{constructor(e,t){const r=e.getReader(),s=t??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()})}}});p(this,"_abortController");p(this,"_innerReader");this._abortController=s,this._innerReader=r}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},uC=class extends Wn{constructor(e){let t;const r=new Promise(s=>{t=s});super({start:s=>{t(s)}});p(this,"modes");p(this,"controller");p(this,"passthroughFn");p(this,"_closed",!1);r.then(s=>{this.controller=s}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}get closed(){return this._closed}push(e){var t;this._closed||!this.controller||((t=this.passthroughFn)==null||t.call(this,e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){var t;try{(t=this.controller)==null||t.error(e)}finally{this._closed=!0}}},WV=class extends Qs{constructor(e){super();p(this,"name","StreamToolsHandler");p(this,"awaitHandlers",!0);p(this,"streamFn");p(this,"runs",{});this.streamFn=e}handleToolStart(e,t,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:t};this.runs[r]=l,this.streamFn([u,"tools",{event:"on_tool_start",toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){const r=this.runs[t];r&&this.streamFn([r.ns,"tools",{event:"on_tool_event",toolCallId:r.toolCallId,name:r.toolName,data:e}])}handleToolEnd(e,t){const r=this.runs[t];delete this.runs[t],r&&this.streamFn([r.ns,"tools",{event:"on_tool_end",toolCallId:r.toolCallId,name:r.toolName,output:e}])}handleToolError(e,t){const r=this.runs[t];delete this.runs[t],r&&this.streamFn([r.ns,"tools",{event:"on_tool_error",toolCallId:r.toolCallId,name:r.toolName,error:e}])}};function qV(n){return JSON.stringify(n,function(e,t){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 t})}function GV(n){return n instanceof Error?{error:n.name,message:n.message}:{error:"Error",message:JSON.stringify(n)}}function Hw(n){return typeof n!="object"||n==null?!1:"configurable"in n&&typeof n.configurable=="object"&&n.configurable!=null}function Cm(n){return!Hw(n)||!n.configurable.thread_id?null:{thread_id:n.configurable.thread_id,checkpoint_ns:n.configurable.checkpoint_ns||"",checkpoint_id:n.configurable.checkpoint_id||null,checkpoint_map:n.configurable.checkpoint_map||null}}function bS(n){if(Hw(n)){const e=Object.fromEntries(Object.entries(n.configurable).filter(([r])=>!r.startsWith("__"))),t={...n,configurable:e};return delete t.callbacks,t}return n}function vS(n){const e={...n,checkpoint:Cm(n.config),parent_checkpoint:Cm(n.parentConfig),config:bS(n.config),parent_config:bS(n.parentConfig),tasks:n.tasks.map(t=>{if(Hw(t.state)){const r=Cm(t.state);if(r!=null){const s={...t,checkpoint:r};return delete s.state,s}}return t})};return delete e.parentConfig,e}function JV(n){const e=new TextEncoder;return new ReadableStream({async start(t){const r=s=>{t.enqueue(e.encode(`event: ${s.event}
|
|
344
|
+
data: ${qV(s.data)}
|
|
345
|
+
|
|
346
|
+
`))};try{for await(const s of n){const[i,a,o]=s;let c=o;if(a==="debug"){const u=o;u.type==="checkpoint"&&(c={...u,payload:vS(u.payload)})}a==="checkpoints"&&(c=vS(o)),r({event:i!=null&&i.length?`${a}|${i.join("|")}`:a,data:c})}}catch(s){r({event:"error",data:GV(s)})}t.close()}})}function YV(...n){return new uC({passthroughFn:e=>{const t=e[1]==="checkpoints"&&Bw(e[2]);for(const r of n)(r.modes.has(e[1])||t)&&r.push(e)},modes:new Set(n.flatMap(e=>Array.from(e.modes)))})}var gl,jf,lC,FT,XV=(FT=class{constructor(n){et(this,jf);p(this,"checkpointId");et(this,gl,new Set);this.checkpointId=n}async getCheckpoint(n,e,t){if(Zi(this,jf,lC).call(this,n)){const r=[];for await(const s of e.list(t,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))r.push(s);return r.length>0?r[0]:void 0}return await e.getTuple(t)??void 0}},gl=new WeakMap,jf=new WeakSet,lC=function(n){const e=n.includes(":")?n.slice(0,n.lastIndexOf(":")):n;return re(this,gl).has(e)?!1:(re(this,gl).add(e),!0)},FT);const Ed=Symbol.for("INPUT_DONE"),$m=Symbol.for("INPUT_RESUMING"),QV=25;function dC(n){if(!(n==null||typeof n!="object")){if(Lt.isInstance(n)){const e=n;e.id==null&&(e.id=Ni(),e.lc_kwargs!=null&&(e.lc_kwargs.id=e.id));return}if(Array.isArray(n)){for(const e of n)dC(e);return}}}function hC(n){return n===void 0||n===""?[]:n.split("|")}function eZ(n){if(!n)return[];let e="";for(const t of Object.keys(n))t!==""&&t.length>e.length&&(e=t);return hC(e)}var tZ=class extends F8{constructor(e){super();p(this,"cache");p(this,"queue",Promise.resolve());this.cache=e}async get(e){return this.enqueueOperation("get",e)}async set(e){return this.enqueueOperation("set",e)}async clear(e){return this.enqueueOperation("clear",e)}async stop(){await this.queue}enqueueOperation(e,...t){const r=this.queue.then(()=>this.cache[e](...t));return this.queue=r.then(()=>{},()=>{}),r}},Lf,fC,Mo,nZ=(Mo=class{constructor(e){et(this,Lf);p(this,"input");p(this,"output");p(this,"config");p(this,"checkpointer");p(this,"checkpointerGetNextVersion");p(this,"channels");p(this,"checkpoint");p(this,"checkpointIdSaved");p(this,"_exitDeltaWrites");p(this,"_hasPersistedParent",!1);p(this,"_initialCheckpointConfig");p(this,"checkpointConfig");p(this,"checkpointMetadata");p(this,"checkpointNamespace");p(this,"checkpointPendingWrites",[]);p(this,"checkpointPreviousVersions");p(this,"step");p(this,"stop");p(this,"durability");p(this,"outputKeys");p(this,"streamKeys");p(this,"nodes");p(this,"skipDoneTasks");p(this,"prevCheckpointConfig");p(this,"updatedChannels");p(this,"status","pending");p(this,"control");p(this,"tasks",{});p(this,"stream");p(this,"checkpointerPromises",new Set);p(this,"isNested");p(this,"resumeAtHead");p(this,"_checkpointerChainedPromise",Promise.resolve());p(this,"store");p(this,"cache");p(this,"manager");p(this,"interruptAfter");p(this,"interruptBefore");p(this,"toInterrupt",[]);p(this,"debug",!1);p(this,"triggerToNodes");this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer!==void 0?this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer):this.checkpointerGetNextVersion=IV,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 tZ(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 t=e.then(r=>(this.checkpointerPromises.delete(t),r),r=>{throw r});this.checkpointerPromises.add(t)}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 t=((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=rn(this.input)&&this.input.resume!=null,i=this.input===$m,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&&(t||r||s||i||a)}get isReplaying(){return!this.skipDoneTasks}static async initialize(e){var x,O,U,B,F,Y,Z,ge,M,K,se,oe,X,ie,Ee,de,E,v,j,C,_e;let{config:t,stream:r}=e;r!==void 0&&((x=t.configurable)==null?void 0:x.__pregel_stream)!==void 0&&(r=YV(r,t.configurable[iw]));const s=t.configurable?!("checkpoint_id"in t.configurable):!0,i=(O=t.configurable)==null?void 0:O[Vs];t.configurable&&i&&(i.subgraphCounter>0&&(t=Mn(t,{[ls]:[t.configurable[ls],i.subgraphCounter.toString()].join("|")})),i.subgraphCounter+=1);const a=(U=t.configurable)==null?void 0:U.checkpoint_id,o=xi in(t.configurable??{});!o&&((B=t.configurable)==null?void 0:B.checkpoint_ns)!==void 0&&((F=t.configurable)==null?void 0:F.checkpoint_ns)!==""&&(t=Mn(t,{checkpoint_ns:"",checkpoint_id:void 0}));let c=t;((Y=t.configurable)==null?void 0:Y.checkpoint_id)===void 0&&((Z=t.configurable)==null?void 0:Z.checkpoint_map)!==void 0&&((K=(ge=t.configurable)==null?void 0:ge.checkpoint_map)!=null&&K[(M=t.configurable)==null?void 0:M.checkpoint_ns])&&(c=Mn(t,{checkpoint_id:t.configurable[ar][(se=t.configurable)==null?void 0:se.checkpoint_ns]}));const u=hC((oe=t.configurable)==null?void 0:oe.checkpoint_ns);let l;e.checkpointer?(X=c.configurable)!=null&&X.checkpoint_id?l=await e.checkpointer.getTuple(c):(ie=t.configurable)!=null&&ie.__pregel_replay_state?(l=await t.configurable[s_].getCheckpoint(((Ee=t.configurable)==null?void 0:Ee.checkpoint_ns)??"",e.checkpointer,c),t.configurable&&delete t.configurable[Cu]):l=await e.checkpointer.getTuple(c):l=void 0;const d=l!==void 0;l||(l={config:t,checkpoint:A_(),metadata:{source:"input",step:-2,parents:{}},pendingWrites:[]}),c={...t,...l.config,configurable:{checkpoint_ns:"",...t.configurable,...l.config.configurable}};const f=l.parentConfig,h=lf(l.checkpoint),m={...l.metadata};let g=l.pendingWrites??[];const y=(de=t.configurable)==null?void 0:de.checkpoint_ns,b=(E=t.configurable)==null?void 0:E[ar];typeof y=="string"&&y!==""&&typeof b=="object"&&b!==null&&y in b&&g.length>0&&(g=g.filter(([,xe])=>xe!==bs));let _=!1;const w=(v=c.configurable)==null?void 0:v.thread_id,S=((j=c.configurable)==null?void 0:j.checkpoint_ns)??"";e.checkpointer&&a&&typeof w=="string"&&(_=((_e=(C=await e.checkpointer.getTuple({configurable:{thread_id:w,checkpoint_ns:S}}))==null?void 0:C.config.configurable)==null?void 0:_e.checkpoint_id)===a&&m.source!=="update"&&m.source!=="fork");const T=await E_(e.channelSpecs,h,{saver:e.checkpointer,config:c}),A=(m.step??0)+1,I=A+(t.recursionLimit??QV)+1,k={...h.channel_versions},R=e.store?new z8(e.store):void 0;return R&&await R.start(),new Mo({input:e.input,config:t,checkpointer:e.checkpointer,checkpoint:h,checkpointMetadata:m,checkpointConfig:c,prevCheckpointConfig:f,checkpointNamespace:u,channels:T,isNested:o,resumeAtHead:_,manager:e.manager,skipDoneTasks:s,step:A,stop:I,checkpointPreviousVersions:k,checkpointPendingWrites:g,outputKeys:e.outputKeys??[],streamKeys:e.streamKeys??[],nodes:e.nodes,stream:r,store:R,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 t;return(t=this.checkpointer)==null?void 0:t.put(e.config,e.checkpoint,e.metadata,e.newVersions)}),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,t){var c;let r=t;if(r.length===0)return;r.every(([u])=>u in j8)&&(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"&&Gn(l)?[u,jV(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&&vi(d)&&dC(l)}const a=Mn(this.checkpointConfig,{[ls]:((c=this.config.configurable)==null?void 0:c.checkpoint_ns)??"",[Qi]:this.checkpoint.id});if(this.durability!=="exit"&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,r),!t.length||!this.cache||!this.tasks)return;const o=this.tasks[e];o==null||o.cache_key==null||t[0][0]==="__error__"||t[0][0]==="__interrupt__"||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,t,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(t.length>0)if(t[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=t.filter(c=>c[0]===Ft).flatMap(c=>c[1]);this._emit([["updates",{[Ft]:o}],["values",{[Ft]:o}]])}else t[0][0]!=="__error__"&&this._emit(ao(xs(AV(this.outputKeys,[[s,t]],r),"updates")));r||this._emit(ao(xs(DV([[s,t]],this.streamKeys),"tasks")))}}async _matchCachedWrites(){if(!this.cache)return[];const e=[],t=([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[t([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[t(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:t=[]}=e;if(this.status!=="pending")throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![Ed,$m].includes(this.input))await this._first(t);else{if(this.toInterrupt.length>0)throw this.status="interrupt_before",new Oo;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=sr(this.checkpoint,this.channels,o,this.checkpointerGetNextVersion,this.triggerToNodes);const u=await gi(xs(Im(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&&vi(h)&&this._exitDeltaWrites.push([this.step,l,d,f])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:"loop"}),this._emitValuesWithCheckpointMeta(u),Td(this.checkpoint,this.interruptAfter,o))throw this.status="interrupt_after",new Oo;((i=this.config.configurable)==null?void 0:i.__pregel_resuming)!==void 0&&((a=this.config.configurable)==null||delete a[Cu])}else return!1}if(this.step>this.stop)return this.status="out_of_steps",!1;this.tasks=vo(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 gi(xs(UV(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:t});if(Td(this.checkpoint,this.interruptBefore,r))throw this.status="interrupt_before",new Oo;if(this.stream.modes.has("tasks")||this.stream.modes.has("debug")){const o=await gi(xs(xm(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 t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=Ra(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(r=>r.writes.length>0)&&(this.updatedChannels=sr(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(ao(xs(Im(this.outputKeys,Object.values(this.tasks).flatMap(r=>r.writes),this.channels),"values")))),oa(e)&&!e.interrupts.length&&this._emit([["updates",{[Ft]:[]}],["values",{[Ft]:[]}]],Zi(this,Lf,fC).call(this))),t}async acceptPush(e,t,r){var a,o;if(((a=this.interruptAfter)==null?void 0:a.length)>0&&Td(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}const s=$_([Er,e.path??[],t,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&&Td(this.checkpoint,this.interruptBefore,[s])){this.toInterrupt.push(s);return}(this.stream.modes.has("tasks")||this.stream.modes.has("debug"))&&this._emit(ao(xs(xm([s]),"tasks"))),this.debug&&R_(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 t;return(t=this.nodes[e])==null?void 0:t.errorHandlerNode}isErrorHandlerNode(e){var t;return((t=this.nodes[e])==null?void 0:t.isErrorHandler)===!0}scheduleErrorHandler(e,t){const r=this.getErrorHandlerNode(String(e.name));if(!r)return;const s=NV(e,r,t,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(ao(xs(xm([s]),"tasks"))),this.debug&&R_(this.step,[s]),s}_resumeErrorHandlersIfApplicable(){const e=new Map;for(const[t,r]of this.checkpointPendingWrites){if(r!=="__error_source_node__")continue;const s=this.checkpointPendingWrites.find(([o,c])=>o===t&&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(t,a)}for(const[t,r]of e){const s=this.tasks[t];s!==void 0&&this.getErrorHandlerNode(String(s.name))&&(s.writes.length===0&&s.writes.push([jl,{message:r.message,name:r.name}]),this.scheduleErrorHandler(s,r))}}_suppressInterrupt(e){return oa(e)&&!this.isNested}async _first(e){var u,l;const{configurable:t}=this.config,r=t==null?void 0:t[Vs];if(r&&r.nullResume!==void 0&&this.putWrites(Tr,[[bs,r.nullResume]]),rn(this.input)){const d=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume=="object"&&Object.keys(this.input.resume).every(iC)&&((u=this.config).configurable??(u.configurable={}),this.config.configurable[Ru]=this.input.resume),d&&this.checkpointer==null)throw new Error("Cannot use Command(resume=...) without checkpointer");const f={};for(const[h,m,g]of SV(this.input,this.checkpointPendingWrites))f[h]??(f[h]=[]),f[h].push([m,g]);if(Object.keys(f).length===0)throw new eS("Received empty Command input");for(const[h,m]of Object.entries(f))this.putWrites(h,m)}const s=(this.checkpointPendingWrites??[]).filter(d=>d[0]===Tr).map(d=>d.slice(1));s.length>0&&sr(this.checkpoint,this.channels,[{name:mi,writes:s,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);const i=rn(this.input),a=i&&s.length>0,o=this.isReplaying&&(this.isNested&&(t==null?void 0:t.checkpoint_ns)!==void 0&&(t==null?void 0:t.checkpoint_ns)!==""&&(t==null?void 0:t.checkpoint_map)!==void 0&&t.checkpoint_ns in t.checkpoint_map||!(i&&this.input.resume!=null||(t==null?void 0:t.__pregel_resuming)===!0||this.resumeAtHead));o&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(d=>d[1]!==bs));const c=this.isResuming;if(c||a){const d={...this.checkpoint.versions_seen[Ft]};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[Ft]=d,o&&this.checkpointMetadata.source!=="update"&&this.checkpointMetadata.source!=="fork"&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(h=>h[1]!==Ft),await this._putCheckpoint({source:"fork"}));const f=await gi(xs(Im(this.outputKeys,!0,this.channels),"values"));c?this.input=$m:a&&(await this._putCheckpoint({source:"input"}),this.input=Ed),this._emitValuesWithCheckpointMeta(f)}else{const d=await gi(aC(e,this.input));if(d.length>0){const f=vo(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=sr(this.checkpoint,this.channels,Object.values(f).concat([{name:mi,writes:d,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);const h=d.filter(([m])=>{const g=this.channels[m];return g!=null&&vi(g)});if(h.length>0)if(this._exitDeltaWrites!==void 0)for(const[m,g]of h)this._exitDeltaWrites.push([this.step,Tr,m,g]);else this.checkpointer!=null&&this.putWrites(Tr,h);await this._putCheckpoint({source:"input"}),this.input=Ed}else if("__pregel_resuming"in(this.config.configurable??{}))this.input=Ed;else throw new eS(`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 XV(f)}this.config=Mn(this.config,{[Cu]:this.isResuming,[s_]:d})}}_emit(e,t=this.checkpointNamespace){for(const[r,s]of e)if(this.stream.modes.has(r)&&this.stream.push([t,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([t,"debug",{step:i,type:o,timestamp:a,payload:s}])}}_currentCheckpointMeta(){var t,r,s;if(!this.checkpointMetadata||!((t=this.checkpoint)!=null&&t.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 t=this._currentCheckpointMeta();for(const[r,s]of e)r==="values"&&(t==null?void 0:t.checkpoint)!=null&&!this.stream.modes.has("checkpoints")&&this.stream.push([this.checkpointNamespace,"checkpoints",t.checkpoint]),this.stream.modes.has(r)&&this.stream.push([this.checkpointNamespace,r,s])}_putCheckpoint(e){var c;const t=this.checkpointMetadata===e,r=this.checkpointer!=null&&(this.durability!=="exit"||t),s=u=>{var f,h,m;this.prevCheckpointConfig=(h=(f=this.checkpointConfig)==null?void 0:f.configurable)!=null&&h.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Mn(this.checkpointConfig,{[ls]:((m=this.config.configurable)==null?void 0:m.checkpoint_ns)??""});const l={...this.checkpoint.channel_versions},d=dh(this.checkpointPreviousVersions,l);this.checkpointPreviousVersions=l,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:lf(u),metadata:{...this.checkpointMetadata},newVersions:d}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};let i;if(t)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)||!vi(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?gS(this.channels,i):new Set;this.checkpoint=sa(this.checkpoint,r?this.channels:void 0,this.step,{id:t?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),t||(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??{},t=gS(this.channels,e),r=this._exitDeltaWrites.filter(([,,l])=>!t.has(l));if(r.length===0)return;let s;if(this._hasPersistedParent)s=this._initialCheckpointConfig;else{const l=A_();l.id=this.checkpointIdSaved??l.id,l.ts=new Date().toISOString();const d=Mn(this._initialCheckpointConfig,{[Qi]:void 0});s=Mn(this._initialCheckpointConfig,{[Qi]:l.id}),this._trackCheckpointerPromise(this.checkpointer.put(d,l,{source:"loop",step:-2,parents:{}},{})),this.checkpointConfig=s}const i=Mn(s,{[ls]:((c=this.config.configurable)==null?void 0:c.checkpoint_ns)??"",[Qi]:(u=s.configurable)==null?void 0:u[Qi]}),a=new Map,o=[];for(const[l,d,f,h]of r){const m=`${l}\0${d}`;let g=a.get(m);g===void 0&&(g=[],a.set(m,g),o.push({key:m,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=Mn(this.checkpointConfig,{[ls]:((r=this.config.configurable)==null?void 0:r.checkpoint_ns)??"",[Qi]:this.checkpoint.id}),t={};for(const[s,i,a]of this.checkpointPendingWrites)t[s]??(t[s]=[]),t[s].push([i,a]);for(const[s,i]of Object.entries(t))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,i,s))}_matchWrites(e){for(const[t,r,s]of this.checkpointPendingWrites){if(r==="__error__"||r==="__interrupt__"||r==="__resume__")continue;const i=Object.values(e).find(a=>a.id===t);i&&i.writes.push([r,s])}for(const t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}},Lf=new WeakSet,fC=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 t=eZ((s=this.config.configurable)==null?void 0:s[ar]);return t.length>0?t:e},Mo);function rZ(n){return Rt(n==null?void 0:n.message)}function SS(n,e,t){if(!n)return;const r=n.langgraph_checkpoint_ns,s=n.checkpoint_ns,i=r??s;if(i)return[i.split("|"),{tags:e,name:t,...n}]}var sZ=class extends Qs{constructor(e){super();p(this,"name","StreamMessagesHandler");p(this,"streamFn");p(this,"metadatas",{});p(this,"seen",{});p(this,"emittedChatModelRunIds",{});p(this,"stableMessageIdMap",{});p(this,"lc_prefer_streaming",!0);this.streamFn=e}_emit(e,t,r,s=!1){var a;if(s&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;r!=null&&(_a(t)?i??(i=`run-${r}-tool-${t.tool_call_id}`):((i==null||i===`run-${r}`)&&(i=this.stableMessageIdMap[r]??i??`run-${r}`),(a=this.stableMessageIdMap)[r]??(a[r]=i))),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],"messages",[t,e[1]]])}handleChatModelStart(e,t,r,s,i,a,o,c){o&&(!a||!a.includes("langsmith:nostream")&&!a.includes("nostream"))&&(this.metadatas[r]=SS(o,a,c))}handleLLMNewToken(e,t,r,s,i,a){const o=a==null?void 0:a.chunk;this.emittedChatModelRunIds[r]=!0,this.metadatas[r]!==void 0&&(rZ(o)?this._emit(this.metadatas[r],o.message,r):this._emit(this.metadatas[r],new nt({content:e}),r))}handleLLMEnd(e,t){var r,s;if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){const i=(s=(r=e.generations)==null?void 0:r[0])==null?void 0:s[0];Rt(i==null?void 0:i.message)&&this._emit(this.metadatas[t],i==null?void 0:i.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,r,s,i,a,o,c){if(a!==void 0&&c===a.langgraph_node&&(i===void 0||!i.includes("langsmith:hidden"))&&(this.metadatas[r]=SS(a,i,c),typeof t=="object")){for(const u of Object.values(t))if((Rt(u)||Go(u))&&u.id!==void 0)this.seen[u.id]=u;else if(Array.isArray(u))for(const l of u)(Rt(l)||Go(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){const r=this.metadatas[t];if(delete this.metadatas[t],r!==void 0){if(Rt(e))this._emit(r,e,t,!0);else if(Array.isArray(e))for(const s of e)Rt(s)&&this._emit(r,s,t,!0);else if(e!=null&&typeof e=="object"){for(const s of Object.values(e))if(Rt(s))this._emit(r,s,t,!0);else if(Array.isArray(s))for(const i of s)Rt(i)&&this._emit(r,i,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function AS(n){if("response_metadata"in n&&typeof n.response_metadata=="object"&&n.response_metadata!=null)return n.response_metadata}function TS(n){if("usage_metadata"in n&&typeof n.usage_metadata=="object"&&n.usage_metadata!=null)return n.usage_metadata}function iZ(n){switch(n.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",...n.id!=null?{id:n.id}:{},...n.name!=null?{name:n.name}:{},args:""};default:return n}}function aZ(n){switch(n.type){case"text":{const e=typeof n.text=="string"?n.text:"";return e.length>0?{event:"content-block-delta",index:typeof n.index=="number"?n.index:0,delta:{type:"text-delta",text:e}}:void 0}case"reasoning":{const e=typeof n.reasoning=="string"?n.reasoning:"";return e.length>0?{event:"content-block-delta",index:typeof n.index=="number"?n.index:0,delta:{type:"reasoning-delta",reasoning:e}}:void 0}case"tool_call_chunk":return{event:"content-block-delta",index:typeof n.index=="number"?n.index:0,delta:{type:"block-delta",fields:{...n,type:"tool_call_chunk"}}};default:return}}var oZ=class extends Qs{constructor(e){super();p(this,"name","StreamProtocolMessagesHandler");p(this,"streamFn");p(this,"metadatas",{});p(this,"seen",{});p(this,"streamedRunIds",new Set);p(this,"stableMessageIdMap",{});p(this,"lc_prefer_chat_model_stream_events",!0);this.streamFn=e}normalizeMessageId(e,t){var s;let r=e.id;return t!=null&&(_n.isInstance(e)?r??(r=`run-${t}-tool-${e.tool_call_id}`):((r==null||r===`run-${t}`)&&(r=this.stableMessageIdMap[t]??r??`run-${t}`),(s=this.stableMessageIdMap)[t]??(s[t]=r))),r!==e.id&&(e.id=r,e.lc_kwargs.id=r),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,r){const s=r!=null?{...e[1],run_id:r}:e[1];this.streamFn([e[0],"messages",[t,s]])}emitFinalMessage(e,t,r,s=!1){const i=t.id??(r!=null?this.stableMessageIdMap[r]:void 0);if(s&&i!=null&&this.seen[i]!==void 0)return;const a=this.normalizeMessageId(t,r),o=t.type==="human"?"human":t.type==="system"?"system":t.type==="tool"?"tool":"ai",c=o==="tool"&&_n.isInstance(t)?t.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(t.content)?t.content:typeof t.content=="string"&&t.content.length>0?[{type:"text",text:t.content}]:[]).forEach((u,l)=>{const d=typeof u.index=="number"?u.index:l;this.emit(e,{event:"content-block-start",index:d,content:iZ(u)},r);const f=aZ({...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",...TS(t)!=null?{usage:TS(t)}:{},...AS(t)!=null?{responseMetadata:AS(t)}:{}},r)}handleChatModelStart(e,t,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,t){var i;const r=this.metadatas[t];if(r===void 0)return;let s=e;if(e.event==="message-start"){this.streamedRunIds.add(t);const a=e.id??`run-${t}`;this.seen[a]=!0,(i=this.stableMessageIdMap)[t]??(i[t]=a),e.id==null&&(s={...e,id:a})}this.emit(r,s,t)}handleLLMEnd(e,t){var a,o;const r=this.metadatas[t];if(r===void 0)return;const s=(o=(a=e.generations)==null?void 0:a[0])==null?void 0:o[0],i=Lt.isInstance(s==null?void 0:s.message)?s.message:void 0;if(i!=null)if(this.streamedRunIds.has(t)){const c=this.normalizeMessageId(i,t);c!=null&&(this.seen[c]=i)}else this.emitFinalMessage(r,i,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,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 t=="object")){for(const u of Object.values(t))if((Lt.isInstance(u)||As.isInstance(u))&&u.id!==void 0)this.seen[u.id]=u;else if(Array.isArray(u))for(const l of u)(Lt.isInstance(l)||As.isInstance(l))&&l.id!==void 0&&(this.seen[l.id]=l)}}handleChainEnd(e,t){const r=this.metadatas[t];if(delete this.metadatas[t],r===void 0)return;const s=i=>{Lt.isInstance(i)&&!_n.isInstance(i)&&this.emitFinalMessage(r,i,t,!0)};if(Lt.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[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}},cZ=class{constructor(n){p(this,"active",!0);p(this,"lastProgress",Date.now());p(this,"refreshOn");this.refreshOn=n}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn==="auto"&&(this.lastProgress=Date.now())}close(){this.active=!1}},_l,Jt,BT,uZ=(BT=class extends Qs{constructor(e){super();p(this,"name","IdleProgressCallbackHandler");p(this,"awaitHandlers",!1);et(this,_l);et(this,Jt,()=>{re(this,_l).autoTouch()});p(this,"handleLLMStart",re(this,Jt));p(this,"handleChatModelStart",re(this,Jt));p(this,"handleLLMNewToken",re(this,Jt));p(this,"handleLLMEnd",re(this,Jt));p(this,"handleLLMError",re(this,Jt));p(this,"handleChainStart",re(this,Jt));p(this,"handleChainEnd",re(this,Jt));p(this,"handleChainError",re(this,Jt));p(this,"handleToolStart",re(this,Jt));p(this,"handleToolEnd",re(this,Jt));p(this,"handleToolError",re(this,Jt));p(this,"handleText",re(this,Jt));p(this,"handleRetrieverStart",re(this,Jt));p(this,"handleRetrieverEnd",re(this,Jt));p(this,"handleRetrieverError",re(this,Jt));p(this,"handleCustomEvent",re(this,Jt));_t(this,_l,e)}},_l=new WeakMap,Jt=new WeakMap,BT);function lZ(n,e,t,r){const s=n.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[oc];typeof o=="function"&&(i[oc]=(...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?Mn(n,i):n};if(c.heartbeat=()=>{t.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((t.refreshOn??"auto")==="auto"&&t.idleTimeout!==void 0){const u=new uZ(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 dZ(n,e,t,r){const s=new cZ(t.refreshOn??"auto"),i=new AbortController,{signal:a,dispose:o}=al(e.signal,i.signal),c=lZ({...e,signal:a},s,t,String(n.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)},m=new Promise(b=>{if(t.runTimeout!==void 0&&(d=setTimeout(()=>b({type:"timeout",kind:"run"}),t.runTimeout)),t.idleTimeout!==void 0){const _=t.idleTimeout,w=()=>{const S=s.lastProgress+_-Date.now();S<=0?b({type:"timeout",kind:"idle"}):f=setTimeout(w,S)};f=setTimeout(w,_)}});let g;try{g=await Promise.race([l,m])}finally{h()}if(g.type!=="timeout"){const b=Date.now();t.runTimeout!==void 0&&b-u>=t.runTimeout?g={type:"timeout",kind:"run"}:t.idleTimeout!==void 0&&b-s.lastProgress>=t.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(),n.writes.splice(0,n.writes.length),i.abort(),o==null||o(),new I3({node:String(n.name),elapsed:y,kind:g.kind,runTimeout:t.runTimeout,idleTimeout:t.idleTimeout})}const hZ=[400,401,402,403,404,405,406,407,409],fZ=n=>{var t,r;if(n.message.startsWith("Cancel")||n.message.startsWith("AbortError")||n.name==="AbortError"||n.name==="GraphValueError"||(n==null?void 0:n.code)==="ECONNABORTED")return!1;const e=((t=n==null?void 0:n.response)==null?void 0:t.status)??(n==null?void 0:n.status);return!(e&&hZ.includes(+e)||((r=n==null?void 0:n.error)==null?void 0:r.code)==="insufficient_quota")};async function P_(n,e,t,r){var l;const s=n.retry_policy??e;let i=0,a,o,c=n.config??{};t&&(c=Mn(c,t)),c={...c,signal:r};const u=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:u});!(r!=null&&r.aborted);){n.writes.splice(0,n.writes.length),a=void 0;try{n.timeout!==void 0?o=await dZ(n,c,n.timeout,d=>n.proc.invoke(n.input,d)):o=await n.proc.invoke(n.input,c);break}catch(d){if(a=d,a.pregelTaskId=n.id,k3(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 n.writers)await _.invoke(b,c);a=void 0;break}else if(b.graph===cr.PARENT){const _=J8(y);a.command=new cr({...a.command,graph:_})}}if(au(a)||s===void 0||(i+=1,i>=(s.maxAttempts??3))||!(s.retryOn??fZ)(a))break;const f=s.initialInterval??500,h=Math.min(s.maxInterval??128e3,f*(s.backoffFactor??2)**(i-1)),m=s.jitter??!0?h+Math.random()*1e3:h;await new Promise(y=>setTimeout(y,m));const g=a.name??a.constructor.unminifiable_name??a.constructor.name;((s==null?void 0:s.logWarning)??!0)&&console.log(`Retrying task "${String(n.name)}" after ${m.toFixed(2)}ms (attempt ${i}) after ${g}: ${a}`),c=Mn(c,{[Cu]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:i+1,nodeFirstAttemptTime:u})}}return{task:n,result:o,error:a,signalAborted:r==null?void 0:r.aborted}}const N_=Symbol.for("promiseAdded");function pZ(){const n={next:()=>{},wait:Promise.resolve(N_)};function e(t){n.next=()=>{n.wait=new Promise(e),t(N_)}}return n.wait=new Promise(e),n}var mZ=class{constructor({loop:n,nodeFinished:e}){p(this,"nodeFinished");p(this,"loop");p(this,"handledExceptions",new WeakSet);this.loop=n,this.nodeFinished=e}async tick(n={}){const{timeout:e,retryPolicy:t,onStepWrite:r,maxConcurrency:s}=n,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:n.signal}),m=this._executeTasksWithRetry(d,{signals:f,retryPolicy:t,maxConcurrency:s});for await(const{task:g,error:y,signalAborted:b}of m)this._commit(g,y),!(y!==void 0&&this.handledExceptions.has(y))&&(oa(y)||au(y)&&!oa(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(oa(a)||Q0(a)||au(a)&&this.loop.isNested)throw a}_initializeAbortSignals({exceptionSignal:n,stepTimeoutSignal:e,signal:t}){var u;const r=((u=this.loop.config.configurable)==null?void 0:u.__pregel_abort_signals)??{},s=r.externalAbortSignal??t,i=e??r.timeoutAbortSignal,{signal:a,dispose:o}=al(s,i,n),c={externalAbortSignal:s,timeoutAbortSignal:i,composedAbortSignal:a};return this.loop.config=Mn(this.loop.config,{[w3]:c}),{signals:c,disposeCombinedSignal:o}}async*_executeTasksWithRetry(n,e){var f,h,m;const{retryPolicy:t,maxConcurrency:r,signals:s}=e??{},i=pZ(),a={},o={executingTasksMap:a,barrier:i,retryPolicy:t,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=al(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)&&n.length;){for(;Object.values(a).length<(r??n.length)&&c<n.length;c+=1){const w=n[c];a[w.id]=P_(w,t,{[oc]:ea==null?void 0:ea.bind(o,this,w)},s==null?void 0:s.composedAbortSignal).catch(S=>{var T;return{task:w,error:S,signalAborted:(T=s==null?void 0:s.composedAbortSignal)==null?void 0:T.aborted}})}const g=await Promise.race([...Object.values(a),...d?[d]:[],i.wait]);if(g===N_)continue;const y=g,{task:b,error:_}=y;if(_!==void 0&&!au(_)&&!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]=P_(w,t,{[oc]:ea==null?void 0:ea.bind(o,this,w)},s==null?void 0:s.composedAbortSignal).catch(S=>{var T;return{task:w,error:S,signalAborted:(T=s==null?void 0:s.composedAbortSignal)==null?void 0:T.aborted}}),i.next())}yield y,u!=null&&((h=l.signal)==null||h.removeEventListener("abort",u),(m=l.dispose)==null||m.call(l)),delete a[g.task.id]}}_shouldRouteToErrorHandler(n){const e=String(n.name);return this.loop.isErrorHandlerNode(e)?!1:this.loop.getErrorHandlerNode(e)!==void 0}_commit(n,e){var t;if(e!==void 0)if(oa(e)){if(e.interrupts.length){const r=e.interrupts.map(i=>[Ft,i]),s=n.writes.filter(i=>i[0]===bs);s.length&&r.push(...s),this.loop.putWrites(n.id,r)}}else Q0(e)?n.writes.length&&this.loop.putWrites(n.id,n.writes):au(e)&&n.writes.length?this.loop.putWrites(n.id,n.writes):(n.writes.push([jl,{message:e.message,name:e.name}]),this._shouldRouteToErrorHandler(n)&&(n.writes.push([sw,String(n.name)]),this.handledExceptions.add(e)),this.loop.putWrites(n.id,n.writes));else this.nodeFinished&&(((t=n.config)==null?void 0:t.tags)==null||!n.config.tags.includes("langsmith:hidden"))&&this.nodeFinished(String(n.name)),n.writes.length===0&&n.writes.push([aw,null]),this.loop.putWrites(n.id,n.writes)}};async function ea(n,e,t,r,s,i={}){var d,f;const a=(f=(d=e.config)==null?void 0:d.configurable)==null?void 0:f[Vs];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 TV({func:t,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===op),m=u.writes.filter(([g])=>g===jl);if(h.length>0){if(h.length===1)return Promise.resolve(h[0][1]);throw new Error(`BUG: multiple returns found for task ${u.name}__${u.id}`)}if(m.length>0){if(m.length===1){const g=m[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=P_(u,i.retry,{[oc]:ea.bind(this,n,u)});return this.executingTasksMap[u.id]=h,this.barrier.next(),h.then(({result:m,error:g})=>g?Promise.reject(g):m)}}const Rm=Symbol.for("langgraph.stream_channel");var HT,us,yl,ha,jo,wl,Lo,mh,Ea,Pa=(Ea=class{constructor(e){et(this,Lo);p(this,HT,!0);p(this,"channelName");et(this,us,[]);et(this,yl,[]);et(this,ha,!1);et(this,jo);et(this,wl);this.channelName=e}static local(){return new Ea}static remote(e){return new Ea(e)}static isInstance(e){return typeof e=="object"&&e!==null&&Rm in e&&e[Rm]===!0}push(e){var t;re(this,us).push(e),Zi(this,Lo,mh).call(this),(t=re(this,wl))==null||t.call(this,e)}iterate(e=0){let t=e;return{next:async()=>{for(;;){if(t<re(this,us).length)return{value:re(this,us)[t++],done:!1};if(re(this,ha)){if(re(this,jo))throw re(this,jo);return{value:void 0,done:!0}}await new Promise(r=>re(this,yl).push(r))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){const t=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(t.encode(`${c.join(`
|
|
347
|
+
`)}
|
|
348
|
+
|
|
349
|
+
`))}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>=re(this,us).length)throw new RangeError(`StreamChannel index ${e} out of bounds (size=${re(this,us).length})`);return re(this,us)[e]}get size(){return re(this,us).length}get done(){return re(this,ha)}close(){_t(this,ha,!0),Zi(this,Lo,mh).call(this)}fail(e){_t(this,jo,e),_t(this,ha,!0),Zi(this,Lo,mh).call(this)}_wire(e){_t(this,wl,e)}_close(){this.close()}_fail(e){this.fail(e)}[(HT=Rm,Symbol.asyncIterator)](){return this.iterate()}},us=new WeakMap,yl=new WeakMap,ha=new WeakMap,jo=new WeakMap,wl=new WeakMap,Lo=new WeakSet,mh=function(){const e=re(this,yl).splice(0);for(const t of e)t()},Ea);function gZ(n){return Pa.isInstance(n)}const _Z="custom:";function yZ(n){return`${_Z}${n}`}function wZ(n){return n!=null&&(typeof n=="object"||typeof n=="function")&&typeof n.then=="function"}const M_=Symbol("resolveValues"),pC=Symbol("rejectValues");var Do,Uo,zo,bl,fa,pa,Fo,ma,vl,Sl,Al,VT,bZ=(VT=class{constructor(){p(this,"_events",Pa.local());p(this,"_discoveries",Pa.local());et(this,Do,0);et(this,Uo,!1);et(this,zo);et(this,bl,!1);et(this,fa,[]);et(this,pa,[]);et(this,Fo,[]);et(this,ma,new Map);et(this,vl,new Map);et(this,Sl,[]);et(this,Al,[])}register(n,e){re(this,ma).set(Bn(n),e)}addTransformer(n){var t,r;const e=this._events.size;re(this,pa).push(n),n.onRegister&&n.onRegister({push:(s,i)=>this.push(s,i)});for(let s=0;s<e;s+=1)n.process(this._events.get(s));re(this,Uo)&&(re(this,zo)!==void 0?(t=n.fail)==null||t.call(n,re(this,zo)):(r=n.finalize)==null||r.call(n))}wireChannels(n){for(const[e,t]of Object.entries(n)){if(gZ(t)){if(re(this,Fo).push(t),typeof t.channelName!="string")continue;const r=yZ(t.channelName);t._wire(s=>{this._events.push({type:"event",seq:nd(this,Do)._++,method:r,params:{namespace:re(this,fa),timestamp:Date.now(),data:s}})});continue}wZ(t)&&re(this,Al).push({name:e,promise:Promise.resolve(t)})}}push(n,e){e.method==="values"&&re(this,vl).set(Bn(n),e.params.data);const t=re(this,fa);_t(this,fa,n);let r=!0;for(const s of re(this,pa))s.process(e)||(r=!1);_t(this,fa,t),r&&this._events.push({...e,seq:nd(this,Do)._++})}close(){var t,r;_t(this,Uo,!0);for(const[s,i]of re(this,vl).entries()){const a=s?s.split("\0"):[];(t=re(this,ma).get(Bn(a)))==null||t[M_](i)}const n=[];for(const s of re(this,pa)){const i=(r=s.finalize)==null?void 0:r.call(s);i!=null&&typeof i.then=="function"&&n.push(i)}for(const s of re(this,Fo))s._close();const e=re(this,Al);e.length===0&&n.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...n,...e.map(async({name:s,promise:i})=>{try{const a=await i;this._events.done||this._events.push({type:"event",seq:nd(this,Do)._++,method:"custom",params:{namespace:[],timestamp:Date.now(),data:{name:s,payload:a}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(const s of re(this,ma).values())s[M_](void 0)}fail(n){var e;_t(this,Uo,!0),_t(this,zo,n);for(const t of re(this,pa))(e=t.fail)==null||e.call(t,n);for(const t of re(this,Fo))t._fail(n);this._events.fail(n),this._discoveries.fail(n);for(const t of re(this,ma).values())t[pC](n)}markInterrupted(n){_t(this,bl,!0),re(this,Sl).push(...n)}get interrupted(){return re(this,bl)}get interrupts(){return re(this,Sl)}subscribeEvents(n,e=0){const t=this._events.iterate(e);return{async next(){for(;;){const r=await t.next();if(r.done||Ic(r.value.params.namespace,n))return r}}}}},Do=new WeakMap,Uo=new WeakMap,zo=new WeakMap,bl=new WeakMap,fa=new WeakMap,pa=new WeakMap,Fo=new WeakMap,ma=new WeakMap,vl=new WeakMap,Sl=new WeakMap,Al=new WeakMap,VT);async function vZ(n,e){let t=0;try{for await(const r of n){const[s,i,a]=r;if(i==="values"&&cw(a)){const c=a[Ft];e.markInterrupted(c.map(u=>({interruptId:u.id??"",payload:u.value})))}const o=VV({namespace:s,mode:i,payload:a,seq:t});t+=o.length;for(const c of o)e.push(s,c)}}catch(r){e.fail(r);return}e.close()}function Bn(n){return n.join("\0")}function Ic(n,e){if(e.length>n.length)return!1;for(let t=0;t<e.length;t+=1)if(n[t]!==e[t])return!1;return!0}function mC(n,e,t=0){return{[Symbol.asyncIterator](){const r=n.iterate(t);return{async next(){for(;;){const s=await r.next();if(s.done)return{value:void 0,done:!0};if(Ic(s.value.namespace,e))return{value:s.value,done:!1}}}}}}}const gC="root";function SZ(n){if(n.length===0)return gC;const e=n[n.length-1],t=e.indexOf(":");return t===-1?e:e.slice(0,t)}function AZ(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}function pf(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function TZ(n){if(!pf(n)||n.event!=="started")return;const e=n.cause;if(pf(e)&&typeof e.type=="string")return e}function EZ(n){if(pf(n)&&"result"in n&&typeof n.name=="string"&&typeof n.id=="string"&&!n.name.startsWith("__"))return{name:n.name,id:n.id}}function kZ(n={}){const e=n.rootGraphName??gC,t=n.initialStatus??"running",r=n.emitRootOnRegister??!0,s=n.getGraphName??SZ,i=n.serializeError??AZ,a=n.getTerminalStatusOverride,o=Pa.local(),c=new Map,u=new Map,l=new Set,d=[];let f,h=0,m=!1;const g=O=>O.length===0?e:s(O),y=(O,U,B)=>{const F=Bn(O);let Y=c.get(F);const Z=(Y==null?void 0:Y.graphName)??g(O);if(Y!=null&&Y.status===U&&Y.graphName===Z&&(B==null?void 0:B.error)==null)return;Y==null?(Y={namespace:O,graphName:Z,status:U},c.set(F,Y)):Y.status=U;const ge={event:U,graph_name:Z,...(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:O,timestamp:M,...ge}),!(O.length===0&&!r)&&f!=null){h+=1;try{f.push(O,{type:"event",seq:0,method:"lifecycle",params:{namespace:O,timestamp:M,data:ge}})}finally{h-=1}}},b=O=>{const U=Bn(O);let B=c.get(U);return B==null&&(B={namespace:O,graphName:g(O),status:void 0},c.set(U,B)),B},_=()=>{if(d.length===0)return;const O=d.splice(0,d.length);for(const U of O){const B=Bn(U.namespace),F=c.get(B);F==null||F.status!=="started"||y(U.namespace,"completed")}},w=O=>{const U=Bn(O.namespace),B=c.get(U);B==null||B.status!=="started"||d.some(F=>Bn(F.namespace)===U)||d.push(O)},S=(O,U)=>{for(let B=d.length-1;B>=0;B-=1){const F=d[B];F.source.type==="node"&&F.source.node===U&&Bn(F.source.parent)===Bn(O)&&d.splice(B,1)}},T=O=>{for(let U=1;U<=O.length;U+=1){const B=O.slice(0,U),F=Bn(B);if(c.has(F))continue;b(B);const Y=u.get(F);y(B,"started",Y!=null?{cause:Y}:void 0)}},A=()=>l.size>0?"interrupted":"completed",I=O=>{for(const U of c.values())U.namespace.length!==0&&U.status==="started"&&y(U.namespace,O);y([],O),o.close()},k=async()=>{if(a==null)return A();try{return await a()??A()}catch{return A()}},R=(O,U)=>{const B=`${U}:`;for(const F of c.values()){if(F.namespace.length!==O.length+1||F.status!=="started"||!Ic(F.namespace,O))continue;const Y=F.namespace[F.namespace.length-1];if(Y===U||Y.startsWith(B))return F.namespace}},x=(O,U)=>{var F;const B=[...O,`${U.name}:${U.id}`];return((F=c.get(Bn(B)))==null?void 0:F.status)==="started"?B:void 0};return{__native:!0,init(){return{_lifecycleLog:o,lifecycle:mC(o,[],0)}},onRegister(O){f=O,b([]),r&&y([],t)},process(O){const U=O.params.namespace;if(h>0)return!0;const B=O.method==="tasks"?EZ(O.params.data):void 0;if(B!=null&&S(U,B.name),_(),O.method==="lifecycle"){const F=TZ(O.params.data);return F!=null&&u.set(Bn(U),F),T(U),!1}if(T(U),O.method==="input"&&pf(O.params.data)&&O.params.data.event==="requested"){const F=O.params.data.id;typeof F=="string"&&l.add(F)}if(B!=null){const F=x(U,B);F!=null&&w({namespace:F,source:{type:"task"}})}if(O.method==="updates"){const F=O.params.node;if(typeof F=="string"&&!F.startsWith("__")){const Y=R(U,F);Y!=null&&w({namespace:Y,source:{type:"node",parent:U,node:F}})}}return!0},finalize(){if(!m){if(m=!0,_(),a==null){I(A());return}return k().then(I).catch(O=>{o.fail(O)})}},fail(O){if(m)return;m=!0;const U=i(O);for(const B of c.values())B.namespace.length!==0&&B.status==="started"&&y(B.namespace,"failed");y([],"failed",{error:U}),o.fail(O)}}}function Ka(n){const e=n;return typeof e.run_id=="string"?`run:${e.run_id}`:n.event==="message-start"&&typeof e.id=="string"?`message:${e.id}`:"__default__"}function j_(n,e){const t=Pa.local(),r=new Map,s=new Set;return{init:()=>({messages:t.toAsyncIterable()}),process(i){var o,c;if(i.method!=="messages"||!Ic(i.params.namespace,n)||i.params.namespace.length!==n.length+1||e!==void 0&&i.params.node!==e)return!0;const a=i.params.data;switch(a.event){case"message-start":{const u=Ka(a);if(a.role==="tool"){s.add(u);break}const l=Pa.local(),d=Object.assign(new rf(l.toAsyncIterable()),{namespace:i.params.namespace,node:i.params.node});r.set(u,{source:l,stream:d}),l.push(a),t.push(d);break}case"content-block-start":case"content-block-delta":case"content-block-finish":if(s.has(Ka(a)))break;(o=r.get(Ka(a)))==null||o.source.push(a);break;case"message-finish":{const u=Ka(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(Ka(a)))break;(c=r.get(Ka(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(),t.close()},fail(i){for(const[a,o]of r)o.source.fail(i),r.delete(a);s.clear(),t.fail(i)}}}function Vw(n,e,t=0){const r=e.length+1;return{[Symbol.asyncIterator](){const s=n.iterate(t);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&&Ic(a,e))return{value:o,done:!1}}}}}}}function IZ(n,e){const{createStream:t}=e,r=new Set;return{__native:!0,init(){return{_discoveries:n._discoveries,subgraphs:Vw(n._discoveries,[],0)}},process(s){const i=s.params.namespace;if(i.length===0)return!0;const a=i.slice(0,1),o=Bn(a);if(r.has(o))return!0;r.add(o);const c=t(a,n._discoveries.size,n._events.size);return n.register(a,c),n._discoveries.push({ns:a,stream:c}),!0}}}function xZ(n){const e=Pa.local();return{init:()=>({_valuesLog:e}),process(t){return t.method!=="values"||t.params.namespace.length!==n.length||!Ic(t.params.namespace,n)||e.push(t.params.data),!0},finalize(){e.close()},fail(t){e.fail(t)}}}function ES(n){return"__native"in n&&n.__native===!0}const _C=Symbol("setValuesLog"),yC=Symbol("setMessagesIterable"),L_=Symbol("setLifecycleIterable"),D_=Symbol("setSubgraphsIterable"),OZ={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}};var Bo,Tl,Ho,Vo,Zo,ga,El,_i,kl,Ko,ZT,wC=(ZT=class{constructor(n,e,t=0,r=0,s,i){p(this,"path");p(this,"extensions");p(this,"_mux");et(this,Bo);et(this,Tl);et(this,Ho);et(this,Vo);et(this,Zo);et(this,ga);et(this,El);et(this,_i);et(this,kl);et(this,Ko);this.path=n,this._mux=e,_t(this,Tl,t),_t(this,Bo,r),this.extensions=s??{},_t(this,Ho,i??new AbortController),_t(this,ga,new Promise((a,o)=>{_t(this,Vo,a),_t(this,Zo,o)})),re(this,ga).catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,re(this,Bo))}get subgraphs(){return re(this,Ko)?re(this,Ko):Vw(this._mux._discoveries,this.path,re(this,Tl))}get values(){const n=re(this,El),e=re(this,ga),t=this._mux,r=re(this,Bo),s=this.path,i=n?n.toAsyncIterable():{[Symbol.asyncIterator]:()=>{const a=t.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(re(this,_i))return re(this,_i);const n=j_(this.path),e=n.init();return this._mux.addTransformer(n),_t(this,_i,e.messages),re(this,_i)}get lifecycle(){return re(this,kl)??OZ}messagesFrom(n){const e=j_(this.path,n),t=e.init();return this._mux.addTransformer(e),t.messages}get output(){return re(this,ga)}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(n){re(this,Ho).abort(n)}get signal(){return re(this,Ho).signal}[M_](n){var e;(e=re(this,Vo))==null||e.call(this,n),_t(this,Vo,void 0)}[pC](n){var e;(e=re(this,Zo))==null||e.call(this,n),_t(this,Zo,void 0)}[_C](n){_t(this,El,n)}[yC](n){_t(this,_i,n)}[L_](n){_t(this,kl,n)}[D_](n){_t(this,Ko,n)}},Bo=new WeakMap,Tl=new WeakMap,Ho=new WeakMap,Vo=new WeakMap,Zo=new WeakMap,ga=new WeakMap,El=new WeakMap,_i=new WeakMap,kl=new WeakMap,Ko=new WeakMap,ZT),CZ=class extends wC{constructor(e,t,r=0,s=0,i,a){super(e,t,r,s,i,a);p(this,"name");p(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 $Z(n,e=[],t){const{abortController:r}=t instanceof AbortController?{abortController:t}:{},s=new bZ,i=kZ(),a=i.init(),o=a._lifecycleLog,c=IZ(s,{createStream:(b,_,w)=>{const S=new CZ(b,s,_,w);return S[D_](Vw(s._discoveries,b,_)),S[L_](mC(o,b,o.size)),S}}),u=c.init();s.addTransformer(c),s.addTransformer(i);const l=xZ([]),d=j_([]);s.addTransformer(l),s.addTransformer(d);const f={},h=[];for(const b of e){const _=b();s.addTransformer(_);const w=_.init();ES(_)?h.push(w):Object.assign(f,w),typeof w=="object"&&w!==null&&!ES(_)&&s.wireChannels(w)}const m=new wC([],s,0,0,f,r);for(const b of h)Object.assign(m,b);const g=l.init();m[_C](g._valuesLog);const y=d.init();return m[yC](y.messages),m[L_](a.lifecycle),m[D_](u.subgraphs),s.register([],m),vZ(n,s).catch(b=>{}),m}var Os=class extends Error{constructor(n){super(n),this.name="GraphValidationError"}};function RZ({nodes:n,channels:e,inputChannels:t,outputChannels:r,streamChannels:s,interruptAfterNodes:i,interruptBeforeNodes:a}){if(!e)throw new Os("Channels not provided");const o=new Set,c=new Set;for(const[u,l]of Object.entries(n)){if(u==="__interrupt__")throw new Os(`"Node name ${Ft} is reserved"`);if(l.constructor===il)l.triggers.forEach(d=>o.add(d));else throw new Os(`Invalid node type ${typeof l}, expected PregelNode`)}for(const u of o)if(!(u in e))throw new Os(`Subscribed channel '${String(u)}' not in channels`);if(Array.isArray(t)){if(t.every(u=>!o.has(u)))throw new Os(`None of the input channels ${t} are subscribed to by any node`)}else if(!o.has(t))throw new Os(`Input channel ${String(t)} 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 Os(`Output channel '${String(u)}' not in channels`);if(i&&i!=="*"){for(const u of i)if(!(u in n))throw new Os(`Node ${String(u)} not in nodes`)}if(a&&a!=="*"){for(const u of a)if(!(u in n))throw new Os(`Node ${String(u)} not in nodes`)}}function kS(n,e){if(Array.isArray(n)){for(const t of n)if(!(t in e))throw new Error(`Key ${String(t)} not found in channels`)}else if(!(n in e))throw new Error(`Key ${String(n)} not found in channels`)}var PZ=class bC extends Hi{constructor(t){super();p(this,"lc_graph_name","Topic");p(this,"unique",!1);p(this,"accumulate",!1);p(this,"seen");p(this,"values");this.unique=(t==null?void 0:t.unique)??this.unique,this.accumulate=(t==null?void 0:t.accumulate)??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){const r=new bC({unique:this.unique,accumulate:this.accumulate});return typeof t<"u"&&(r.seen=new Set(t[0]),r.values=t[1]),r}update(t){let r=!1;this.accumulate||(r=this.values.length>0,this.values=[]);const s=t.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 on;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function NZ(n){var a,o,c;const e=yn.getRunnableConfig();if(!e)throw new Error("Called interrupt() outside the context of a graph.");const t=e.configurable;if(!t)throw new Error("No configurable found in config");if(!t.__pregel_checkpointer)throw new rh("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});const r=t[Vs];r.interruptCounter+=1;const s=r.interruptCounter;if(r.resume.length>0&&s<r.resume.length)return(a=t[Jr])==null||a.call(t,[[bs,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=t[Jr])==null||o.call(t,[[bs,r.resume]]),u}const i=(c=t[ls])==null?void 0:c.split("|");throw new Oo([{id:i?hi(i.join("|")):void 0,value:n}])}function MZ(n){const e=new TextEncoder;return new ReadableStream({async start(t){try{for await(const r of n){const s=r.params.namespace,i=s.length?`${r.method}|${s.join("|")}`:r.method;t.enqueue(e.encode(`event: ${i}
|
|
350
|
+
data: ${JSON.stringify(r.params.data??{})}
|
|
351
|
+
|
|
352
|
+
`))}}catch(r){t.enqueue(e.encode(`event: error
|
|
353
|
+
data: ${JSON.stringify({message:String(r)})}
|
|
354
|
+
|
|
355
|
+
`))}finally{t.close()}}})}var jZ=class{static subscribeTo(n,e){const{key:t,tags:r}={key:void 0,tags:void 0,...e??{}};if(Array.isArray(n)&&t!==void 0)throw new Error("Can't specify a key when subscribing to multiple channels");let s;return typeof n=="string"?t?s={[t]:n}:s=[n]:s=Object.fromEntries(n.map(i=>[i,i])),new il({channels:s,triggers:Array.isArray(n)?n:[n],tags:r})}static writeTo(n,e){const t=[];for(const r of n)t.push({channel:r,value:Ta,skipNone:!1});for(const[r,s]of Object.entries(e??{}))Ge.isRunnable(s)||typeof s=="function"?t.push({channel:r,value:Ta,skipNone:!0,mapper:gn(s)}):t.push({channel:r,value:s,skipNone:!1});return new Ln(t)}},LZ=class extends Ge{constructor(){super(...arguments);p(this,"lc_namespace",["langgraph","pregel"])}invoke(e,t){throw new Error("Not implemented")}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Df,vC,KT,DZ=(KT=class extends LZ{constructor(e){super(e);et(this,Df);p(this,"lc_namespace",["langgraph","pregel"]);p(this,"lg_is_pregel",!0);p(this,"nodes");p(this,"channels");p(this,"inputChannels");p(this,"outputChannels");p(this,"autoValidate",!0);p(this,"streamMode",["values"]);p(this,"streamChannels");p(this,"interruptAfter");p(this,"interruptBefore");p(this,"stepTimeout");p(this,"debug",!1);p(this,"checkpointer");p(this,"retryPolicy");p(this,"config");p(this,"store");p(this,"cache");p(this,"userInterrupt");p(this,"streamTransformers");p(this,"triggerToNodes",{});let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,"__pregel_tasks"in this.channels&&"lc_graph_name"in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!=="Topic")throw new Error(`Channel '${cc}' is reserved and cannot be used in the graph.`);this.channels[cc]=new PZ({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}static lc_name(){return"LangGraph"}withConfig(e){const{streamTransformers:t,...r}=e,s=or(this.config,r),i=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:s,streamTransformers:i})}validate(){var e;RZ({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(const[t,r]of Object.entries(this.nodes))for(const s of r.triggers)(e=this.triggerToNodes)[s]??(e[s]=[]),this.triggerToNodes[s].push(t);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){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=YO(o);if(c!==void 0){if(s===e){yield[s,c];return}if(e===void 0&&(yield[s,c]),t){let u=e;e!==void 0&&(u=e.slice(s.length+1));for(const[l,d]of c.getSubgraphs(u,t))yield[`${s}|${l}`,d]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:r,applyPendingWrites:s=!1}){var f,h,m,g,y,b,_,w;if(t===void 0)return{values:{},next:[],config:e,tasks:[]};const i=await E_(this.channels,t.checkpoint,{saver:typeof this.checkpointer=="object"?this.checkpointer:void 0,config:t.config??e});if((f=t.pendingWrites)!=null&&f.length){const S=t.pendingWrites.filter(([T,A])=>T===Tr).map(([T,A,I])=>[String(A),I]);S.length>0&&sr(t.checkpoint,i,[{name:mi,writes:S,triggers:[]}],void 0,this.triggerToNodes)}const a=Object.values(vo(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(((h=t.metadata)==null?void 0:h.step)??-1)+1,store:this.store})),o=await gi(this.getSubgraphsAsync()),c=((m=t.config.configurable)==null?void 0:m.checkpoint_ns)??"",u={};for(const S of a){const T=o.find(([I])=>I===S.name);if(!T)continue;let A=`${String(S.name)}:${S.id}`;if(c&&(A=`${c}|${A}`),r===void 0){const I={configurable:{thread_id:(g=t.config.configurable)==null?void 0:g.thread_id,checkpoint_ns:A}};u[S.id]=I}else{const I={configurable:{[hs]:r,thread_id:(y=t.config.configurable)==null?void 0:y.thread_id,checkpoint_ns:A}},k=T[1];u[S.id]=await k.getState(I,{subgraphs:!0})}}if(s&&((b=t.pendingWrites)!=null&&b.length)){const S=Object.fromEntries(a.map(A=>[A.id,A]));for(const[A,I,k]of t.pendingWrites)["__error__","__interrupt__",sh].includes(I)||A in S&&S[A].writes.push([String(I),k]);const T=a.filter(A=>A.writes.length>0);T.length>0&&sr(t.checkpoint,i,T,void 0,this.triggerToNodes)}let l=t==null?void 0:t.metadata;l&&((w=(_=t==null?void 0:t.config)==null?void 0:_.configurable)!=null&&w.thread_id)&&(l={...l,thread_id:t.config.configurable.thread_id});const d=a.filter(S=>S.writes.length===0).map(S=>S.name);return{values:Ra(i,this.streamChannelsAsIs),next:d,tasks:cC(a,(t==null?void 0:t.pendingWrites)??[],u,this.streamChannelsAsIs),metadata:l,config:Ki(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){var o,c,u,l,d;const r=((o=e.configurable)==null?void 0:o.__pregel_checkpointer)??this.checkpointer;if(!r)throw new rh("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=Tm(s);for await(const[h,m]of this.getSubgraphsAsync(f,!0))if(h===f)return await m.getState(Va(e,{[hs]:r}),{subgraphs:t==null?void 0:t.subgraphs})}const i=or(this.config,e),a=await r.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:t!=null&&t.subgraphs?r:void 0,applyPendingWrites:!((d=e.configurable)!=null&&d.checkpoint_id)})}async*getStateHistory(e,t){var a,o,c;const r=((a=e.configurable)==null?void 0:a.__pregel_checkpointer)??this.checkpointer;if(!r)throw new rh("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=Tm(s);for await(const[l,d]of this.getSubgraphsAsync(u,!0))if(l===u){yield*d.getStateHistory(Va(e,{[hs]:r}),t);return}}const i=or(this.config,e,{configurable:{checkpoint_ns:s}});for await(const u of r.list(i,t))yield this._prepareStateSnapshot({config:u.config,saved:u})}async bulkUpdateState(e,t){var o,c,u;const r=((o=e.configurable)==null?void 0:o.__pregel_checkpointer)??this.checkpointer;if(!r)throw new rh("No checkpointer set",{lc_error_code:"MISSING_CHECKPOINTER"});if(t.length===0)throw new Error("No supersteps provided");if(t.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=Tm(s);for await(const[,d]of this.getSubgraphsAsync(l,!0))return await d.bulkUpdateState(Va(e,{[hs]:r}),t);throw new Error(`Subgraph "${l}" not found`)}const i=async(l,d)=>{var O,U,B,F,Y,Z,ge,M,K,se,oe;const f=this.config?or(this.config,l):l,h=await r.getTuple(f),m=h!==void 0?lf(h.checkpoint):A_(),g={...h==null?void 0:h.checkpoint.channel_versions},y=((O=h==null?void 0:h.metadata)==null?void 0:O.step)??-1;let b=Va(f,{checkpoint_ns:((U=f.configurable)==null?void 0:U.checkpoint_ns)??""}),_=f.metadata??{};h!=null&&h.config.configurable&&(b=Va(f,h.config.configurable),_={...h.metadata,..._});const{values:w,asNode:S}=d[0];if(w==null&&S===void 0){if(d.length>1)throw new vt("Cannot create empty checkpoint with multiple updates");return Ki(await r.put(b,sa(m,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 T=await E_(this.channels,m,{saver:r,config:(h==null?void 0:h.config)??b});if(w===null&&S==="__end__"){if(d.length>1)throw new vt("Cannot apply multiple updates when clearing state");if(h){const X=vo(m,h.pendingWrites||[],this.nodes,T,h.config,!0,{step:(((F=h.metadata)==null?void 0:F.step)??-1)+1,checkpointer:r,store:this.store}),ie=(h.pendingWrites||[]).filter(Ee=>Ee[0]===Tr).map(Ee=>Ee.slice(1));ie.length>0&&sr(m,T,[{name:mi,writes:ie,triggers:[]}],r.getNextVersion.bind(r),this.triggerToNodes);for(const[Ee,de,E]of h.pendingWrites||[])["__error__","__interrupt__",sh].includes(de)||Ee in X&&X[Ee].writes.push([de,E]);sr(m,T,Object.values(X),r.getNextVersion.bind(r),this.triggerToNodes)}return Ki(await r.put(b,sa(m,T,y),{..._,source:"update",step:y+1,parents:((Y=h==null?void 0:h.metadata)==null?void 0:Y.parents)??{}},dh(g,m.channel_versions)),h?h.metadata:void 0)}if(S==="__copy__"){if(d.length>1)throw new vt("Cannot copy checkpoint with multiple updates");if(h==null)throw new vt("Cannot copy a non-existent checkpoint");const X=de=>!Array.isArray(de)||de.length===0?!1:de.every(E=>Array.isArray(E)&&E.length===2),ie=sa(m,void 0,y),Ee=await r.put(h.parentConfig??Va(h.config,{checkpoint_id:void 0}),ie,{source:"fork",step:y+1,parents:((Z=h.metadata)==null?void 0:Z.parents)??{}},{});if(X(w)){const de=vo(ie,h.pendingWrites,this.nodes,T,Ee,!1,{step:y+2}),E=Object.values(de).reduce((j,{name:C,id:_e})=>(j[C]??(j[C]=[]),j[C].push({id:_e}),j),{}),v=w.reduce((j,C)=>{var yt,Ot;const[_e,xe]=C;j[xe]??(j[xe]=[]);const dt=j[xe].length,Qe=(Ot=(yt=E[xe])==null?void 0:yt[dt])==null?void 0:Ot.id;return j[xe].push({values:_e,asNode:xe,taskId:Qe}),j},{});return i(Ki(Ee,h.metadata),Object.values(v).flat())}return Ki(Ee,h.metadata)}if(S==="__input__"){if(d.length>1)throw new vt("Cannot apply multiple updates when updating as input");const X=await gi(aC(this.inputChannels,w));if(X.length===0)throw new vt(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);sr(m,T,[{name:mi,writes:X,triggers:[]}],r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const ie=((ge=h==null?void 0:h.metadata)==null?void 0:ge.step)!=null?h.metadata.step+1:-1,Ee=await r.put(b,sa(m,T,ie),{source:"input",step:ie,parents:((M=h==null?void 0:h.metadata)==null?void 0:M.parents)??{}},dh(g,m.channel_versions));return await r.putWrites(Ee,X,ca(mi,m.id)),Ki(Ee,h?h.metadata:void 0)}if(((K=f.configurable)==null?void 0:K.checkpoint_id)===void 0&&(h==null?void 0:h.pendingWrites)!==void 0&&h.pendingWrites.length>0){const X=vo(m,h.pendingWrites,this.nodes,T,h.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(((se=h.metadata)==null?void 0:se.step)??-1)+1}),ie=(h.pendingWrites??[]).filter(de=>de[0]===Tr).map(de=>de.slice(1));ie.length>0&&sr(h.checkpoint,T,[{name:mi,writes:ie,triggers:[]}],void 0,this.triggerToNodes);for(const[de,E,v]of h.pendingWrites)["__error__","__interrupt__",sh].includes(E)||X[de]===void 0||X[de].writes.push([E,v]);const Ee=Object.values(X).filter(de=>de.writes.length>0);Ee.length>0&&sr(m,T,Ee,void 0,this.triggerToNodes)}const A=Object.values(m.versions_seen).map(X=>Object.values(X)).flat().find(X=>!!X),I=[];if(d.length===1){let{values:X,asNode:ie,taskId:Ee}=d[0];if(ie===void 0&&Object.keys(this.nodes).length===1)[ie]=Object.keys(this.nodes);else if(ie===void 0&&A===void 0)typeof this.inputChannels=="string"&&this.nodes[this.inputChannels]!==void 0&&(ie=this.inputChannels);else if(ie===void 0){const de=Object.entries(m.versions_seen).map(([E,v])=>Object.values(v).map(j=>[j,E])).flat().filter(([E,v])=>v!==Ft).sort(([E],[v])=>HO(E,v));de&&(de.length===1?ie=de[0][1]:de[de.length-1][0]!==de[de.length-2][0]&&(ie=de[de.length-1][1]))}if(ie===void 0)throw new vt('Ambiguous update, specify "asNode"');I.push({values:X,asNode:ie,taskId:Ee})}else for(const{asNode:X,values:ie,taskId:Ee}of d){if(X==null)throw new vt('"asNode" is required when applying multiple updates');I.push({values:ie,asNode:X,taskId:Ee})}const k=[];for(const{asNode:X,values:ie,taskId:Ee}of I){if(this.nodes[X]===void 0)throw new vt(`Node "${X.toString()}" does not exist`);const de=this.nodes[X].getWriters();if(!de.length)throw new vt(`No writers found for node "${X.toString()}"`);k.push({name:X,input:ie,proc:de.length>1?pr.from(de,{omitSequenceTags:!0}):de[0],writes:[],triggers:[Ft],id:Ee??ca("__interrupt__",m.id),writers:[]})}for(const X of k)await X.proc.invoke(X.input,ut({...f,store:(f==null?void 0:f.store)??this.store},{runName:f.runName??`${this.getName()}UpdateState`,configurable:{[Jr]:ie=>X.writes.push(...ie),[xi]:(ie,Ee=!1)=>Mu(m,T,X,ie,Ee)}}));for(const X of k){const ie=X.writes.filter(Ee=>Ee[0]!==Er);h!==void 0&&ie.length>0&&await r.putWrites(b,ie,X.id)}sr(m,T,k,r.getNextVersion.bind(this.checkpointer),this.triggerToNodes);const R=dh(g,m.channel_versions),x=await r.put(b,sa(m,T,y+1),{source:"update",step:y+1,parents:((oe=h==null?void 0:h.metadata)==null?void 0:oe.parents)??{}},R);for(const X of k){const ie=X.writes.filter(Ee=>Ee[0]===Er);ie.length>0&&await r.putWrites(x,ie,X.id)}return Ki(x,h?h.metadata:void 0)};let a=e;for(const{updates:l}of t)a=await i(a,l);return a}async updateState(e,t,r){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:r}]}])}_defaults(e){var T,A,I;const{debug:t,streamMode:r,inputKeys:s,outputKeys:i,interruptAfter:a,interruptBefore:o,...c}=e;let u=!0;const l=t!==void 0?t:this.debug;let d=i;d===void 0?d=this.streamChannelsAsIs:kS(d,this.channels);let f=s;f===void 0?f=this.inputChannels:kS(f,this.channels);const h=o??this.interruptBefore??[],m=a??this.interruptAfter??[];let g;r!==void 0?(g=Array.isArray(r)?r:[r],u=typeof r=="string"):(((T=e.configurable)==null?void 0:T.__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&&((A=e.configurable)==null?void 0:A.__pregel_checkpointer)!==void 0)y=e.configurable[hs];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"})(),S=e.durability??w??((I=e==null?void 0:e.configurable)==null?void 0:I.__pregel_durability)??"async";return[l,g,f,d,c,h,m,y,b,u,_,S]}async stream(e,t){var a;const r=new AbortController,s={recursionLimit:(a=this.config)==null?void 0:a.recursionLimit,...t,signal:al(t==null?void 0:t.signal,r.signal).signal},i=await super.stream(e,s);return new Om((t==null?void 0:t.encoding)==="text/event-stream"?JV(i):i,r)}streamEvents(e,t,r){var a,o;if(t.version==="v3")return Zi(this,Df,vC).call(this,e,t);const s=new AbortController,i={recursionLimit:(a=this.config)==null?void 0:a.recursionLimit,...t,callbacks:eV((o=this.config)==null?void 0:o.callbacks,t==null?void 0:t.callbacks),signal:al(t==null?void 0:t.signal,s.signal).signal};return new Om(super.streamEvents(e,i,r),s)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){var B;const r="version"in(t??{})?void 0:(t==null?void 0:t.encoding)??void 0,s=t==null?void 0:t.subgraphs,i=(t==null?void 0:t.version)==="v3",a=GO(this.config,t);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,m,g,y,b,_,w,S]=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 T=new uC({modes:new Set(d)});if(this.checkpointer===!0){h.configurable??(h.configurable={});const F=h.configurable.checkpoint_ns??"";h.configurable[ls]=F.split("|").map(Y=>Y.split(":")[0]).join("|")}if(d.includes("messages")){const F=i?new oZ(Z=>T.push(Z)):new sZ(Z=>T.push(Z)),{callbacks:Y}=h;if(Y===void 0)h.callbacks=[F];else if(Array.isArray(Y))h.callbacks=Y.concat(F);else{const Z=Y.copy();Z.addHandler(F,!0),h.callbacks=Z}}if(d.includes("tools")){const F=new WV(Z=>T.push(Z)),{callbacks:Y}=h;if(Y===void 0)h.callbacks=[F];else if(Array.isArray(Y))h.callbacks=Y.concat(F);else{const Z=Y.copy();Z.addHandler(F,!0),h.callbacks=Z}}h.writer??(h.writer=F=>{var Z,ge,M;if(!d.includes("custom"))return;const Y=(M=(ge=(Z=G8())==null?void 0:Z.configurable)==null?void 0:ge[ls])==null?void 0:M.split("|").slice(0,-1);T.push([Y??[],"custom",F])}),h.interrupt??(h.interrupt=this.userInterrupt??NZ),h.serverInfo==null&&(h.serverInfo=UZ(h)),h.control??(h.control=new nV);const A={tracerInheritableMetadata:BZ(h)},I=await((B=await An._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,A))==null?void 0:B.handleChainStart(this.toJSON(),Q8(e,"input"),c,void 0,void 0,void 0,(h==null?void 0:h.runName)??this.getName())),k=wp(this.channels);let R,x;const U=(async()=>{var F,Y,Z;try{R=await nZ.initialize({input:o,config:h,checkpointer:y,nodes:this.nodes,channelSpecs:k,outputKeys:f,streamKeys:this.streamChannelsAsIs,store:b,cache:w,stream:T,interruptAfter:g,interruptBefore:m,manager:I,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:S});const ge=new mZ({loop:R,nodeFinished:(F=h.configurable)==null?void 0:F[y3]});t!=null&&t.subgraphs&&(R.config.configurable={...R.config.configurable,[iw]:R.stream}),await this._runLoop({loop:R,runner:ge,debug:l,config:h}),S==="sync"&&await Promise.all((R==null?void 0:R.checkpointerPromises)??[])}catch(ge){x=ge}finally{try{R&&(await((Y=R.store)==null?void 0:Y.stop()),await((Z=R.cache)==null?void 0:Z.stop())),await Promise.all((R==null?void 0:R.checkpointerPromises)??[])}catch(ge){x=x??ge}x?(await new Promise(ge=>{queueMicrotask(ge)}),T.error(x)):T.close()}})();try{for await(const F of T){if(F===void 0)throw new Error("Data structure error.");const[Y,Z,ge]=F,M="version"in(t??{});if(d.includes(Z)||Z==="checkpoints"&&Bw(ge)&&(i||M&&s&&d.includes("values"))){if(r==="text/event-stream"){s?yield[Y,Z,ge]:yield[null,Z,ge];continue}s&&!_?yield[Y,Z,ge]:_?s?yield[Y,ge]:yield ge:yield[Z,ge]}}}catch(F){throw await(I==null?void 0:I.handleChainError(x)),F}finally{await U}await(I==null?void 0:I.handleChainEnd((R==null?void 0:R.output)??{},c,void 0,void 0,void 0))}async invoke(e,t){const r=(t==null?void 0:t.streamMode)??"values",s={...t,outputKeys:(t==null?void 0:t.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"?cw(u)?o.push(u[Ft]):c=u:i.push(u);if(r==="values"){if(o.length>0){const u=o.flat(1);if(c==null)return{[Ft]:u};if(typeof c=="object")return{...c,[Ft]:u}}return c}return i}async _runLoop(e){const{loop:t,runner:r,debug:s,config:i}=e;let a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(const{task:o}of await t._matchCachedWrites())t._outputWrites(o.id,o.writes,!0);s&&zV(t.checkpointMetadata.step,t.channels,this.streamChannelsList),s&&R_(t.step,Object.values(t.tasks)),await r.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(o,c)=>{s&&FV(o,c,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status==="draining")throw t.control==null?new Error("Draining status requires run control"):new tx(t.control.drainReason??"shutdown");if(t.status==="out_of_steps")throw new T3([`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 t.finishAndHandleError(a))throw o}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){var e;await((e=this.cache)==null?void 0:e.clear([]))}},Df=new WeakSet,vC=async function(e,t){var l,d;const{version:r,encoding:s,transformers:i,...a}=t,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:BV,subgraphs:!0,encoding:void 0},c=this.stream(e,o),u=$Z({[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 Om(MZ(u),f)}return u},KT);function UZ(n){const e=n.metadata??{},t=n.configurable??{},r=t.assistant_id??e.assistant_id,s=t.graph_id??e.graph_id,i=t.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 zZ=new Set(["key","token","secret","password","auth"]);function FZ(n,e){const t=n.toLowerCase();let r=!1;for(const s of zZ)if(t.includes(s)){r=!0;break}return n.startsWith("__")||!(typeof e=="string"||typeof e=="number"||typeof e=="boolean")||r}function BZ(n){const e=n.configurable;if(!e)return;const t={};for(const[r,s]of Object.entries(e))FZ(r,s)||(t[r]=s);return Object.keys(t).length>0?t:void 0}var SC=class{constructor(n){p(this,"path");p(this,"ends");Ge.isRunnable(n.path)?this.path=n.path:this.path=gn(n.path),this.ends=Array.isArray(n.pathMap)?n.pathMap.reduce((e,t)=>(e[t]=t,e),{}):n.pathMap}run(n,e){return Ln.registerWriter(new vs({name:"<branch_run>",trace:!1,func:async(t,r)=>{try{return await this._route(t,r,n,e)}catch(s){throw s.name===nx.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
356
|
+
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),s}}}))}async _route(n,e,t,r){let s=await this.path.invoke(r?r(e):n,e);Array.isArray(s)||(s=[s]);let i;if(this.ends?i=s.map(a=>Gn(a)?a:this.ends[a]):i=s,i.some(a=>!a))throw new Error("Branch condition returned unknown or null destination");if(i.filter(Gn).some(a=>a.node==="__end__"))throw new vt("Cannot send a packet to the END node");return await t(i,e)??n}},HZ=class{constructor(){p(this,"nodes");p(this,"edges");p(this,"branches");p(this,"entryPoint");p(this,"compiled",!1);this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(n){this.compiled&&console.warn(n)}get allEdges(){return this.edges}addNode(...n){function e(r){return r.length>=1&&typeof r[0]!="string"}const t=e(n)?Array.isArray(n[0])?n[0]:Object.entries(n[0]):[[n[0],n[1],n[2]]];if(t.length===0)throw new Error("No nodes provided in `addNode`");for(const[r,s,i]of t){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=gn(s);this.nodes[r]={runnable:a,metadata:i==null?void 0:i.metadata,subgraphs:zw(a)?[a]:i==null?void 0:i.subgraphs,ends:i==null?void 0:i.ends}}return this}addEdge(n,e){if(this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),n==="__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(([t])=>t===n)&&!("channels"in this))throw new Error(`Already found path for ${n}. For multiple edges, use StateGraph.`);return this.edges.add([n,e]),this}addConditionalEdges(n,e,t){var i,a;const r=typeof n=="object"?n:{source:n,path:e,pathMap:t};this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."),Ge.isRunnable(r.path)||(r.path=gn(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 \`${n}\``);return(i=this.branches)[a=r.source]??(i[a]={}),this.branches[r.source][s]=new SC(r),this}setEntryPoint(n){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(hn,n)}setFinishPoint(n){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(n,bt)}compile({checkpointer:n,interruptBefore:e,interruptAfter:t,name:r,transformers:s}={}){this.validate([...Array.isArray(e)?e:[],...Array.isArray(t)?t:[]]);const i=new AC({builder:this,checkpointer:n,interruptAfter:t,interruptBefore:e,autoValidate:!1,nodes:{},channels:{[hn]:new dc,[bt]:new dc},inputChannels:hn,outputChannels:bt,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(n){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 t=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))t.add(a);else{t.add(bt);for(const a of Object.keys(this.nodes))a!==r&&t.add(a)}for(const r of Object.values(this.nodes))for(const s of r.ends??[])t.add(s);if(Object.values(this.nodes).some(r=>r.isErrorHandler))for(const r of Object.keys(this.nodes))t.add(r);for(const r of Object.keys(this.nodes))if(!this.nodes[r].isErrorHandler&&!t.has(r))throw new x3([`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(`
|
|
357
|
+
`),{lc_error_code:"UNREACHABLE_NODE"});for(const r of t)if(r!=="__end__"&&!(r in this.nodes))throw new Error(`Found edge ending at unknown node \`${r}\``);if(n){for(const r of n)if(!(r in this.nodes))throw new Error(`Interrupt node \`${r}\` is not present`)}this.compiled=!0}},AC=class extends DZ{constructor({builder:e,...t}){super(t);p(this,"builder");this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new dc,this.nodes[e]=new il({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Ln([{channel:e,value:Ta}],[Kn])),this.streamChannels.push(e)}attachEdge(e,t){if(t==="__end__"){if(e==="__start__")throw new Error("Cannot have an edge from START to END");this.nodes[e].writers.push(new Ln([{channel:bt,value:Ta}],[Kn]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,r){e==="__start__"&&!this.nodes.__start__&&(this.nodes[hn]=jZ.subscribeTo(hn,{tags:[Kn]})),this.nodes[e].pipe(r.run(i=>new Ln(i.map(a=>Gn(a)?a:{channel:a==="__end__"?bt:`branch:${e}:${t}:${a}`,value:Ta}),[Kn])));const s=r.ends?Object.values(r.ends):Object.keys(this.nodes);for(const i of s)if(i!=="__end__"){const a=`branch:${e}:${t}:${i}`;this.channels[a]=new dc,this.nodes[i].triggers.push(a),this.nodes[i].channels.push(a)}}async getGraphAsync(e){var l,d,f,h;const t=e==null?void 0:e.xray,r=new Ju,s={[hn]:r.addNode({schema:wd()},hn)},i={};let a={};t&&(a=Object.fromEntries((await gi(this.getSubgraphsAsync())).filter(m=>IS(m[1]))));const o=[];function c(m,g,y,b=!1){if(g==="__end__"&&i.__end__===void 0&&(i[bt]=r.addNode({schema:wd()},bt)),s[m]!==void 0){if(i[g]===void 0)throw new Error(`End node ${g} not found!`);return o.push({src:m,dest:g,conditional:b}),r.addEdge(s[m],i[g],y!==g?y:void 0,b)}}for(const[m,g]of Object.entries(this.builder.nodes)){const y=Wt(m),b=g.runnable,_=g.metadata??{};if((l=this.interruptBefore)!=null&&l.includes(m)&&((d=this.interruptAfter)!=null&&d.includes(m))?_.__interrupt="before,after":(f=this.interruptBefore)!=null&&f.includes(m)?_.__interrupt="before":(h=this.interruptAfter)!=null&&h.includes(m)&&(_.__interrupt="after"),t){const w=typeof t=="number"?t-1:t,S=a[m]!==void 0?await a[m].getGraphAsync({...e,xray:w}):b.getGraph(e);if(S.trimFirstNode(),S.trimLastNode(),Object.keys(S.nodes).length>1){let I=function(R){return R?R.lc_runnable:!1},k=function(R,x){if(R!==void 0&&!wa(R))return R;if(I(x))try{let O=x.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return x.getName()}else return x.name??"UnknownSchema"};const[T,A]=r.extend(S,y);if(T===void 0)throw new Error(`Could not extend subgraph "${m}" due to missing entrypoint.`);A!==void 0&&(s[y]={name:k(A.id,A.data),...A}),i[y]={name:k(T.id,T.data),...T}}else{const T=r.addNode(b,y,_);s[y]=T,i[y]=T}}else{const w=r.addNode(b,y,_);s[y]=w,i[y]=w}}const u=[...this.builder.allEdges].sort(([m],[g])=>m<g?-1:g>m?1:0);for(const[m,g]of u)c(Wt(m),Wt(g));for(const[m,g]of Object.entries(this.builder.branches)){const y={...Object.fromEntries(Object.keys(this.builder.nodes).filter(b=>b!==m).map(b=>[Wt(b),Wt(b)])),[bt]:bt};for(const b of Object.values(g)){let _;b.ends!==void 0?_=b.ends:_=y;for(const[w,S]of Object.entries(_))c(Wt(m),Wt(S),w,!0)}}for(const[m,g]of Object.entries(this.builder.nodes))if(g.ends!==void 0)for(const y of g.ends)c(Wt(m),Wt(y),void 0,!0);return xS(this.builder.nodes,o,c),r}getGraph(e){var l,d,f,h;const t=e==null?void 0:e.xray,r=new Ju,s={[hn]:r.addNode({schema:wd()},hn)},i={};let a={};t&&(a=Object.fromEntries(ao(this.getSubgraphs()).filter(m=>IS(m[1]))));const o=[];function c(m,g,y,b=!1){if(g==="__end__"&&i.__end__===void 0&&(i[bt]=r.addNode({schema:wd()},bt)),s[m]!==void 0){if(i[g]===void 0)throw new Error(`End node ${g} not found!`);return o.push({src:m,dest:g,conditional:b}),r.addEdge(s[m],i[g],y!==g?y:void 0,b)}}for(const[m,g]of Object.entries(this.builder.nodes)){const y=Wt(m),b=g.runnable,_=g.metadata??{};if((l=this.interruptBefore)!=null&&l.includes(m)&&((d=this.interruptAfter)!=null&&d.includes(m))?_.__interrupt="before,after":(f=this.interruptBefore)!=null&&f.includes(m)?_.__interrupt="before":(h=this.interruptAfter)!=null&&h.includes(m)&&(_.__interrupt="after"),t){const w=typeof t=="number"?t-1:t,S=a[m]!==void 0?a[m].getGraph({...e,xray:w}):b.getGraph(e);if(S.trimFirstNode(),S.trimLastNode(),Object.keys(S.nodes).length>1){let I=function(R){return R?R.lc_runnable:!1},k=function(R,x){if(R!==void 0&&!wa(R))return R;if(I(x))try{let O=x.getName();return O=O.startsWith("Runnable")?O.slice(8):O,O}catch{return x.getName()}else return x.name??"UnknownSchema"};const[T,A]=r.extend(S,y);if(T===void 0)throw new Error(`Could not extend subgraph "${m}" due to missing entrypoint.`);A!==void 0&&(s[y]={name:k(A.id,A.data),...A}),i[y]={name:k(T.id,T.data),...T}}else{const T=r.addNode(b,y,_);s[y]=T,i[y]=T}}else{const w=r.addNode(b,y,_);s[y]=w,i[y]=w}}const u=[...this.builder.allEdges].sort(([m],[g])=>m<g?-1:g>m?1:0);for(const[m,g]of u)c(Wt(m),Wt(g));for(const[m,g]of Object.entries(this.builder.branches)){const y={...Object.fromEntries(Object.keys(this.builder.nodes).filter(b=>b!==m).map(b=>[Wt(b),Wt(b)])),[bt]:bt};for(const b of Object.values(g)){let _;b.ends!==void 0?_=b.ends:_=y;for(const[w,S]of Object.entries(_))c(Wt(m),Wt(S),w,!0)}}for(const[m,g]of Object.entries(this.builder.nodes))if(g.ends!==void 0)for(const y of g.ends)c(Wt(m),Wt(y),void 0,!0);return xS(this.builder.nodes,o,c),r}};function IS(n){return typeof n.attachNode=="function"&&typeof n.attachEdge=="function"}function Wt(n){return n==="subgraph"?`"${n}"`:n}function xS(n,e,t){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(n).find(c=>Wt(c)===a);o!==void 0&&((i=n[o])!=null&&i.isErrorHandler)||t(a,bt)}}const ua=(n,e)=>n.size===e.size&&[...n].every(t=>e.has(t));var VZ=class TC extends Hi{constructor(t){super();p(this,"lc_graph_name","NamedBarrierValue");p(this,"names");p(this,"seen");this.names=t,this.seen=new Set}fromCheckpoint(t){const r=new TC(this.names);return typeof t<"u"&&(r.seen=new Set(t)),r}update(t){let r=!1;for(const s of t)if(this.names.has(s))this.seen.has(s)||(this.seen.add(s),r=!0);else throw new vt(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!ua(this.names,this.seen))throw new on}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&ua(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&ua(this.names,this.seen)}},ZZ=class EC extends Hi{constructor(t){super();p(this,"lc_graph_name","NamedBarrierValueAfterFinish");p(this,"names");p(this,"seen");p(this,"finished");this.names=t,this.seen=new Set,this.finished=!1}fromCheckpoint(t){const r=new EC(this.names);if(typeof t<"u"){const[s,i]=t;r.seen=new Set(s),r.finished=i}return r}update(t){let r=!1;for(const s of t)if(this.names.has(s)&&!this.seen.has(s))this.seen.add(s),r=!0;else if(!this.names.has(s))throw new vt(`Value ${JSON.stringify(s)} not in names ${JSON.stringify(this.names)}`);return r}get(){if(!this.finished||!ua(this.names,this.seen))throw new on}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&ua(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&ua(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&ua(this.names,this.seen)}};function lu(n){return typeof n=="object"&&n!==null&&"~standard"in n&&typeof n["~standard"]=="object"&&n["~standard"]!==null&&"validate"in n["~standard"]}function KZ(n){return typeof n=="object"&&n!==null&&"~standard"in n&&typeof n["~standard"]=="object"&&n["~standard"]!==null&&"jsonSchema"in n["~standard"]}function Wa(n){if(KZ(n))try{return n["~standard"].jsonSchema.input({target:"draft-07"})}catch{return}}function qa(n){if(n!=null&&lu(n))try{const e=n["~standard"].validate(void 0);if(e&&typeof e=="object"&&!("then"in e&&typeof e.then=="function")){const t=e;if(!t.issues){const r=t.value;return()=>r}}}catch{}}const Pm=Symbol.for("langgraph.channel.missing");var WZ=class kC extends Hi{constructor(t){super();p(this,"lc_graph_name","UntrackedValue");p(this,"guard");p(this,"_value",Pm);p(this,"initialValueFactory");this.guard=(t==null?void 0:t.guard)??!0,this.initialValueFactory=t==null?void 0:t.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new kC({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(t){if(t.length===0)return!1;if(t.length!==1&&this.guard)throw new vt("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=t[t.length-1],!0}get(){if(this._value===Pm)throw new on;return this._value}checkpoint(){}isAvailable(){return this._value!==Pm}};const Nm=Symbol.for("langgraph.state.reduced_value");var WT,oo=(WT=Nm,class{constructor(n,e){p(this,WT,!0);p(this,"valueSchema");p(this,"inputSchema");p(this,"reducer");p(this,"jsonSchemaExtra");this.reducer=e.reducer,this.jsonSchemaExtra=e.jsonSchemaExtra,this.valueSchema=n,this.inputSchema="inputSchema"in e?e.inputSchema:n,this.jsonSchemaExtra=e.jsonSchemaExtra}static isInstance(n){return typeof n=="object"&&n!==null&&Nm in n&&n[Nm]===!0}});const OS=Symbol.for("langgraph.state.untracked_value");var qT,Mc=(qT=OS,class{constructor(n,e){p(this,qT,!0);p(this,"schema");p(this,"guard");this.schema=n,this.guard=(e==null?void 0:e.guard)??!0}static isInstance(n){return typeof n=="object"&&n!==null&&OS in n}});const Mm=Symbol.for("langgraph.state.state_schema");var GT,Si=(GT=Mm,class{constructor(n){p(this,GT,!0);this.fields=n}getChannels(){const n={};for(const[e,t]of Object.entries(this.fields))if(oo.isInstance(t)){const r=qa(t.valueSchema);n[e]=new df(t.reducer,r)}else if(Mc.isInstance(t)){const r=t.schema?qa(t.schema):void 0;n[e]=new WZ({guard:t.guard,initialValueFactory:r})}else if(lu(t))n[e]=new bp(qa(t));else throw new Error(`Invalid state field "${e}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return n}getJsonSchema(){const n={},e=[];for(const[t,r]of Object.entries(this.fields)){let s;if(oo.isInstance(r)?(s=Wa(r.valueSchema),r.jsonSchemaExtra&&(s={...s??{},...r.jsonSchemaExtra})):Mc.isInstance(r)?s=r.schema?Wa(r.schema):void 0:lu(r)&&(s=Wa(r)),s){n[t]=s;let i=!1;oo.isInstance(r)?i=qa(r.valueSchema)!==void 0:Mc.isInstance(r)?i=r.schema?qa(r.schema)!==void 0:!1:i=qa(r)!==void 0,i||e.push(t)}}return{type:"object",properties:n,required:e.length>0?e:void 0}}getInputJsonSchema(){const n={};for(const[e,t]of Object.entries(this.fields)){let r;oo.isInstance(t)?(r=Wa(t.inputSchema),t.jsonSchemaExtra&&(r={...r??{},...t.jsonSchemaExtra})):Mc.isInstance(t)?r=t.schema?Wa(t.schema):void 0:lu(t)&&(r=Wa(t)),r&&(n[e]=r)}return{type:"object",properties:n}}getChannelKeys(){return Object.entries(this.fields).map(([n])=>n)}getAllKeys(){return Object.keys(this.fields)}async validateInput(n){if(n==null||typeof n!="object")return n;const e={};for(const[t,r]of Object.entries(n)){const s=this.fields[t];if(s===void 0){e[t]=r;continue}let i;if(oo.isInstance(s)){const[a,o]=Xu(r);if(a){i=s.valueSchema;const c=await i["~standard"].validate(o);if(c.issues)throw new Error(`Validation failed for field "${t}": ${JSON.stringify(c.issues)}`);e[t]={[ow]:c.value};continue}i=s.inputSchema}else Mc.isInstance(s)?i=s.schema:lu(s)&&(i=s);if(i){const a=await i["~standard"].validate(r);if(a.issues)throw new Error(`Validation failed for field "${t}": ${JSON.stringify(a.issues)}`);e[t]=a.value}else e[t]=r}return e}static isInstance(n){return typeof n=="object"&&n!==null&&Mm in n&&n[Mm]===!0}});function Zw(n,e){const t=Array.isArray(n)?n:[n],r=Array.isArray(e)?e:[e],s=t.map(ys),i=r.map(ys);for(const l of s)(l.id===null||l.id===void 0)&&(l.id=Ni(),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=Ni(),d.lc_kwargs.id=d.id),ya.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)ya.isInstance(l)?u.add(l.id):(u.delete(l.id),o[d]=l);else{if(ya.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 oo(y_().default(()=>[]),{inputSchema:y_(),reducer:Zw,jsonSchemaExtra:{langgraph_type:"messages",description:"A list of chat messages"}});var qZ=class{constructor(){p(this,"_map",new Map);p(this,"_extensionCache",new Map)}get(n){return this._map.get(n)}extend(n,e){const t=this.get(n);this._map.set(n,e(t))}remove(n){return this._map.delete(n),this}has(n){return this._map.has(n)}getChannelsForSchema(n){const e={},t=nc(n);for(const[r,s]of Object.entries(t)){const i=this.get(s);i!=null&&i.reducer?e[r]=new df(i.reducer.fn,i.default):e[r]=new bp(i==null?void 0:i.default)}return e}getExtendedChannelSchemas(n,e){if(Object.keys(e).length===0)return n;const t=Object.entries(e).filter(([,i])=>i===!0).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}:${a}`).join("|"),r=this._extensionCache.get(t)??new Map;if(r.has(n))return r.get(n);let s=n;if(e.withReducerSchema||e.withJsonSchemaExtrasAsDescription){const i=Object.entries(nc(n)).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=tc(u)??tc(o),f=JSON.stringify({...c.jsonSchemaExtra,description:d});u=u.describe(`lg:${f}`)}return[a,u]});s=TI(n,Object.fromEntries(i)),Ht(s)&&(s._def.unknownKeys="strip")}return e.asPartial&&(s=xu(s)),r.set(n,s),this._extensionCache.set(t,r),s}};const IC=new qZ;function co(n){return n==null?!1:!!(Si.isInstance(n)||ir(n)||typeof n=="object"&&"lc_graph_name"in n&&n.lc_graph_name==="AnnotationRoot"||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0&&Object.values(n).every(e=>typeof e=="function"||VO(e)))}function GZ(n){if(typeof n!="object"||n==null)return!1;const e=n,t="state"in e&&co(e.state),r="stateSchema"in e&&co(e.stateSchema),s="input"in e&&co(e.input);return!(!t&&!r&&!s||"input"in e&&e.input!=null&&!co(e.input)||"output"in e&&e.output!=null&&!co(e.output))}const Fs="__root__",Ga="__default_error_handler__",mf=Symbol.for("langgraph.state.partial");var JZ=class extends HZ{constructor(e,t){super();p(this,"channels",{});p(this,"waitingEdges",new Set);p(this,"_schemaDefinition");p(this,"_schemaRuntimeDefinition");p(this,"_inputDefinition");p(this,"_inputRuntimeDefinition");p(this,"_outputDefinition");p(this,"_outputRuntimeDefinition");p(this,"_schemaDefinitions",new Map);p(this,"_metaRegistry",IC);p(this,"_configSchema");p(this,"_configRuntimeSchema");p(this,"_interrupt");p(this,"_writer");p(this,"_nodeDefaults",{});const r=this._normalizeToStateGraphInit(e,t),s=r.state??r.stateSchema??r.input;if(!s)throw new gm;const i=this._getChannelsFromSchema(s);this._schemaDefinition=i,Si.isInstance(s)?this._schemaRuntimeDefinition=s:ir(s)&&(this._schemaRuntimeDefinition=s),r.input?Si.isInstance(r.input)?this._inputRuntimeDefinition=r.input:ir(r.input)?this._inputRuntimeDefinition=r.input:this._inputRuntimeDefinition=mf:this._inputRuntimeDefinition=mf,r.output?Si.isInstance(r.output)?this._outputRuntimeDefinition=r.output:ir(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&&ir(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=n_(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 vs({func:(t,r)=>{var i;const s=(i=r==null?void 0:r.configurable)==null?void 0:i[r_];return e(t,s,r)},name:Ga,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(GZ(e)){if(ir(t)||k_.isInstance(t))return{...e,context:t};const r=t;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(co(e)){if(ir(t)||k_.isInstance(t))return{state:e,context:t};const r=t;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(QZ(e))return{state:YZ(e.channels)};throw new gm}_getChannelsFromSchema(e){if(Si.isInstance(e))return e.getChannels();if(ir(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 gm("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.")}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(r=>[r,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(const[t,r]of Object.entries(e)){let s;if(typeof r=="function"?s=r():s=r,this.channels[t]!==void 0){if(!this.channels[t].equals(s)&&s.lc_graph_name!=="LastValue")throw new Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=s}}}addNode(...e){function t(s){return s.length>=1&&typeof s[0]!="string"}const r=t(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;Ge.isRunnable(i)?c=i:typeof i=="function"?c=new vs({func:i,name:s,trace:!1}):c=gn(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,m={runnable:new vs({func:(g,y)=>{var _;const b=(_=y==null?void 0:y.configurable)==null?void 0:_[r_];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]=m}const f={runnable:c,retryPolicy:a==null?void 0:a.retryPolicy,cachePolicy:l,timeout:n_(a==null?void 0:a.timeout),metadata:a==null?void 0:a.metadata,input:o??this._schemaDefinition,subgraphs:zw(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,t){if(typeof e=="string")return super.addEdge(e,t);this.compiled&&console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.");for(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(t==="__end__")throw new Error("END cannot be an end node");if(!Object.keys(this.nodes).some(r=>r===t))throw new Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){const t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw new Error("Sequence requires at least one node.");let r;for(const[s,i,a]of t){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:t,cache:r,interruptBefore:s,interruptAfter:i,name:a,description:o,transformers:c}={}){const u=this._createDefaultErrorHandlerSpec();if(u!==void 0){if(Ga in this.nodes)throw new Error(`Cannot apply a default error handler: the reserved node name \`${Ga}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[Ga]=u}try{return this._compileResolved({checkpointer:e,store:t,cache:r,interruptBefore:s,interruptAfter:i,name:a,description:o,transformers:c,defaultErrorHandlerNode:u!==void 0?Ga:void 0})}finally{u!==void 0&&delete this.nodes[Ga]}}_compileResolved({checkpointer:e,store:t,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]===Fs?Fs:l,f=Object.keys(this.channels),h=f.length===1&&f[0]===Fs?Fs:f,m=this._interrupt,g=new XZ({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:s,autoValidate:!1,nodes:{},channels:{...this.channels,[hn]:new dc},inputChannels:hn,outputChannels:d,streamChannels:h,streamMode:"updates",store:t,cache:r,name:a,description:o,userInterrupt:m,streamTransformers:c});g.attachNode(hn);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 S=w.isErrorHandler===!0,T=b?{...w,retryPolicy:w.retryPolicy??y.retryPolicy,cachePolicy:S||w.cachePolicy===!1?void 0:w.cachePolicy??y.cachePolicy,timeout:w.timeout??y.timeout,errorHandlerNode:!S&&u!==void 0&&w.errorHandlerNode===void 0?u:w.errorHandlerNode}:w;g.attachNode(_,T)}g.attachBranch(hn,Y0,CS(),{withReader:!1});for(const[_]of Object.entries(this.nodes))g.attachBranch(_,Y0,CS(),{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[S,T]of Object.entries(w))g.attachBranch(_,S,T);return g.validate()}};function YZ(n){const e={};for(const[t,r]of Object.entries(n))e[t]=I_(r);return e}var XZ=class extends AC{constructor({description:e,...t}){super(t);p(this,"description");p(this,"_metaRegistry",IC);this.description=e}attachNode(e,t){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(rn(u))return u.graph===cr.PARENT?null:u._updateAsTuples();if(Array.isArray(u)&&u.length>0&&u.some(l=>rn(l))){const l=[];for(const d of u)if(rn(d)){if(d.graph===cr.PARENT)continue;l.push(...d._updateAsTuples())}else l.push([Fs,d]);return l}else if(u!=null)return[[Fs,u]];return null}const i=e,a=async u=>{if(u==null||u.length===0)return u;const l=this.builder._schemaRuntimeDefinition;if(Si.isInstance(l)){const d=new Set(l.getChannelKeys());return Promise.all(u.map(async([f,h])=>{if(!d.has(f))return[f,h];const m=await l.validateInput({[f]:h});return[f,Object.prototype.hasOwnProperty.call(m,f)?m[f]:h]}))}if(ir(l)){const d=new Set(Object.keys(nc(l)));if(u.filter(([m])=>d.has(m)).length===0)return u;const f=xu(this._metaRegistry.getExtendedChannelSchemas(l,{withReducerSchema:!0})),h=xu(l);return u.map(([m,g])=>{if(!d.has(m))return[m,g];const[y,b]=Xu(g);if(y){const w=so(h,{[m]:b});return[m,Object.prototype.hasOwnProperty.call(w,m)?{[ow]:w[m]}:g]}const _=so(f,{[m]:g});return[m,Object.prototype.hasOwnProperty.call(_,m)?_[m]:g]})}return u};async function o(u){if(u){if(rn(u))return u.graph===cr.PARENT?null:a(u._updateAsTuples().filter(([l])=>r.includes(l)));if(Array.isArray(u)&&u.length>0&&u.some(rn)){const l=[];for(const d of u)if(rn(d)){if(d.graph===cr.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 vt(`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:Ta,mapper:new vs({func:r.length&&r[0]===Fs?s:o,trace:!1,recurse:!1})}];if(e==="__start__")this.nodes[e]=new il({tags:[Kn],triggers:[hn],channels:[hn],writers:[new Ln(c,[Kn])]});else{const u=(t==null?void 0:t.input)??this.builder._schemaDefinition,l=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(u)).map(g=>[g,g])),d=Object.keys(l).length===1&&Fs in l,f=`branch:to:${e}`;this.channels[f]=t!=null&&t.defer?new B8:new dc(!1);const h=t==null?void 0:t.cachePolicy,m=h===!1?void 0:h;this.nodes[e]=new il({triggers:[f],channels:d?Object.keys(l):l,writers:[new Ln(c,[Kn])],mapper:d?void 0:g=>Object.fromEntries(Object.entries(g).filter(([y])=>y in l)),bound:t==null?void 0:t.runnable,metadata:t==null?void 0:t.metadata,retryPolicy:t==null?void 0:t.retryPolicy,cachePolicy:m,timeout:t==null?void 0:t.timeout,subgraphs:t==null?void 0:t.subgraphs,ends:t==null?void 0:t.ends,isErrorHandler:t==null?void 0:t.isErrorHandler,errorHandlerNode:t==null?void 0:t.errorHandlerNode})}}attachEdge(e,t){if(t!=="__end__"){if(typeof e=="string")this.nodes[e].writers.push(new Ln([{channel:`branch:to:${t}`,value:null}],[Kn]));else if(Array.isArray(e)){const r=`join:${e.join("+")}:${t}`;this.channels[r]=this.builder.nodes[t].defer?new ZZ(new Set(e)):new VZ(new Set(e)),this.nodes[t].triggers.push(r);for(const s of e)this.nodes[s].writers.push(new Ln([{channel:r,value:s}],[Kn]))}}}attachBranch(e,t,r,s={withReader:!0}){const i=async(a,o)=>{const c=a.filter(l=>l!==bt);if(!c.length)return;const u=c.map(l=>Gn(l)?l:{channel:l==="__end__"?l:`branch:to:${l}`,value:e});await Ln.doWrite({...o,tags:(o.tags??[]).concat([Kn])},u)};this.nodes[e].writers.push(r.run(i,s.withReader?a=>X8.doRead(a,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;const t=this.builder._inputRuntimeDefinition,r=this.builder._schemaRuntimeDefinition;if(Si.isInstance(t)){if(rn(e)){const i=e;return e.update&&(i.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),i}return await t.validateInput(e)}if(t===mf&&Si.isInstance(r)){if(rn(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(ir(t))return i(t);if(t===mf)return ir(r)?xu(i(r)):void 0})();if(rn(e)){const i=e;if(e.update&&s!=null){const a=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,o=so(s,a);i.update=Object.fromEntries(Object.keys(a).map(c=>[c,o[c]]))}return i}return s!=null?so(s,e):e}isInterrupted(e){return cw(e)}async _validateContext(e){const t=this.builder._configRuntimeSchema;return ir(t)&&so(t,e),e}};function QZ(n){return typeof n=="object"&&n!==null&&n.channels!==void 0}function eK(n){if(Gn(n))return[n];const e=[];rn(n)?e.push(n):Array.isArray(n)&&e.push(...n.filter(rn));const t=[];for(const r of e){if(r.graph===cr.PARENT)throw new rx(r);Gn(r.goto)||typeof r.goto=="string"?t.push(r.goto):Array.isArray(r.goto)&&t.push(...r.goto)}return t}function CS(){return new SC({path:new vs({func:eK,tags:[Kn],trace:!1,recurse:!1,name:"<control_branch>"})})}const xC=n=>Array.isArray(n)&&n.every(Rt),tK=n=>typeof n=="object"&&n!=null&&"messages"in n&&xC(n.messages),nK=n=>typeof n=="object"&&n!=null&&"lg_tool_call"in n;var rK=class extends vs{constructor(e,t){const{name:r,tags:s,handleToolErrors:i}=t??{};super({name:r,tags:s,func:(a,o)=>this.run(a,o)});p(this,"tools");p(this,"handleToolErrors",!0);p(this,"trace",!1);this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,t,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={...t,state:r,toolCallId:e.id??"",config:t,context:t.context,store:t.store??null,writer:t.writer??((i=t.configurable)==null?void 0:i.writer)??null},c=await s.invoke(a,o);return Rt(c)&&c.getType()==="tool"||rn(c)?c:new _n({status:"success",name:s.name,content:typeof c=="string"?c:JSON.stringify(c),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||oa(a))throw a;return new _n({status:"error",content:`Error: ${a.message}
|
|
358
|
+
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){var a;let r;if(nK(e)){const{lg_tool_call:o,...c}=e;r=[await this.runTool(o,t,c)]}else{let o;if(xC(e))o=e;else if(tK(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(xr(d)){u=d;break}}if(u==null||!xr(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,t,e)))??[])}if(!r.some(rn))return Array.isArray(e)?r:{messages:r};const s=[];let i=null;for(const o of r)rn(o)?o.graph===cr.PARENT&&Array.isArray(o.goto)&&o.goto.every(c=>Gn(c))?i?i.goto.push(...o.goto):i=new cr({graph:cr.PARENT,goto:o.goto}):s.push(o):s.push(Array.isArray(e)?[o]:{messages:[o]});return i&&s.push(i),s}};const jm=/<name>(.*?)<\/name>/s,Lm=/<content>(.*?)<\/content>/s;function sK(n){if(!(Rt(n)&&(xr(n)||Go(n)&&Ph(n)))||!n.name)return n;const{name:e}=n;if(typeof n.content=="string")return new Ve({...Object.keys(n.lc_kwargs??{}).length>0?n.lc_kwargs:n,content:`<name>${e}</name><content>${n.content}</content>`,name:void 0});const t=[];let r=0;for(const s of n.content)typeof s=="string"?(r+=1,t.push(`<name>${e}</name><content>${s}</content>`)):typeof s=="object"&&"type"in s&&s.type==="text"?(r+=1,t.push({...s,text:`<name>${e}</name><content>${s.text}</content>`})):t.push(s);return r||t.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new Ve({...n.lc_kwargs,content:t,name:void 0})}function iK(n){if(!xr(n)||!n.content)return n;let e=[],t;if(Array.isArray(n.content))e=n.content.filter(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(jm),i=r.text.match(Lm);return s&&(!i||i[1]==="")?(t=s[1],!1):!0}return!0}).map(r=>{if(r.type==="text"&&typeof r.text=="string"){const s=r.text.match(jm),i=r.text.match(Lm);return!s||!i?r:(t=s[1],{...r,text:i[1]})}return r});else{const r=n.content,s=r.match(jm),i=r.match(Lm);if(!s||!i)return n;t=s[1],e=i[1]}return new Ve({...Object.keys(n.lc_kwargs??{}).length>0?n.lc_kwargs:n,content:e,name:t})}function $S(n,e){let t,r;if(e==="inline")t=sK,r=iK;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function s(i){return i.map(t)}return pr.from([an.from(s),n,an.from(r)])}function aK(n){if(typeof n=="string"||Rt(n)&&n._getType()==="system")return n;if(typeof n=="function")return async e=>n(e.messages);if(Ge.isRunnable(n))return an.from(e=>e.messages).pipe(n);throw new Error(`Unexpected type for messageModifier: ${typeof n}`)}const kd="prompt";function oK(n){let e;if(n==null)e=an.from(t=>t.messages).withConfig({runName:kd});else if(typeof n=="string"){const t=new hr(n);e=an.from(r=>[t,...r.messages??[]]).withConfig({runName:kd})}else if(Rt(n)&&n._getType()==="system")e=an.from(t=>[n,...t.messages]).withConfig({runName:kd});else if(typeof n=="function")e=an.from(n).withConfig({runName:kd});else if(Ge.isRunnable(n))e=n;else throw new Error(`Got unexpected type for 'prompt': ${typeof n}`);return e}function U_(n){return Ge.isRunnable(n)}function RS(n,e,t){if([n,e,t].filter(s=>s!=null).length>1)throw new Error("Expected only one of prompt, stateModifier, or messageModifier, got multiple values");let r=n;return e!=null?r=e:t!=null&&(r=aK(t)),oK(r)}function fc(n){return"invoke"in n&&typeof n.invoke=="function"&&"_modelType"in n}function pc(n){return"_queuedMethodOperations"in n&&"_model"in n&&typeof n._model=="function"}function PS(n){return fc(n)?"bindTools"in n&&typeof n.bindTools=="function":!1}async function cK(n,e){let t=n;if(pr.isRunnableSequence(t)&&(t=t.steps.find(o=>mn.isRunnableBinding(o)||fc(o)||pc(o))||t),pc(t)&&(t=await t._model()),!mn.isRunnableBinding(t))return!0;let r=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)?t.kwargs.tools??null:t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)?t.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=>U_(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 Dm=(n,e)=>{if(PS(n))return n.bindTools(e);if(mn.isRunnableBinding(n)&&PS(n.bound)){const t=n.bound.bindTools(e);return mn.isRunnableBinding(t)?new mn({bound:t.bound,config:{...n.config,...t.config},kwargs:{...n.kwargs,...t.kwargs},configFactories:t.configFactories??n.configFactories}):new mn({bound:t,config:n.config,kwargs:n.kwargs,configFactories:n.configFactories})}return null};async function uK(n,e){const t=Dm(n,e);if(t)return t;if(pc(n)){const r=Dm(await n._model(),e);if(r)return r}if(pr.isRunnableSequence(n)){const r=n.steps.findIndex(s=>mn.isRunnableBinding(s)||fc(s)||pc(s));if(r>=0){const s=Dm(n.steps[r],e);if(s){const i=n.steps.slice();return i.splice(r,1,s),pr.from(i)}}}throw new Error(`llm ${n} must define bindTools method.`)}async function lK(n){let e=n;if(pr.isRunnableSequence(e)&&(e=e.steps.find(t=>mn.isRunnableBinding(t)||fc(t)||pc(t))||e),pc(e)&&(e=await e._model()),mn.isRunnableBinding(e)&&(e=e.bound),!fc(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 dK=()=>Aa.Root({messages:Aa({reducer:Zw,default:()=>[]}),structuredResponse:Aa}),hK=Aa.Root({llmInputMessages:Aa({reducer:(n,e)=>Zw([],e),default:()=>[]})});function fK(n){const{llm:e,tools:t,messageModifier:r,stateModifier:s,prompt:i,stateSchema:a,contextSchema:o,checkpointSaver:c,checkpointer:u,interruptBefore:l,interruptAfter:d,store:f,responseFormat:h,preModelHook:m,postModelHook:g,name:y,description:b,version:_="v1",includeAgentName:w}=n;let S,T;Array.isArray(t)?(S=t,T=new rK(S.filter(U_))):(S=t.tools,T=t);let A=null;const I=async M=>{if(A)return A;let K;await cK(M,S)?K=await uK(M,S):K=M;const se=RS(i,s,r),oe=w==="inline"?$S(K,w):K;return A=se.pipe(oe),A},k=async(M,K,se)=>{const oe=await M(K,se);return RS(i,s,r).pipe(w==="inline"?$S(oe,w):oe)},R=new Set(S.filter(U_).filter(M=>"returnDirect"in M&&M.returnDirect).map(M=>M.name));function x(M){const{messages:K,llmInputMessages:se,...oe}=M;return se!=null&&se.length>0?{messages:se,...oe}:{messages:K,...oe}}const O=async(M,K)=>{if(h==null)throw new Error("Attempted to generate structured output with no passed response schema. Please contact us for help.");const se=[...M.messages];let oe;const X=typeof e=="function"?await e(M,K):await lK(e);if(!fc(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:Ee,schema:de,...E}=h;oe=X.withStructuredOutput(de,E),Ee!=null&&se.unshift(new hr({content:Ee}))}else oe=X.withStructuredOutput(h);const ie=await oe.invoke(se,K);if(ie==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:ie}},U=async(M,K)=>{const se=await(typeof e=="function"?await k(e,M,K):await I(e)).invoke(x(M),K);return se.name=y,se.lc_kwargs.name=y,{messages:[se]}},B=new JZ(a??dK(),o).addNode("tools",T);if(!("messages"in B._schemaDefinition))throw new Error("Missing required `messages` key in state schema.");const F=B,Y=M=>Object.fromEntries(Object.entries(M).filter(([K,se])=>se!=null));let Z="agent",ge;return m!=null?(F.addNode("pre_model_hook",m).addEdge("pre_model_hook","agent"),Z="pre_model_hook",ge=Aa.Root({...B._schemaDefinition,...hK.spec})):Z="agent",F.addNode("agent",U,{input:ge}).addEdge(hn,Z),g!=null&&F.addNode("post_model_hook",g).addEdge("agent","post_model_hook").addConditionalEdges("post_model_hook",M=>{var Ee;const{messages:K}=M,se=new Set(K.filter(_a).map(de=>de.tool_call_id));let oe;for(let de=K.length-1;de>=0;de-=1){const E=K[de];if(xr(E)){oe=E;break}}const X=((Ee=oe==null?void 0:oe.tool_calls)==null?void 0:Ee.filter(de=>de.id==null||!se.has(de.id)))??[],ie=K[K.length-1];return X.length>0?_==="v2"?X.map(de=>new Oa("tools",{...M,lg_tool_call:de})):"tools":ie&&_a(ie)?Z:h!=null?"generate_structured_response":bt},Y({tools:"tools",[Z]:Z,generate_structured_response:h!=null?"generate_structured_response":null,[bt]:h!=null?null:bt})),h!==void 0&&B.addNode("generate_structured_response",O).addEdge("generate_structured_response",bt),g==null&&F.addConditionalEdges("agent",M=>{var oe;const{messages:K}=M,se=K[K.length-1];return!xr(se)||!((oe=se.tool_calls)!=null&&oe.length)?h!=null?"generate_structured_response":bt:_==="v2"?se.tool_calls.map(X=>new Oa("tools",{...M,lg_tool_call:X})):"tools"},Y({tools:"tools",generate_structured_response:h!=null?"generate_structured_response":null,[bt]:h!=null?null:bt})),R.size>0?F.addConditionalEdges("tools",M=>{const K=M;for(let se=K.messages.length-1;se>=0;se-=1){const oe=K.messages[se];if(!_a(oe))break;if(oe.name!==void 0&&R.has(oe.name))return bt}return Z},Y({[Z]:Z,[bt]:bt})):F.addEdge("tools",Z),F.compile({checkpointer:u??c,interruptBefore:l,interruptAfter:d,store:f,name:y,description:b})}function Id(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
359
|
+
|
|
360
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
361
|
+
`,n}function Pe(n,e,t,r,s){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function N(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let OC=function(){const{crypto:n}=globalThis;if(n!=null&&n.randomUUID)return OC=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function z_(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const F_=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class we extends Error{}let kn=class B_ extends we{constructor(e,t,r,s){super(`${B_.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=t;const i=t;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,t,r){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new vp({message:r,cause:F_(t)});const i=t==null?void 0:t.error;return e===400?new CC(e,i,r,s):e===401?new $C(e,i,r,s):e===403?new RC(e,i,r,s):e===404?new PC(e,i,r,s):e===409?new NC(e,i,r,s):e===422?new MC(e,i,r,s):e===429?new jC(e,i,r,s):e>=500?new LC(e,i,r,s):new B_(e,i,r,s)}},ur=class extends kn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},vp=class extends kn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Sp=class extends vp{constructor({message:e}={}){super({message:e??"Request timed out."})}},CC=class extends kn{},$C=class extends kn{},RC=class extends kn{},PC=class extends kn{},NC=class extends kn{},MC=class extends kn{},jC=class extends kn{},LC=class extends kn{};class DC extends we{constructor(){super("Could not parse response content as the length limit was reached")}}class UC extends we{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class du extends Error{constructor(e){super(e)}}class zC extends kn{constructor(e,t,r){let s="OAuth2 authentication error",i;if(t&&typeof t=="object"){const a=t;i=a.error;const o=a.error_description;o&&typeof o=="string"?s=o:i&&(s=i)}super(e,t,s,r),this.error_code=i}}class pK extends we{constructor(e,t,r){super(e),this.provider=t,this.cause=r}}const mK=/^[a-z][a-z0-9+.-]*:/i,gK=n=>mK.test(n);let Vn=n=>(Vn=Array.isArray,Vn(n)),NS=Vn;function Kw(n){return typeof n!="object"?{}:n??{}}function MS(n){if(!n)return!0;for(const e in n)return!1;return!0}function _K(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function gh(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const yK=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new we(`${n} must be an integer`);if(e<0)throw new we(`${n} must be a positive integer`);return e},wK=n=>{try{return JSON.parse(n)}catch{return}},Kl=n=>new Promise(e=>setTimeout(e,n)),uo="6.42.0",bK=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function vK(){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 SK=()=>{var t;const n=vK();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":uo,"X-Stainless-OS":LS(Deno.build.os),"X-Stainless-Arch":jS(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":uo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":uo,"X-Stainless-OS":LS(globalThis.process.platform??"unknown"),"X-Stainless-Arch":jS(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=AK();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":uo,"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":uo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function AK(){if(typeof navigator>"u"||!navigator)return null;const n=[{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:t}of n){const r=t.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 jS=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",LS=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let DS;const TK=()=>DS??(DS=SK());function FC(){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 BC(...n){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(...n)}function HC(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return BC({start(){},async pull(t){const{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function VC(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function US(n){var r,s;if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await((s=(r=n[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const EK=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),ZC="RFC3986",KC=n=>String(n),zS={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:KC},kK="RFC1738";let H_=(n,e)=>(H_=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),H_(n,e));const ss=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),Um=1024,IK=(n,e,t,r,s)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="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+=Um){const c=i.length>=Um?i.slice(o,o+Um):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===kK&&(d===40||d===41)){u[u.length]=c.charAt(l);continue}if(d<128){u[u.length]=ss[d];continue}if(d<2048){u[u.length]=ss[192|d>>6]+ss[128|d&63];continue}if(d<55296||d>=57344){u[u.length]=ss[224|d>>12]+ss[128|d>>6&63]+ss[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=ss[240|d>>18]+ss[128|d>>12&63]+ss[128|d>>6&63]+ss[128|d&63]}a+=u.join("")}return a};function xK(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function FS(n,e){if(Vn(n)){const t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}const WC={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},qC=function(n,e){Array.prototype.push.apply(n,Vn(e)?e:[e])};let BS;const Gt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:IK,encodeValuesOnly:!1,format:ZC,formatter:KC,indices:!1,serializeDate(n){return(BS??(BS=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function OK(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const zm={};function GC(n,e,t,r,s,i,a,o,c,u,l,d,f,h,m,g,y,b){let _=n,w=b,S=0,T=!1;for(;(w=w.get(zm))!==void 0&&!T;){const x=w.get(n);if(S+=1,typeof x<"u"){if(x===S)throw new RangeError("Cyclic object value");T=!0}typeof w.get(zm)>"u"&&(S=0)}if(typeof u=="function"?_=u(e,_):_ instanceof Date?_=f==null?void 0:f(_):t==="comma"&&Vn(_)&&(_=FS(_,function(x){return x instanceof Date?f==null?void 0:f(x):x})),_===null){if(i)return c&&!g?c(e,Gt.encoder,y,"key",h):e;_=""}if(OK(_)||xK(_)){if(c){const x=g?e:c(e,Gt.encoder,y,"key",h);return[(m==null?void 0:m(x))+"="+(m==null?void 0:m(c(_,Gt.encoder,y,"value",h)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(_)))]}const A=[];if(typeof _>"u")return A;let I;if(t==="comma"&&Vn(_))g&&c&&(_=FS(_,c)),I=[{value:_.length>0?_.join(",")||null:void 0}];else if(Vn(u))I=u;else{const x=Object.keys(_);I=l?x.sort(l):x}const k=o?String(e).replace(/\./g,"%2E"):String(e),R=r&&Vn(_)&&_.length===1?k+"[]":k;if(s&&Vn(_)&&_.length===0)return R+"[]";for(let x=0;x<I.length;++x){const O=I[x],U=typeof O=="object"&&typeof O.value<"u"?O.value:_[O];if(a&&U===null)continue;const B=d&&o?O.replace(/\./g,"%2E"):O,F=Vn(_)?typeof t=="function"?t(R,B):R:R+(d?"."+B:"["+B+"]");b.set(n,S);const Y=new WeakMap;Y.set(zm,b),qC(A,GC(U,F,t,r,s,i,a,o,t==="comma"&&g&&Vn(_)?null:c,u,l,d,f,h,m,g,y,Y))}return A}function CK(n=Gt){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||Gt.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=ZC;if(typeof n.format<"u"){if(!H_(zS,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=zS[t];let s=Gt.filter;(typeof n.filter=="function"||Vn(n.filter))&&(s=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in WC?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=Gt.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:Gt.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:Gt.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:Gt.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:Gt.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?Gt.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:Gt.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:Gt.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:Gt.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:Gt.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:Gt.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:Gt.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:Gt.strictNullHandling}}function $K(n,e={}){let t=n;const r=CK(e);let s,i;typeof r.filter=="function"?(i=r.filter,t=i("",t)):Vn(r.filter)&&(i=r.filter,s=i);const a=[];if(typeof t!="object"||t===null)return"";const o=WC[r.arrayFormat],c=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);const u=new WeakMap;for(let f=0;f<s.length;++f){const h=s[f];r.skipNulls&&t[h]===null||qC(a,GC(t[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 RK(n){return $K(n,{arrayFormat:"brackets"})}function PK(n){let e=0;for(const s of n)e+=s.length;const t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}let HS;function Ww(n){let e;return(HS??(e=new globalThis.TextEncoder,HS=e.encode.bind(e)))(n)}let VS;function ZS(n){let e;return(VS??(e=new globalThis.TextDecoder,VS=e.decode.bind(e)))(n)}var Qn,er;let Ap=class{constructor(){Qn.set(this,void 0),er.set(this,void 0),Pe(this,Qn,new Uint8Array),Pe(this,er,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ww(e):e;Pe(this,Qn,PK([N(this,Qn,"f"),t]));const r=[];let s;for(;(s=NK(N(this,Qn,"f"),N(this,er,"f")))!=null;){if(s.carriage&&N(this,er,"f")==null){Pe(this,er,s.index);continue}if(N(this,er,"f")!=null&&(s.index!==N(this,er,"f")+1||s.carriage)){r.push(ZS(N(this,Qn,"f").subarray(0,N(this,er,"f")-1))),Pe(this,Qn,N(this,Qn,"f").subarray(N(this,er,"f"))),Pe(this,er,null);continue}const i=N(this,er,"f")!==null?s.preceding-1:s.preceding,a=ZS(N(this,Qn,"f").subarray(0,i));r.push(a),Pe(this,Qn,N(this,Qn,"f").subarray(s.index)),Pe(this,er,null)}return r}flush(){return N(this,Qn,"f").length?this.decode(`
|
|
362
|
+
`):[]}};Qn=new WeakMap,er=new WeakMap;Ap.NEWLINE_CHARS=new Set([`
|
|
363
|
+
`,"\r"]);Ap.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function NK(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function MK(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const gf={off:0,error:200,warn:300,info:400,debug:500},KS=(n,e,t)=>{if(n){if(_K(gf,n))return n;ln(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(gf))}`)}};function hu(){}function xd(n,e,t){return!e||gf[n]>gf[t]?hu:e[n].bind(e)}const jK={error:hu,warn:hu,info:hu,debug:hu};let WS=new WeakMap;function ln(n){const e=n.logger,t=n.logLevel??"off";if(!e)return jK;const r=WS.get(e);if(r&&r[0]===t)return r[1];const s={error:xd("error",e,t),warn:xd("warn",e,t),info:xd("info",e,t),debug:xd("debug",e,t)};return WS.set(e,[t,s]),s}const ta=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var jc;let ul=class fu{constructor(e,t,r){this.iterator=e,jc.set(this,void 0),this.controller=t,Pe(this,jc,r)}static fromSSEResponse(e,t,r,s){let i=!1;const a=r?ln(r):console;async function*o(){if(i)throw new we("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let c=!1;try{for await(const u of LK(e,t))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 kn(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 kn(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}c=!0}catch(u){if(z_(u))return;throw u}finally{c||t.abort()}}return new fu(o,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*i(){const o=new Ap,c=VC(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 we("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(z_(c))return;throw c}finally{o||t.abort()}}return new fu(a,t,r)}[(jc=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){const a=r.next();e.push(a),t.push(a)}return i.shift()}});return[new fu(()=>s(e),this.controller,N(this,jc,"f")),new fu(()=>s(t),this.controller,N(this,jc,"f"))]}toReadableStream(){const e=this;let t;return BC({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:i}=await t.next();if(i)return r.close();const a=Ww(JSON.stringify(s)+`
|
|
364
|
+
`);r.enqueue(a)}catch(s){r.error(s)}},async cancel(){var r;await((r=t.return)==null?void 0:r.call(t))}})}};async function*LK(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new we("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 we("Attempted to iterate over a response with no body");const t=new UK,r=new Ap,s=VC(n.body);for await(const i of DK(s))for(const a of r.decode(i)){const o=t.decode(a);o&&(yield o)}for(const i of r.flush()){const a=t.decode(i);a&&(yield a)}}async function*DK(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ww(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=MK(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}let UK=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(`
|
|
365
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=zK(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function zK(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function JC(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:i}=e,a=await(async()=>{var d;if(e.options.stream)return ln(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData):ul.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.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(t.headers.get("content-length")==="0")return;const h=await t.json();return YC(h,t)}return await t.text()})();return ln(n).debug(`[${r}] response parsed`,ta({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function YC(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var pu;let XC=class QC extends Promise{constructor(e,t,r=JC){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,pu.set(this,void 0),Pe(this,pu,e)}_thenUnwrap(e){return new QC(N(this,pu,"f"),this.responsePromise,async(t,r)=>YC(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(N(this,pu,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};pu=new WeakMap;var Od;let Tp=class{constructor(e,t,r,s){Od.set(this,void 0),Pe(this,Od,e),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new we("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,Od,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Od=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}},FK=class extends XC{constructor(e,t,r){super(e,t,async(s,i)=>new r(s,i.response,await JC(s,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}},Ui=class extends Tp{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}};class Pt extends Tp{constructor(e,t,r,s){super(e,t,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(),t=(r=e[e.length-1])==null?void 0:r.id;return t?{...this.options,query:{...Kw(this.options.query),after:t}}:null}}class wn extends Tp{constructor(e,t,r,s){super(e,t,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:{...Kw(this.options.query),after:e}}:null}}class ni extends Tp{constructor(e,t,r,s){super(e,t,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:{...Kw(this.options.query),after:e}}:null}}const BK={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},HK="urn:ietf:params:oauth:grant-type:token-exchange";class VK{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??FC()}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(),t={grant_type:HK,subject_token:e,subject_token_type:BK[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);const r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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 zC(r.status,c,r.headers):kn.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 e1=()=>{var n;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((n=e==null?void 0:e.versions)==null?void 0:n.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ju(n,e,t){return e1(),new File(n,e??"unknown_file",t)}function _h(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const qw=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Ep=async(n,e)=>V_(n.body)?{...n,body:await t1(n.body,e)}:n,gs=async(n,e)=>({...n,body:await t1(n.body,e)}),qS=new WeakMap;function ZK(n){const e=typeof n=="function"?n:n.fetch,t=qS.get(e);if(t)return t;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 qS.set(e,r),r}const t1=async(n,e)=>{if(!await ZK(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>Z_(t,r,s))),t},n1=n=>n instanceof Blob&&"name"in n,KK=n=>typeof n=="object"&&n!==null&&(n instanceof Response||qw(n)||n1(n)),V_=n=>{if(KK(n))return!0;if(Array.isArray(n))return n.some(V_);if(n&&typeof n=="object"){for(const e in n)if(V_(n[e]))return!0}return!1},Z_=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,ju([await t.blob()],_h(t)));else if(qw(t))n.append(e,ju([await new Response(HC(t)).blob()],_h(t)));else if(n1(t))n.append(e,t,_h(t));else if(Array.isArray(t))await Promise.all(t.map(r=>Z_(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>Z_(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},r1=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",WK=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&r1(n),qK=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function GK(n,e,t){if(e1(),n=await n,WK(n))return n instanceof File?n:ju([await n.arrayBuffer()],n.name);if(qK(n)){const s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),ju(await K_(s),e,t)}const r=await K_(n);if(e||(e=_h(n)),!(t!=null&&t.type)){const s=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(t={...t,type:s})}return ju(r,e,t)}async function K_(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(r1(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(qw(n))for await(const r of n)e.push(...await K_(r));else{const r=(t=n==null?void 0:n.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof n}${r?`; constructor: ${r}`:""}${JK(n)}`)}return e}function JK(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}let W=class{constructor(e){this._client=e}};function s1(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const GS=Object.freeze(Object.create(null)),YK=(n=s1)=>function(t,...r){if(t.length===1)return t[0];let s=!1;const i=[],a=t.reduce((l,d,f)=>{var g;/[?#]/.test(d)&&(s=!0);const h=r[f];let m=(s?encodeURIComponent:n)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??GS)??GS))==null?void 0:g.toString))&&(m=h+"",i.push({start:l.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":m)},""),o=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 m=" ".repeat(h.start-l),g="^".repeat(h.length);return l=h.start+h.length,f+m+g},"");throw new we(`Path parameters result in path with invalid segments:
|
|
366
|
+
${i.map(f=>f.error).join(`
|
|
367
|
+
`)}
|
|
368
|
+
${a}
|
|
369
|
+
${d}`)}return a},$=YK(s1);let i1=class extends W{list(e,t={},r){return this._client.getAPIList($`/chat/completions/${e}/messages`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}};function _f(n){return n!==void 0&&"function"in n&&n.function!==void 0}function XK(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function Gw(n){return(n==null?void 0:n.$brand)==="auto-parseable-response-format"}function Wl(n){return(n==null?void 0:n.$brand)==="auto-parseable-tool"}function QK(n,e){return!e||!a1(e)?{...n,choices:n.choices.map(t=>(o1(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Jw(n,e)}function Jw(n,e){const t=n.choices.map(r=>{var s;if(r.finish_reason==="length")throw new DC;if(r.finish_reason==="content_filter")throw new UC;return o1(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=>tW(e,i)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?eW(e,r.message.content):null}}});return{...n,choices:t}}function eW(n,e){var t,r;return((t=n.response_format)==null?void 0:t.type)!=="json_schema"?null:((r=n.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function tW(n,e){var r;const t=(r=n.tools)==null?void 0:r.find(s=>{var i;return _f(s)&&((i=s.function)==null?void 0:i.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Wl(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function nW(n,e){var r;if(!n||!("tools"in n)||!n.tools)return!1;const t=(r=n.tools)==null?void 0:r.find(s=>{var i;return _f(s)&&((i=s.function)==null?void 0:i.name)===e.function.name});return _f(t)&&(Wl(t)||(t==null?void 0:t.function.strict)||!1)}function a1(n){var e;return Gw(n.response_format)?!0:((e=n.tools)==null?void 0:e.some(t=>Wl(t)||t.type==="function"&&t.function.strict===!0))??!1}function o1(n){for(const e of n||[])if(e.type!=="function")throw new we(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function rW(n){for(const e of n??[]){if(e.type!=="function")throw new we(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new we(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const yf=n=>(n==null?void 0:n.role)==="assistant",c1=n=>(n==null?void 0:n.role)==="tool";var W_,yh,wh,mu,gu,bh,_u,Ns,yu,wf,bf,lo,u1;class Yw{constructor(){W_.add(this),this.controller=new AbortController,yh.set(this,void 0),wh.set(this,()=>{}),mu.set(this,()=>{}),gu.set(this,void 0),bh.set(this,()=>{}),_u.set(this,()=>{}),Ns.set(this,{}),yu.set(this,!1),wf.set(this,!1),bf.set(this,!1),lo.set(this,!1),Pe(this,yh,new Promise((e,t)=>{Pe(this,wh,e,"f"),Pe(this,mu,t,"f")})),Pe(this,gu,new Promise((e,t)=>{Pe(this,bh,e,"f"),Pe(this,_u,t,"f")})),N(this,yh,"f").catch(()=>{}),N(this,gu,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},N(this,W_,"m",u1).bind(this))},0)}_connected(){this.ended||(N(this,wh,"f").call(this),this._emit("connect"))}get ended(){return N(this,yu,"f")}get errored(){return N(this,wf,"f")}get aborted(){return N(this,bf,"f")}abort(){this.controller.abort()}on(e,t){return(N(this,Ns,"f")[e]||(N(this,Ns,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=N(this,Ns,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(N(this,Ns,"f")[e]||(N(this,Ns,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{Pe(this,lo,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){Pe(this,lo,!0),await N(this,gu,"f")}_emit(e,...t){if(N(this,yu,"f"))return;e==="end"&&(Pe(this,yu,!0),N(this,bh,"f").call(this));const r=N(this,Ns,"f")[e];if(r&&(N(this,Ns,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!N(this,lo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),N(this,mu,"f").call(this,s),N(this,_u,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!N(this,lo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),N(this,mu,"f").call(this,s),N(this,_u,"f").call(this,s),this._emit("end")}}_emitFinal(){}}yh=new WeakMap,wh=new WeakMap,mu=new WeakMap,gu=new WeakMap,bh=new WeakMap,_u=new WeakMap,Ns=new WeakMap,yu=new WeakMap,wf=new WeakMap,bf=new WeakMap,lo=new WeakMap,W_=new WeakSet,u1=function(e){if(Pe(this,wf,!0),e instanceof Error&&e.name==="AbortError"&&(e=new ur),e instanceof ur)return Pe(this,bf,!0),this._emit("abort",e);if(e instanceof we)return this._emit("error",e);if(e instanceof Error){const t=new we(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new we(String(e)))};function sW(n){return typeof n.parse=="function"}var Pn,q_,vf,G_,J_,Y_,l1,d1;const iW=10;class h1 extends Yw{constructor(){super(...arguments),Pn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(r=e.choices[0])==null?void 0:r.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),c1(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(yf(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 we("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),N(this,Pn,"m",q_).call(this)}async finalMessage(){return await this.done(),N(this,Pn,"m",vf).call(this)}async finalFunctionToolCall(){return await this.done(),N(this,Pn,"m",G_).call(this)}async finalFunctionToolCallResult(){return await this.done(),N(this,Pn,"m",J_).call(this)}async totalUsage(){return await this.done(),N(this,Pn,"m",Y_).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=N(this,Pn,"m",vf).call(this);t&&this._emit("finalMessage",t);const r=N(this,Pn,"m",q_).call(this);r&&this._emit("finalContent",r);const s=N(this,Pn,"m",G_).call(this);s&&this._emit("finalFunctionToolCall",s);const i=N(this,Pn,"m",J_).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",N(this,Pn,"m",Y_).call(this))}async _createChatCompletion(e,t,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),N(this,Pn,"m",l1).call(this,t);const i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Jw(i,t))}async _runChatCompletion(e,t,r){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){var h,m,g;const s="tool",{tool_choice:i="auto",stream:a,...o}=t,c=typeof i!="string"&&i.type==="function"&&((h=i==null?void 0:i.function)==null?void 0:h.name),{maxChatCompletions:u=iW}=r||{},l=t.tools.map(y=>{if(Wl(y)){if(!y.$callback)throw new we("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 t?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 t.messages)this._addMessage(y,!1);for(let y=0;y<u;++y){const _=(m=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:f,messages:[...this.messages]},r)).choices[0])==null?void 0:m.message;if(!_)throw new we("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 S=w.id,{name:T,arguments:A}=w.function,I=d[T];if(I){if(c&&c!==T){const O=`Invalid tool_call: ${JSON.stringify(T)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:O});continue}}else{const O=`Invalid tool_call: ${JSON.stringify(T)}. Available options are: ${Object.keys(d).map(U=>JSON.stringify(U)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:O});continue}let k;try{k=sW(I)?await I.parse(A):A}catch(O){const U=O instanceof Error?O.message:String(O);this._addMessage({role:s,tool_call_id:S,content:U});continue}const R=await I.function(k,this),x=N(this,Pn,"m",d1).call(this,R);if(this._addMessage({role:s,tool_call_id:S,content:x}),c)return}}}}Pn=new WeakSet,q_=function(){return N(this,Pn,"m",vf).call(this).content??null},vf=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(yf(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new we("stream ended without producing a ChatCompletionMessage with role=assistant")},G_=function(){var e,t;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(yf(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.filter(i=>i.type==="function").at(-1))==null?void 0:t.function}},J_=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(c1(t)&&t.content!=null&&typeof t.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===t.tool_call_id))}))return t.content}},Y_=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},l1=function(e){if(e.n!=null&&e.n>1)throw new we("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},d1=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Xw extends h1{static runTools(e,t,r){const s=new Xw,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}_addMessage(e,t=!0){super._addMessage(e,t),yf(e)&&e.content&&this._emit("content",e.content)}}const f1=1,p1=2,m1=4,g1=8,_1=16,y1=32,w1=64,b1=128,v1=256,S1=b1|v1,A1=_1|y1|S1|w1,T1=f1|p1|A1,E1=m1|g1,aW=T1|E1,nn={STR:f1,NUM:p1,ARR:m1,OBJ:g1,NULL:_1,BOOL:y1,NAN:w1,INFINITY:b1,MINUS_INFINITY:v1,INF:S1,SPECIAL:A1,ATOM:T1,COLLECTION:E1,ALL:aW};class oW extends Error{}class cW extends Error{}function uW(n,e=nn.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return lW(n.trim(),e)}const lW=(n,e)=>{const t=n.length;let r=0;const s=f=>{throw new oW(`${f} at position ${r}`)},i=f=>{throw new cW(`${f} at position ${r}`)},a=()=>(d(),r>=t&&s("Unexpected end of input"),n[r]==='"'?o():n[r]==="{"?c():n[r]==="["?u():n.substring(r,r+4)==="null"||nn.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||nn.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||nn.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||nn.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||nn.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||nn.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):l()),o=()=>{const f=r;let h=!1;for(r++;r<t&&(n[r]!=='"'||h&&n[r-1]==="\\");)h=n[r]==="\\"?!h:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(f,++r-Number(h)))}catch(m){i(String(m))}else if(nn.STR&e)try{return JSON.parse(n.substring(f,r-Number(h))+'"')}catch{return JSON.parse(n.substring(f,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,d();const f={};try{for(;n[r]!=="}";){if(d(),r>=t&&nn.OBJ&e)return f;const h=o();d(),r++;try{const m=a();Object.defineProperty(f,h,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(nn.OBJ&e)return f;throw m}d(),n[r]===","&&r++}}catch{if(nn.OBJ&e)return f;s("Expected '}' at end of object")}return r++,f},u=()=>{r++;const f=[];try{for(;n[r]!=="]";)f.push(a()),d(),n[r]===","&&r++}catch{if(nn.ARR&e)return f;s("Expected ']' at end of array")}return r++,f},l=()=>{if(r===0){n==="-"&&nn.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(h){if(nn.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}i(String(h))}}const f=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(nn.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(f,r))}catch{n.substring(f,r)==="-"&&nn.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(f,n.lastIndexOf("e")))}catch(m){i(String(m))}}},d=()=>{for(;r<t&&`
|
|
370
|
+
\r `.includes(n[r]);)r++};return a()},JS=n=>uW(n,nn.ALL^nn.NUM);var Kt,Cs,Ja,si,Fm,Cd,Bm,Hm,Vm,$d,Zm,YS;class ll extends h1{constructor(e){super(),Kt.add(this),Cs.set(this,void 0),Ja.set(this,void 0),si.set(this,void 0),Pe(this,Cs,e),Pe(this,Ja,[])}get currentChatCompletionSnapshot(){return N(this,si,"f")}static fromReadableStream(e){const t=new ll(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const s=new ll(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,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,Kt,"m",Fm).call(this);const i=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const o of i)N(this,Kt,"m",Bm).call(this,o);if((a=i.controller.signal)!=null&&a.aborted)throw new ur;return this._addChatCompletion(N(this,Kt,"m",$d).call(this))}async _fromReadableStream(e,t){var a;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),N(this,Kt,"m",Fm).call(this),this._connected();const s=ul.fromReadableStream(e,this.controller);let i;for await(const o of s)i&&i!==o.id&&this._addChatCompletion(N(this,Kt,"m",$d).call(this)),N(this,Kt,"m",Bm).call(this,o),i=o.id;if((a=s.controller.signal)!=null&&a.aborted)throw new ur;return this._addChatCompletion(N(this,Kt,"m",$d).call(this))}[(Cs=new WeakMap,Ja=new WeakMap,si=new WeakMap,Kt=new WeakSet,Fm=function(){this.ended||Pe(this,si,void 0)},Cd=function(t){let r=N(this,Ja,"f")[t.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,Ja,"f")[t.index]=r,r)},Bm=function(t){var s,i,a,o,c,u,l,d,f,h,m,g,y,b,_;if(this.ended)return;const r=N(this,Kt,"m",YS).call(this,t);this._emit("chunk",t,r);for(const w of t.choices){const S=r.choices[w.index];w.delta.content!=null&&((s=S.message)==null?void 0:s.role)==="assistant"&&((i=S.message)!=null&&i.content)&&(this._emit("content",w.delta.content,S.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:S.message.content,parsed:S.message.parsed})),w.delta.refusal!=null&&((a=S.message)==null?void 0:a.role)==="assistant"&&((o=S.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:S.message.refusal}),((c=w.logprobs)==null?void 0:c.content)!=null&&((u=S.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(l=w.logprobs)==null?void 0:l.content,snapshot:((d=S.logprobs)==null?void 0:d.content)??[]}),((f=w.logprobs)==null?void 0:f.refusal)!=null&&((h=S.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=w.logprobs)==null?void 0:m.refusal,snapshot:((g=S.logprobs)==null?void 0:g.refusal)??[]});const T=N(this,Kt,"m",Cd).call(this,S);S.finish_reason&&(N(this,Kt,"m",Vm).call(this,S),T.current_tool_call_index!=null&&N(this,Kt,"m",Hm).call(this,S,T.current_tool_call_index));for(const A of w.delta.tool_calls??[])T.current_tool_call_index!==A.index&&(N(this,Kt,"m",Vm).call(this,S),T.current_tool_call_index!=null&&N(this,Kt,"m",Hm).call(this,S,T.current_tool_call_index)),T.current_tool_call_index=A.index;for(const A of w.delta.tool_calls??[]){const I=(y=S.message.tool_calls)==null?void 0:y[A.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=I.function)==null?void 0:b.name,index:A.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((_=A.function)==null?void 0:_.arguments)??""}):(I==null||I.type,void 0))}}},Hm=function(t,r){var a,o,c;if(N(this,Kt,"m",Cd).call(this,t).done_tool_calls.has(r))return;const i=(a=t.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,Cs,"f"))==null?void 0:o.tools)==null?void 0:c.find(l=>_f(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:Wl(u)?u.$parseRaw(i.function.arguments):u!=null&&u.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Vm=function(t){var s,i;const r=N(this,Kt,"m",Cd).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const a=N(this,Kt,"m",Zm).call(this);this._emit("content.done",{content:t.message.content,parsed:a?a.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(s=t.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(i=t.logprobs)!=null&&i.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},$d=function(){if(this.ended)throw new we("stream has ended, this shouldn't happen");const t=N(this,si,"f");if(!t)throw new we("request ended without sending any chunks");return Pe(this,si,void 0),Pe(this,Ja,[]),dW(t,N(this,Cs,"f"))},Zm=function(){var r;const t=(r=N(this,Cs,"f"))==null?void 0:r.response_format;return Gw(t)?t:null},YS=function(t){var r,s,i,a;let o=N(this,si,"f");const{choices:c,...u}=t;o?Object.assign(o,u):o=Pe(this,si,{...u,choices:[]});for(const{delta:l,finish_reason:d,index:f,logprobs:h=null,...m}of t.choices){let g=o.choices[f];if(g||(g=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:h,...m}),h)if(!g.logprobs)g.logprobs=Object.assign({},h);else{const{content:A,refusal:I,...k}=h;Object.assign(g.logprobs,k),A&&((r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...A)),I&&((s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...I))}if(d&&(g.finish_reason=d,N(this,Cs,"f")&&a1(N(this,Cs,"f")))){if(d==="length")throw new DC;if(d==="content_filter")throw new UC}if(Object.assign(g,m),!l)continue;const{content:y,refusal:b,function_call:_,role:w,tool_calls:S,...T}=l;if(Object.assign(g.message,T),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,Kt,"m",Zm).call(this)&&(g.message.parsed=JS(g.message.content))),S){g.message.tool_calls||(g.message.tool_calls=[]);for(const{index:A,id:I,type:k,function:R,...x}of S){const O=(a=g.message.tool_calls)[A]??(a[A]={});Object.assign(O,x),I&&(O.id=I),k&&(O.type=k),R&&(O.function??(O.function={name:R.name??"",arguments:""})),R!=null&&R.name&&(O.function.name=R.name),R!=null&&R.arguments&&(O.function.arguments+=R.arguments,nW(N(this,Cs,"f"),O)&&(O.function.parsed_arguments=JS(O.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>t.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 ul(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function dW(n,e){const{id:t,choices:r,created:s,model:i,system_fingerprint:a,...o}=n,c={...o,id:t,choices:r.map(({message:u,finish_reason:l,index:d,logprobs:f,...h})=>{if(!l)throw new we(`missing finish_reason for choice ${d}`);const{content:m=null,function_call:g,tool_calls:y,...b}=u,_=u.role;if(!_)throw new we(`missing role for choice ${d}`);if(g){const{arguments:w,name:S}=g;if(w==null)throw new we(`missing function_call.arguments for choice ${d}`);if(!S)throw new we(`missing function_call.name for choice ${d}`);return{...h,message:{content:m,function_call:{arguments:w,name:S},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:m,refusal:u.refusal??null,tool_calls:y.map((w,S)=>{const{function:T,type:A,id:I,...k}=w,{arguments:R,name:x,...O}=T||{};if(I==null)throw new we(`missing choices[${d}].tool_calls[${S}].id
|
|
371
|
+
${Rd(n)}`);if(A==null)throw new we(`missing choices[${d}].tool_calls[${S}].type
|
|
372
|
+
${Rd(n)}`);if(x==null)throw new we(`missing choices[${d}].tool_calls[${S}].function.name
|
|
373
|
+
${Rd(n)}`);if(R==null)throw new we(`missing choices[${d}].tool_calls[${S}].function.arguments
|
|
374
|
+
${Rd(n)}`);return{...k,id:I,type:A,function:{...O,name:x,arguments:R}}})}}:{...h,message:{...b,content:m,role:_,refusal:u.refusal??null},finish_reason:l,index:d,logprobs:f}}),created:s,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return QK(c,e)}function Rd(n){return JSON.stringify(n)}class Sf extends ll{static fromReadableStream(e){const t=new Sf(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const s=new Sf(t),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,i)),s}}let Qw=class extends W{constructor(){super(...arguments),this.messages=new i1(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",Pt,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return rW(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Jw(r,e))}runTools(e,t){return e.stream?Sf.runTools(this._client,e,t):Xw.runTools(this._client,e,t)}stream(e,t){return ll.createChatCompletion(this._client,e,t)}};Qw.Messages=i1;class eb extends W{constructor(){super(...arguments),this.completions=new Qw(this._client)}}eb.Completions=Qw;class k1 extends W{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get($`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",Pt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class I1 extends W{list(e={},t){return this._client.getAPIList("/organization/audit_logs",wn,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}let x1=class extends W{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get($`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",wn,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",Ui,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",Ui,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}},O1=class extends W{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}};class C1 extends W{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get($`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",wn,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}let $1=class extends W{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get($`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",ni,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},R1=class extends W{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",wn,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};class P1 extends W{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}let N1=class extends W{create(e,t,r){return this._client.post($`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{group_id:s}=t;return this._client.get($`/organization/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/groups/${e}/roles`,ni,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{group_id:s}=t;return this._client.delete($`/organization/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},M1=class extends W{create(e,t,r){return this._client.post($`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{group_id:s}=t;return this._client.get($`/organization/groups/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/groups/${e}/users`,ni,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{group_id:s}=t;return this._client.delete($`/organization/groups/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},kp=class extends W{constructor(){super(...arguments),this.users=new M1(this._client),this.roles=new N1(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get($`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",ni,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};kp.Users=M1;kp.Roles=N1;class j1 extends W{retrieve(e,t,r){const{project_id:s}=t;return this._client.get($`/organization/projects/${s}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/api_keys`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s}=t;return this._client.delete($`/organization/projects/${s}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class L1 extends W{list(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/certificates`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList($`/organization/projects/${e}/certificates/activate`,Ui,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList($`/organization/projects/${e}/certificates/deactivate`,Ui,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}}class D1 extends W{retrieve(e,t){return this._client.get($`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}}class U1 extends W{retrieve(e,t){return this._client.get($`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}}class z1 extends W{retrieve(e,t){return this._client.get($`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}class F1 extends W{listRateLimits(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/rate_limits`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/organization/projects/${s}/rate_limits/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}}let B1=class extends W{create(e,t,r){return this._client.post($`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:s}=t;return this._client.get($`/projects/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/projects/${s}/roles/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/projects/${e}/roles`,ni,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s}=t;return this._client.delete($`/projects/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};class H1 extends W{create(e,t,r){return this._client.post($`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:s}=t;return this._client.get($`/organization/projects/${s}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/organization/projects/${s}/service_accounts/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/service_accounts`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s}=t;return this._client.delete($`/organization/projects/${s}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class V1 extends W{create(e,t,r){return this._client.post($`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/organization/projects/${s}/spend_alerts/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/spend_alerts`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s}=t;return this._client.delete($`/organization/projects/${s}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}let Z1=class extends W{create(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/projects/${s}/groups/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:s,group_id:i}=t;return this._client.get($`/projects/${s}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){const{project_id:s,...i}=t;return this._client.getAPIList($`/projects/${s}/groups/${e}/roles`,ni,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s,group_id:i}=t;return this._client.delete($`/projects/${s}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};class tb extends W{constructor(){super(...arguments),this.roles=new Z1(this._client)}create(e,t,r){return this._client.post($`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:s,...i}=t;return this._client.get($`/organization/projects/${s}/groups/${e}`,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/groups`,ni,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s}=t;return this._client.delete($`/organization/projects/${s}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}tb.Roles=Z1;let K1=class extends W{create(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/projects/${s}/users/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:s,user_id:i}=t;return this._client.get($`/projects/${s}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){const{project_id:s,...i}=t;return this._client.getAPIList($`/projects/${s}/users/${e}/roles`,ni,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s,user_id:i}=t;return this._client.delete($`/projects/${s}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},nb=class extends W{constructor(){super(...arguments),this.roles=new K1(this._client)}create(e,t,r){return this._client.post($`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:s}=t;return this._client.get($`/organization/projects/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:s,...i}=t;return this._client.post($`/organization/projects/${s}/users/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/projects/${e}/users`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:s}=t;return this._client.delete($`/organization/projects/${s}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};nb.Roles=K1;class gr extends W{constructor(){super(...arguments),this.users=new nb(this._client),this.serviceAccounts=new H1(this._client),this.apiKeys=new j1(this._client),this.rateLimits=new F1(this._client),this.modelPermissions=new z1(this._client),this.hostedToolPermissions=new U1(this._client),this.groups=new tb(this._client),this.roles=new B1(this._client),this.dataRetention=new D1(this._client),this.spendAlerts=new V1(this._client),this.certificates=new L1(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get($`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",wn,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post($`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}}gr.Users=nb;gr.ServiceAccounts=H1;gr.APIKeys=j1;gr.RateLimits=F1;gr.ModelPermissions=z1;gr.HostedToolPermissions=U1;gr.Groups=tb;gr.Roles=B1;gr.DataRetention=D1;gr.SpendAlerts=V1;gr.Certificates=L1;class W1 extends W{create(e,t,r){return this._client.post($`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{user_id:s}=t;return this._client.get($`/organization/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/organization/users/${e}/roles`,ni,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{user_id:s}=t;return this._client.delete($`/organization/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class rb extends W{constructor(){super(...arguments),this.roles=new W1(this._client)}retrieve(e,t){return this._client.get($`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post($`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",wn,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete($`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}rb.Roles=W1;class _r extends W{constructor(){super(...arguments),this.auditLogs=new I1(this._client),this.adminAPIKeys=new k1(this._client),this.usage=new P1(this._client),this.invites=new C1(this._client),this.users=new rb(this._client),this.groups=new kp(this._client),this.roles=new $1(this._client),this.dataRetention=new O1(this._client),this.spendAlerts=new R1(this._client),this.certificates=new x1(this._client),this.projects=new gr(this._client)}}_r.AuditLogs=I1;_r.AdminAPIKeys=k1;_r.Usage=P1;_r.Invites=C1;_r.Users=rb;_r.Groups=kp;_r.Roles=$1;_r.DataRetention=O1;_r.SpendAlerts=R1;_r.Certificates=x1;_r.Projects=gr;class sb extends W{constructor(){super(...arguments),this.organization=new _r(this._client)}}sb.Organization=_r;const q1=Symbol("brand.privateNullableHeaders");function*hW(n){if(!n)return;if(q1 in n){const{values:r,nulls:s}=n;yield*r.entries();for(const i of s)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():NS(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=NS(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 ae=n=>{const e=new Headers,t=new Set;for(const r of n){const s=new Set;for(const[i,a]of hW(r)){const o=i.toLowerCase();s.has(o)||(e.delete(i),s.add(o)),a===null?(e.delete(i),t.add(o)):(e.append(i,a),t.delete(o))}}return{[q1]:!0,values:e,nulls:t}};class G1 extends W{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:ae([{Accept:"application/octet-stream"},t==null?void 0:t.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class J1 extends W{create(e,t){return this._client.post("/audio/transcriptions",gs({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class Y1 extends W{create(e,t){return this._client.post("/audio/translations",gs({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class ql extends W{constructor(){super(...arguments),this.transcriptions=new J1(this._client),this.translations=new Y1(this._client),this.speech=new G1(this._client)}}ql.Transcriptions=J1;ql.Translations=Y1;ql.Speech=G1;let X1=class extends W{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",Pt,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post($`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};class Q1 extends W{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/assistants/${e}`,{...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/assistants/${e}`,{body:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",Pt,{query:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/assistants/${e}`,{...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}}let e$=class extends W{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}};class t$ extends W{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}}let Ip=class extends W{constructor(){super(...arguments),this.sessions=new e$(this._client),this.transcriptionSessions=new t$(this._client)}};Ip.Sessions=e$;Ip.TranscriptionSessions=t$;let n$=class extends W{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post($`/chatkit/sessions/${e}/cancel`,{...t,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}},r$=class extends W{retrieve(e,t){return this._client.get($`/chatkit/threads/${e}`,{...t,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",wn,{query:e,...t,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/chatkit/threads/${e}`,{...t,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList($`/chatkit/threads/${e}/items`,wn,{query:t,...r,headers:ae([{"OpenAI-Beta":"chatkit_beta=v1"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class xp extends W{constructor(){super(...arguments),this.sessions=new n$(this._client),this.threads=new r$(this._client)}}xp.Sessions=n$;xp.Threads=r$;let s$=class extends W{create(e,t,r){return this._client.post($`/threads/${e}/messages`,{body:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get($`/threads/${s}/messages/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{thread_id:s,...i}=t;return this._client.post($`/threads/${s}/messages/${e}`,{body:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/threads/${e}/messages`,Pt,{query:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){const{thread_id:s}=t;return this._client.delete($`/threads/${s}/messages/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class i$ extends W{retrieve(e,t,r){const{thread_id:s,run_id:i,...a}=t;return this._client.get($`/threads/${s}/runs/${i}/steps/${e}`,{query:a,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,t,r){const{thread_id:s,...i}=t;return this._client.getAPIList($`/threads/${s}/runs/${e}/steps`,Pt,{query:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}const fW=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var Km={};const Hr=n=>{var e,t,r,s;if(typeof globalThis.process<"u")return((e=Km==null?void 0:Km[n])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(r=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:r.call(t,n))==null?void 0:s.trim())||void 0};var dn,la,X_,cs,vh,Vr,da,So,ia,Af,rr,Sh,Ah,Lu,wu,bu,XS,QS,eA,tA,nA,rA,sA;class Du extends Yw{constructor(){super(...arguments),dn.add(this),X_.set(this,[]),cs.set(this,{}),vh.set(this,{}),Vr.set(this,void 0),da.set(this,void 0),So.set(this,void 0),ia.set(this,void 0),Af.set(this,void 0),rr.set(this,void 0),Sh.set(this,void 0),Ah.set(this,void 0),Lu.set(this,void 0)}[(X_=new WeakMap,cs=new WeakMap,vh=new WeakMap,Vr=new WeakMap,da=new WeakMap,So=new WeakMap,ia=new WeakMap,Af=new WeakMap,rr=new WeakMap,Sh=new WeakMap,Ah=new WeakMap,Lu=new WeakMap,dn=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>t.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 t=new la;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var i;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=ul.fromReadableStream(e,this.controller);for await(const a of s)N(this,dn,"m",wu).call(this,a);if((i=s.controller.signal)!=null&&i.aborted)throw new ur;return this._addRun(N(this,dn,"m",bu).call(this))}toReadableStream(){return new ul(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){const i=new la;return i._run(()=>i._runToolAssistantStream(e,t,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,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(t,a,{...s,signal:this.controller.signal});this._connected();for await(const u of o)N(this,dn,"m",wu).call(this,u);if((c=o.controller.signal)!=null&&c.aborted)throw new ur;return this._addRun(N(this,dn,"m",bu).call(this))}static createThreadAssistantStream(e,t,r){const s=new la;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){const i=new la;return i._run(()=>i._runAssistantStream(e,t,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return N(this,Sh,"f")}currentRun(){return N(this,Ah,"f")}currentMessageSnapshot(){return N(this,Vr,"f")}currentRunStepSnapshot(){return N(this,Lu,"f")}async finalRunSteps(){return await this.done(),Object.values(N(this,cs,"f"))}async finalMessages(){return await this.done(),Object.values(N(this,vh,"f"))}async finalRun(){if(await this.done(),!N(this,da,"f"))throw Error("Final run was not received.");return N(this,da,"f")}async _createThreadAssistantStream(e,t,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={...t,stream:!0},a=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(const c of a)N(this,dn,"m",wu).call(this,c);if((o=a.controller.signal)!=null&&o.aborted)throw new ur;return this._addRun(N(this,dn,"m",bu).call(this))}async _createAssistantStream(e,t,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(t,a,{...s,signal:this.controller.signal});this._connected();for await(const u of o)N(this,dn,"m",wu).call(this,u);if((c=o.controller.signal)!=null&&c.aborted)throw new ur;return this._addRun(N(this,dn,"m",bu).call(this))}static accumulateDelta(e,t){for(const[r,s]of Object.entries(t)){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(gh(i)&&gh(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(!gh(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,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}la=Du,wu=function(e){if(!this.ended)switch(Pe(this,Sh,e),N(this,dn,"m",eA).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,dn,"m",sA).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,dn,"m",QS).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,dn,"m",XS).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},bu=function(){if(this.ended)throw new we("stream has ended, this shouldn't happen");if(!N(this,da,"f"))throw Error("Final run has not been received");return N(this,da,"f")},XS=function(e){const[t,r]=N(this,dn,"m",nA).call(this,e,N(this,Vr,"f"));Pe(this,Vr,t),N(this,vh,"f")[t.id]=t;for(const s of r){const i=t.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,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let i=s.text,a=t.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,So,"f")){if(N(this,ia,"f"))switch(N(this,ia,"f").type){case"text":this._emit("textDone",N(this,ia,"f").text,N(this,Vr,"f"));break;case"image_file":this._emit("imageFileDone",N(this,ia,"f").image_file,N(this,Vr,"f"));break}Pe(this,So,s.index)}Pe(this,ia,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(N(this,So,"f")!==void 0){const s=e.data.content[N(this,So,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,N(this,Vr,"f"));break;case"text":this._emit("textDone",s.text,N(this,Vr,"f"));break}}N(this,Vr,"f")&&this._emit("messageDone",e.data),Pe(this,Vr,void 0)}},QS=function(e){const t=N(this,dn,"m",tA).call(this,e);switch(Pe(this,Lu,t),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&&t.step_details.type=="tool_calls")for(const i of r.step_details.tool_calls)i.index==N(this,Af,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(N(this,rr,"f")&&this._emit("toolCallDone",N(this,rr,"f")),Pe(this,Af,i.index),Pe(this,rr,t.step_details.tool_calls[i.index]),N(this,rr,"f")&&this._emit("toolCallCreated",N(this,rr,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Pe(this,Lu,void 0),e.data.step_details.type=="tool_calls"&&N(this,rr,"f")&&(this._emit("toolCallDone",N(this,rr,"f")),Pe(this,rr,void 0)),this._emit("runStepDone",e.data,t);break}},eA=function(e){N(this,X_,"f").push(e),this._emit("event",e)},tA=function(e){switch(e.event){case"thread.run.step.created":return N(this,cs,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=N(this,cs,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=la.accumulateDelta(t,r.delta);N(this,cs,"f")[e.data.id]=s}return N(this,cs,"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,cs,"f")[e.data.id]=e.data;break}if(N(this,cs,"f")[e.data.id])return N(this,cs,"f")[e.data.id];throw new Error("No snapshot available")},nA=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)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 t.content){let a=t.content[i.index];t.content[i.index]=N(this,dn,"m",rA).call(this,i,a)}else t.content[i.index]=i,r.push(i);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},rA=function(e,t){return la.accumulateDelta(t,e)},sA=function(e){switch(Pe(this,Ah,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":Pe(this,da,e.data),N(this,rr,"f")&&(this._emit("toolCallDone",N(this,rr,"f")),Pe(this,rr,void 0));break}};let ib=class extends W{constructor(){super(...arguments),this.steps=new i$(this._client)}create(e,t,r){const{include:s,...i}=t;return this._client.post($`/threads/${e}/runs`,{query:{include:s},body:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get($`/threads/${s}/runs/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{thread_id:s,...i}=t;return this._client.post($`/threads/${s}/runs/${e}`,{body:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/threads/${e}/runs`,Pt,{query:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){const{thread_id:s}=t;return this._client.post($`/threads/${s}/runs/${e}/cancel`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return Du.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){var i;const s=ae([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,t,{...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 Kl(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return Du.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:s,...i}=t;return this._client.post($`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){const s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return Du.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};ib.Steps=i$;class Op extends W{constructor(){super(...arguments),this.runs=new ib(this._client),this.messages=new s$(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/threads/${e}`,{...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/threads/${e}`,{body:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/threads/${e}`,{...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Du.createThreadAssistantStream(e,this._client.beta.threads,t)}}Op.Runs=ib;Op.Messages=s$;let xc=class extends W{constructor(){super(...arguments),this.realtime=new Ip(this._client),this.chatkit=new xp(this._client),this.assistants=new Q1(this._client),this.threads=new Op(this._client)}};xc.Realtime=Ip;xc.ChatKit=xp;xc.Assistants=Q1;xc.Threads=Op;let a$=class extends W{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},o$=class extends W{retrieve(e,t,r){const{container_id:s}=t;return this._client.get($`/containers/${s}/files/${e}/content`,{...r,headers:ae([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},ab=class extends W{constructor(){super(...arguments),this.content=new o$(this._client)}create(e,t,r){return this._client.post($`/containers/${e}/files`,Ep({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){const{container_id:s}=t;return this._client.get($`/containers/${s}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/containers/${e}/files`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{container_id:s}=t;return this._client.delete($`/containers/${s}/files/${e}`,{...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};ab.Content=o$;class ob extends W{constructor(){super(...arguments),this.files=new ab(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",Pt,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/containers/${e}`,{...t,headers:ae([{Accept:"*/*"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}}ob.Files=ab;class c$ extends W{create(e,t,r){const{include:s,...i}=t;return this._client.post($`/conversations/${e}/items`,{query:{include:s},body:i,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){const{conversation_id:s,...i}=t;return this._client.get($`/conversations/${s}/items/${e}`,{query:i,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/conversations/${e}/items`,wn,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{conversation_id:s}=t;return this._client.delete($`/conversations/${s}/items/${e}`,{...r,__security:{bearerAuth:!0}})}}class cb extends W{constructor(){super(...arguments),this.items=new c$(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}}cb.Items=c$;class u$ extends W{create(e,t){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&ln(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t,__security:{bearerAuth:!0}});return r?i:(ln(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=fW(c)}),a)))}}class l$ extends W{retrieve(e,t,r){const{eval_id:s,run_id:i}=t;return this._client.get($`/evals/${s}/runs/${i}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){const{eval_id:s,...i}=t;return this._client.getAPIList($`/evals/${s}/runs/${e}/output_items`,Pt,{query:i,...r,__security:{bearerAuth:!0}})}}class ub extends W{constructor(){super(...arguments),this.outputItems=new l$(this._client)}create(e,t,r){return this._client.post($`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){const{eval_id:s}=t;return this._client.get($`/evals/${s}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/evals/${e}/runs`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{eval_id:s}=t;return this._client.delete($`/evals/${s}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){const{eval_id:s}=t;return this._client.post($`/evals/${s}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}}ub.OutputItems=l$;class lb extends W{constructor(){super(...arguments),this.runs=new ub(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",Pt,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}}lb.Runs=ub;let d$=class extends W{create(e,t){return this._client.post("/files",gs({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get($`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",Pt,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get($`/files/${e}/content`,{...t,headers:ae([{Accept:"application/binary"},t==null?void 0:t.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=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 Kl(t),a=await this.retrieve(e),Date.now()-i>r)throw new Sp({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}};class h$ extends W{}let f$=class extends W{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};class db extends W{constructor(){super(...arguments),this.graders=new f$(this._client)}}db.Graders=f$;class p$ extends W{create(e,t,r){return this._client.getAPIList($`/fine_tuning/checkpoints/${e}/permissions`,Ui,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get($`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/fine_tuning/checkpoints/${e}/permissions`,wn,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete($`/fine_tuning/checkpoints/${s}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}let hb=class extends W{constructor(){super(...arguments),this.permissions=new p$(this._client)}};hb.Permissions=p$;class m$ extends W{list(e,t={},r){return this._client.getAPIList($`/fine_tuning/jobs/${e}/checkpoints`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}}class fb extends W{constructor(){super(...arguments),this.checkpoints=new m$(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Pt,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post($`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList($`/fine_tuning/jobs/${e}/events`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post($`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post($`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}}fb.Checkpoints=m$;class Oc extends W{constructor(){super(...arguments),this.methods=new h$(this._client),this.jobs=new fb(this._client),this.checkpoints=new hb(this._client),this.alpha=new db(this._client)}}Oc.Methods=h$;Oc.Jobs=fb;Oc.Checkpoints=hb;Oc.Alpha=db;class g$ extends W{}class pb extends W{constructor(){super(...arguments),this.graderModels=new g$(this._client)}}pb.GraderModels=g$;class _$ extends W{createVariation(e,t){return this._client.post("/images/variations",gs({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",gs({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}let y$=class extends W{retrieve(e,t){return this._client.get($`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Ui,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};class w$ extends W{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}}class b$ extends W{accept(e,t,r){return this._client.post($`/realtime/calls/${e}/accept`,{body:t,...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post($`/realtime/calls/${e}/hangup`,{...t,headers:ae([{Accept:"*/*"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post($`/realtime/calls/${e}/refer`,{body:t,...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post($`/realtime/calls/${e}/reject`,{body:t,...r,headers:ae([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}class v$ extends W{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}}class Cp extends W{constructor(){super(...arguments),this.clientSecrets=new v$(this._client),this.calls=new b$(this._client)}}Cp.ClientSecrets=v$;Cp.Calls=b$;function pW(n,e){return!e||!gW(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:S$(n,e)}function S$(n,e){const t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:wW(e,s)};if(s.type==="message"){const i=s.content.map(a=>a.type==="output_text"?{...a,parsed:mW(e,a.text)}:a);return{...s,content:i}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Q_(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 mW(n,e){var t,r,s,i;return((r=(t=n.text)==null?void 0:t.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=n.text)==null?void 0:s.format)?((i=n.text)==null?void 0:i.format).$parseRaw(e):JSON.parse(e)}function gW(n){var e;return!!Gw((e=n.text)==null?void 0:e.format)}function _W(n){return(n==null?void 0:n.$brand)==="auto-parseable-tool"}function yW(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function wW(n,e){const t=yW(n.tools??[],e.name);return{...e,...e,parsed_arguments:_W(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Q_(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Ya,Pd,ii,Nd,iA,aA,oA,cA;class mb extends Yw{constructor(e){super(),Ya.add(this),Pd.set(this,void 0),ii.set(this,void 0),Nd.set(this,void 0),Pe(this,Pd,e)}static createResponse(e,t,r){const s=new mb(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,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,Ya,"m",iA).call(this);let i,a=null;"response_id"in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const c of i)N(this,Ya,"m",aA).call(this,c,a);if((o=i.controller.signal)!=null&&o.aborted)throw new ur;return N(this,Ya,"m",oA).call(this)}[(Pd=new WeakMap,ii=new WeakMap,Nd=new WeakMap,Ya=new WeakSet,iA=function(){this.ended||Pe(this,ii,void 0)},aA=function(t,r){if(this.ended)return;const s=(a,o)=>{(r==null||o.sequence_number>r)&&this._emit(a,o)},i=N(this,Ya,"m",cA).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const a=i.output[t.output_index];if(!a)throw new we(`missing output at index ${t.output_index}`);if(a.type==="message"){const o=a.content[t.content_index];if(!o)throw new we(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new we(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const a=i.output[t.output_index];if(!a)throw new we(`missing output at index ${t.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:s(t.type,t);break}},oA=function(){if(this.ended)throw new we("stream has ended, this shouldn't happen");const t=N(this,ii,"f");if(!t)throw new we("request ended without sending any events");Pe(this,ii,void 0);const r=bW(t,N(this,Pd,"f"));return Pe(this,Nd,r),r},cA=function(t){var s;let r=N(this,ii,"f");if(!r){if(t.type!=="response.created")throw new we(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=Pe(this,ii,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const i=r.output[t.output_index];if(!i)throw new we(`missing output at index ${t.output_index}`);const a=i.type,o=t.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[t.output_index];if(!i)throw new we(`missing output at index ${t.output_index}`);if(i.type==="message"){const a=i.content[t.content_index];if(!a)throw new we(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new we(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const i=r.output[t.output_index];if(!i)throw new we(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{const i=r.output[t.output_index];if(!i)throw new we(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){const a=(s=i.content)==null?void 0:s[t.content_index];if(!a)throw new we(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new we(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{Pe(this,ii,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>t.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,Nd,"f");if(!e)throw new we("stream ended without producing a ChatCompletion");return e}}function bW(n,e){return pW(n,e)}class A$ extends W{list(e,t={},r){return this._client.getAPIList($`/responses/${e}/input_items`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}}class T$ extends W{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}}class $p extends W{constructor(){super(...arguments),this.inputItems=new A$(this._client),this.inputTokens=new T$(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Q_(r),r))}retrieve(e,t={},r){return this._client.get($`/responses/${e}`,{query:t,...r,stream:(t==null?void 0:t.stream)??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Q_(s),s))}delete(e,t){return this._client.delete($`/responses/${e}`,{...t,headers:ae([{Accept:"*/*"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>S$(r,e))}stream(e,t){return mb.createResponse(this._client,e,t)}cancel(e,t){return this._client.post($`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}}$p.InputItems=A$;$p.InputTokens=T$;let E$=class extends W{retrieve(e,t){return this._client.get($`/skills/${e}/content`,{...t,headers:ae([{Accept:"application/binary"},t==null?void 0:t.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};class k$ extends W{retrieve(e,t,r){const{skill_id:s}=t;return this._client.get($`/skills/${s}/versions/${e}/content`,{...r,headers:ae([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}let gb=class extends W{constructor(){super(...arguments),this.content=new k$(this._client)}create(e,t={},r){return this._client.post($`/skills/${e}/versions`,Ep({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){const{skill_id:s}=t;return this._client.get($`/skills/${s}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/skills/${e}/versions`,Pt,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{skill_id:s}=t;return this._client.delete($`/skills/${s}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};gb.Content=k$;let Rp=class extends W{constructor(){super(...arguments),this.content=new E$(this._client),this.versions=new gb(this._client)}create(e={},t){return this._client.post("/skills",Ep({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get($`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",Pt,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};Rp.Content=E$;Rp.Versions=gb;class I$ extends W{create(e,t,r){return this._client.post($`/uploads/${e}/parts`,gs({body:t,...r,__security:{bearerAuth:!0}},this._client))}}class _b extends W{constructor(){super(...arguments),this.parts=new I$(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post($`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post($`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}}_b.Parts=I$;const vW=async n=>{const e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.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 x$ extends W{create(e,t,r){return this._client.post($`/vector_stores/${e}/file_batches`,{body:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get($`/vector_stores/${s}/file_batches/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){const{vector_store_id:s}=t;return this._client.post($`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){const s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){const{vector_store_id:s,...i}=t;return this._client.getAPIList($`/vector_stores/${s}/file_batches/${e}/files`,Pt,{query:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){var i;const s=ae([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(t,{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 Kl(c);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.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,t.length),o=this._client,c=t.values(),u=[...r];async function l(f){for(let h of f){const m=await o.files.create({file:h,purpose:"assistants"},s);u.push(m.id)}}const d=Array(a).fill(c).map(l);return await vW(d),await this.createAndPoll(e,{file_ids:u})}}let O$=class extends W{create(e,t,r){return this._client.post($`/vector_stores/${e}/files`,{body:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get($`/vector_stores/${s}/files/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{vector_store_id:s,...i}=t;return this._client.post($`/vector_stores/${s}/files/${e}`,{body:i,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList($`/vector_stores/${e}/files`,Pt,{query:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){const{vector_store_id:s}=t;return this._client.delete($`/vector_stores/${s}/files/${e}`,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){var i;const s=ae([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(t,{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 Kl(c);break;case"failed":case"completed":return o}}}async upload(e,t,r){const s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){const s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){const{vector_store_id:s}=t;return this._client.getAPIList($`/vector_stores/${s}/files/${e}/content`,Ui,{...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class Pp extends W{constructor(){super(...arguments),this.files=new O$(this._client),this.fileBatches=new x$(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get($`/vector_stores/${e}`,{...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post($`/vector_stores/${e}`,{body:t,...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",Pt,{query:e,...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/vector_stores/${e}`,{...t,headers:ae([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList($`/vector_stores/${e}/search`,Ui,{body:t,method:"post",...r,headers:ae([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}Pp.Files=O$;Pp.FileBatches=x$;class C$ extends W{create(e,t){return this._client.post("/videos",gs({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get($`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",wn,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete($`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",gs({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get($`/videos/${e}/content`,{query:t,...r,headers:ae([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",gs({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",gs({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get($`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post($`/videos/${e}/remix`,Ep({body:t,...r,__security:{bearerAuth:!0}},this._client))}}var ho,$$,Th;class R$ extends W{constructor(){super(...arguments),ho.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,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,ho,"m",$$).call(this,r);const i=ae([t]).values,a=N(this,ho,"m",Th).call(this,i,"webhook-signature"),o=N(this,ho,"m",Th).call(this,i,"webhook-timestamp"),c=N(this,ho,"m",Th).call(this,i,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new du("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-u>s)throw new du("Webhook timestamp is too old");if(u>l+s)throw new du("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}`,m=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",m,y,new TextEncoder().encode(h)))return}catch{continue}throw new du("The given webhook signature does not match the expected signature")}}ho=new WeakSet,$$=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")},Th=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var ey,yb,Eh,P$;const SW="workload-identity-auth";class Fe{constructor({baseURL:e=Hr("OPENAI_BASE_URL"),apiKey:t=Hr("OPENAI_API_KEY")??null,adminAPIKey:r=Hr("OPENAI_ADMIN_KEY")??null,organization:s=Hr("OPENAI_ORG_ID")??null,project:i=Hr("OPENAI_PROJECT_ID")??null,webhookSecret:a=Hr("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:o,...c}={}){ey.add(this),Eh.set(this,void 0),this.completions=new a$(this),this.chat=new eb(this),this.embeddings=new u$(this),this.files=new d$(this),this.images=new _$(this),this.audio=new ql(this),this.moderations=new w$(this),this.models=new y$(this),this.fineTuning=new Oc(this),this.graders=new pb(this),this.vectorStores=new Pp(this),this.webhooks=new R$(this),this.beta=new xc(this),this.batches=new X1(this),this.uploads=new _b(this),this.admin=new sb(this),this.responses=new $p(this),this.realtime=new Cp(this),this.conversations=new cb(this),this.evals=new lb(this),this.containers=new ob(this),this.skills=new Rp(this),this.videos=new C$(this);const u={apiKey:t,adminAPIKey:r,organization:s,project:i,webhookSecret:a,workloadIdentity:o,...c,baseURL:e||"https://api.openai.com/v1"};if(t&&o)throw new we("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!t&&!r&&!o)throw new we("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!u.dangerouslyAllowBrowser&&bK())throw new we(`It looks like you're running in a browser-like environment.
|
|
375
|
+
|
|
376
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
377
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
378
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
379
|
+
|
|
380
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
381
|
+
|
|
382
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
383
|
+
`);this.baseURL=u.baseURL,this.timeout=u.timeout??yb.DEFAULT_TIMEOUT,this.logger=u.logger??console;const l="warn";this.logLevel=l,this.logLevel=KS(u.logLevel,"ClientOptions.logLevel",this)??KS(Hr("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=u.fetchOptions,this.maxRetries=u.maxRetries??2,this.fetch=u.fetch??FC(),Pe(this,Eh,EK);const d=Hr("OPENAI_CUSTOM_HEADERS");if(d){const f={};for(const h of d.split(`
|
|
384
|
+
`)){const m=h.indexOf(":");m>=0&&(f[h.substring(0,m).trim()]=h.substring(m+1).trim())}u.defaultHeaders=ae([f,u.defaultHeaders])}this._options=u,o&&(this._workloadIdentityAuth=new VK(o,this.fetch)),this.apiKey=typeof t=="string"?t: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:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.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,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return ae([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return ae([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return ae([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return ae([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return RK(e)}getUserAgent(){return`${this.constructor.name}/JS ${uo}`}defaultIdempotencyKey(){return`stainless-node-retry-${OC()}`}makeStatusError(e,t,r,s){return kn.generate(e,t,r,s)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof we?r:new we(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new we(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){const s=!N(this,ey,"m",P$).call(this)&&r||this.baseURL,i=gK(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!MS(a)||!MS(o))&&(t={...o,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new XC(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var _,w,S,T;const s=await e,i=s.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(s);const{req:a,url:o,timeout:c}=await this.buildRequest(s,{retryCount:i-t});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(ln(this).debug(`[${u}] sending request`,ta({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:a.headers})),(_=s.signal)!=null&&_.aborted)throw new ur;const f=s.__security??{bearerAuth:!0},h=new AbortController,m=await this.fetchWithAuth(o,a,c,h,f).catch(F_),g=Date.now();if(m instanceof globalThis.Error){const A=`retrying, ${t} attempts remaining`;if((w=s.signal)!=null&&w.aborted)throw new ur;const I=z_(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ln(this).info(`[${u}] connection ${I?"timed out":"failed"} - ${A}`),ln(this).debug(`[${u}] connection ${I?"timed out":"failed"} (${A})`,ta({retryOfRequestLogID:r,url:o,durationMs:g-d,message:m.message})),this.retryRequest(s,t,r??u);throw ln(this).info(`[${u}] connection ${I?"timed out":"failed"} - error; no more retries left`),ln(this).debug(`[${u}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ta({retryOfRequestLogID:r,url:o,durationMs:g-d,message:m.message})),m instanceof zC||m instanceof pK?m:I?new Sp:new vp({message:AW(m),cause:m})}const y=[...m.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,I])=>", "+A+": "+JSON.stringify(I)).join(""),b=`[${u}${l}${y}] ${a.method} ${o} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-d}ms`;if(!m.ok){if(m.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!((S=s.__metadata)!=null&&S.hasStreamingBody)&&!((T=s.__metadata)!=null&&T.workloadIdentityTokenRefreshed))return await US(m.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??u);const A=await this.shouldRetry(m);if(t&&A){const U=`retrying, ${t} attempts remaining`;return await US(m.body),ln(this).info(`${b} - ${U}`),ln(this).debug(`[${u}] response error (${U})`,ta({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-d})),this.retryRequest(s,t,r??u,m.headers)}const I=A?"error; no more retries left":"error; not retryable";ln(this).info(`${b} - ${I}`);const k=await m.text().catch(U=>F_(U).message),R=wK(k),x=R?void 0:k;throw ln(this).debug(`[${u}] response error (${I})`,ta({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:x,durationMs:Date.now()-d})),this.makeStatusError(m.status,R,x,m.headers)}return ln(this).info(b),ln(this).debug(`[${u}] response start`,ta({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-d})),{response:m,options:s,controller:h,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new FK(this,r,e)}async fetchWithAuth(e,t,r,s,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){const o=t.headers,c=o.get("Authorization");if(!c||c===`Bearer ${SW}`){const u=await this._workloadIdentityAuth.getToken();o.set("Authorization",`Bearer ${u}`)}}return await this.fetchWithTimeout(e,t,r,s)}async fetchWithTimeout(e,t,r,s){const{signal:i,method:a,...o}=t||{},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 t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,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(t,c)}return await Kl(i),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:s,path:i,query:a,defaultBaseURL:o}=r,c=this.buildURL(i,a,o);"timeout"in r&&yK("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:t});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:t,bodyHeaders:r,retryCount:s}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=ae([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))}:{},...TK(),"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:t}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const r=ae([t]),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:HC(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,Eh,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}}yb=Fe,Eh=new WeakMap,ey=new WeakSet,P$=function(){return this.baseURL!=="https://api.openai.com/v1"};Fe.OpenAI=yb;Fe.DEFAULT_TIMEOUT=6e5;Fe.OpenAIError=we;Fe.APIError=kn;Fe.APIConnectionError=vp;Fe.APIConnectionTimeoutError=Sp;Fe.APIUserAbortError=ur;Fe.NotFoundError=PC;Fe.ConflictError=NC;Fe.RateLimitError=jC;Fe.BadRequestError=CC;Fe.AuthenticationError=$C;Fe.InternalServerError=LC;Fe.PermissionDeniedError=RC;Fe.UnprocessableEntityError=MC;Fe.InvalidWebhookSignatureError=du;Fe.toFile=GK;Fe.Completions=a$;Fe.Chat=eb;Fe.Embeddings=u$;Fe.Files=d$;Fe.Images=_$;Fe.Audio=ql;Fe.Moderations=w$;Fe.Models=y$;Fe.FineTuning=Oc;Fe.Graders=pb;Fe.VectorStores=Pp;Fe.Webhooks=R$;Fe.Beta=xc;Fe.Batches=X1;Fe.Uploads=_b;Fe.Admin=sb;Fe.Responses=$p;Fe.Realtime=Cp;Fe.Conversations=cb;Fe.Evals=lb;Fe.Containers=ob;Fe.Skills=Rp;Fe.Videos=C$;function AW(n){if(TW(n))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 TW(n){let e=n;for(let t=0;t<8&&e&&typeof e=="object";t++){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 EW={};class kW extends Fe{constructor({baseURL:e=Hr("OPENAI_BASE_URL"),apiKey:t=Hr("AZURE_OPENAI_API_KEY"),apiVersion:r=Hr("OPENAI_API_VERSION"),endpoint:s,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...c}={}){if(!r)throw new we("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(o=!0),!a&&!t)throw new we("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new we("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 we("baseURL and endpoint are mutually exclusive")}else{if(s||(s=EW.AZURE_OPENAI_ENDPOINT),!s)throw new we("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:a??t,baseURL:e,...c,...o!==void 0?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=i}async buildRequest(e,t={}){var r;if(IW.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!gh(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,t)}async authHeaders(e,t){const r=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&typeof this._options.apiKey=="string"?ae([{"api-key":this.apiKey}]):super.authHeaders(e,r)}}const IW=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);function xW(n){return!!(String(n).includes("context_length_exceeded")||"message"in n&&typeof n.message=="string"&&(n.message.includes("Input tokens exceed the configured limit")||n.message.includes("exceeds the context window")||n.message.includes("maximum context length")))}function wb(n){if(!n||typeof n!="object")return n;let e;return n.constructor.name===Sp.name&&"message"in n&&typeof n.message=="string"?(e=new Error(n.message),e.name="TimeoutError"):n.constructor.name===ur.name&&"message"in n&&typeof n.message=="string"?(e=new Error(n.message),e.name="AbortError"):xW(n)?e=wy.fromError(n):"status"in n&&n.status===400&&"message"in n&&typeof n.message=="string"&&n.message.includes("tool_calls")?e=Id(n,"INVALID_TOOL_RESULTS"):"status"in n&&n.status===401?e=Id(n,"MODEL_AUTHENTICATION"):"status"in n&&n.status===429?e=Id(n,"MODEL_RATE_LIMIT"):"status"in n&&n.status===404?e=Id(n,"MODEL_NOT_FOUND"):e=n,e}const Bs=n=>n();function Gl(n){return n?!!(/^o\d/.test(n??"")||n.startsWith("gpt-5")&&!n.startsWith("gpt-5-chat")):!1}function OW(n){return n.role!=="system"&&n.role!=="developer"&&n.role!=="assistant"&&n.role!=="user"&&n.role!=="function"&&n.role!=="tool"&&console.warn(`Unknown message role: ${n.role}`),n.role}function uA(n){var e,t,r;return((e=n.metadata)==null?void 0:e.filename)??((t=n.metadata)==null?void 0:t.name)??((r=n.metadata)==null?void 0:r.title)}const CW="LC_AUTOGENERATED";function Tf(n){var t,r,s;const e=((t=n.metadata)==null?void 0:t.filename)??((r=n.metadata)==null?void 0:r.name)??((s=n.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'."),CW)}function Jl(n){const e=n._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(!ks.isInstance(n))throw new Error("Invalid generic chat message");return OW(n);default:throw new Error(`Unknown message type: ${e}`)}}function $W(n){return!!(n.includes("gpt-5.2-pro")||n.includes("gpt-5.4-pro")||n.includes("gpt-5.5-pro")||n.includes("codex"))}function N$(n){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:i,azureADTokenProvider:a,azureOpenAIEndpoint:o}=n;if((r||a)&&s&&e)return`${s}/${e}`;if((r||a)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||a){if(!t)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${t}.openai.azure.com/openai/deployments/${e}`}return i}function lA(n){return typeof Headers<"u"&&n!==null&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Headers]"}function RW(n){const e=Bs(()=>{if(lA(n))return n;if(Array.isArray(n))return new Headers(n);if(typeof n=="object"&&n!==null&&"values"in n&&lA(n.values))return n.values;if(typeof n=="object"&&n!==null){const t=Object.entries(n).filter(([,r])=>typeof r=="string").map(([r,s])=>[r,s]);return new Headers(t)}return new Headers});return Object.fromEntries(e.entries())}function PW(){let n=$y();return(n==="node"||n==="deno")&&(n=`(${n}/${process.version}; ${process.platform}; ${process.arch})`),n}function M$(n,e=!1,t="1.0.0"){const r=RW(n),s=PW(),i=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${i}/${t} (${s})${r["User-Agent"]}`:`${i}/${t} (${s})`}}function NW(n,e){let t;return Ys(n)?t=uf(n):t=n,(e==null?void 0:e.strict)!==void 0&&(t.function.strict=e.strict),t}function MW(n){return n.anyOf!==void 0&&Array.isArray(n.anyOf)}function jW(n){const e=["namespace functions {",""];for(const t of n)t.description&&e.push(`// ${t.description}`),Object.keys(t.parameters.properties??{}).length>0?(e.push(`type ${t.name} = (_: {`),e.push(j$(t.parameters,0)),e.push("}) => any;")):e.push(`type ${t.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
385
|
+
`)}function j$(n,e){var r;const t=[];for(const[s,i]of Object.entries(n.properties??{}))i.description&&e<2&&t.push(`// ${i.description}`),(r=n.required)!=null&&r.includes(s)?t.push(`${s}: ${Ef(i,e)},`):t.push(`${s}?: ${Ef(i,e)},`);return t.map(s=>" ".repeat(e)+s).join(`
|
|
386
|
+
`)}function Ef(n,e){if(MW(n))return n.anyOf.map(t=>Ef(t,e)).join(" | ");switch(n.type){case"string":return n.enum?n.enum.map(t=>`"${t}"`).join(" | "):"string";case"number":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"integer":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",j$(n,e+2),"}"].join(`
|
|
387
|
+
`);case"array":return n.items?`${Ef(n.items,e)}[]`:"any[]";default:return""}}function L$(n){if(n)return n==="any"||n==="required"?"required":n==="auto"?"auto":n==="none"?"none":typeof n=="string"?{type:"function",function:{name:n}}:n}function bb(n){return"type"in n&&n.type!=="function"}function LW(n){return typeof n=="object"&&n!==null&&"extras"in n&&typeof n.extras=="object"&&n.extras!==null&&"providerToolDefinition"in n.extras&&typeof n.extras.providerToolDefinition=="object"&&n.extras.providerToolDefinition!==null}function DW(n){return n!=null&&typeof n=="object"&&"type"in n&&n.type!=="function"}function kf(n){return typeof n=="object"&&n!==null&&"metadata"in n&&typeof n.metadata=="object"&&n.metadata!==null&&"customTool"in n.metadata&&typeof n.metadata.customTool=="object"&&n.metadata.customTool!==null}function D$(n){return"type"in n&&n.type==="custom"&&"custom"in n&&typeof n.custom=="object"&&n.custom!==null}function UW(n){if(n.type==="custom_tool_call")return{...n,type:"tool_call",call_id:n.id,id:n.call_id,name:n.name,isCustomTool:!0,args:{input:n.input}}}function zW(n){if(n.type==="computer_call")return{...n,type:"tool_call",call_id:n.id,id:n.call_id,name:"computer_use",isComputerTool:!0,args:{action:n.action}}}function FW(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="tool_call"&&"isComputerTool"in n&&n.isComputerTool===!0}function BW(n,e){return typeof n!="object"||n===null||!("type"in n)||n.type!=="tool_call"?!1:!!("isCustomTool"in n&&n.isCustomTool===!0||e&&"id"in n&&typeof n.id=="string"&&n.id in e)}function HW(n){const e=()=>{if(n.custom.format){if(n.custom.format.type==="grammar")return{type:"grammar",definition:n.custom.format.grammar.definition,syntax:n.custom.format.grammar.syntax};if(n.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:n.custom.name,description:n.custom.description,format:e()}}function VW(n){const e=()=>{if(n.format){if(n.format.type==="grammar")return{type:"grammar",grammar:{definition:n.format.definition,syntax:n.format.syntax}};if(n.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:n.name,description:n.description,format:e()}}}const ZW=Symbol("Let zodToJsonSchema decide on which parser to use"),dA={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"},KW=n=>typeof n=="string"?{...dA,basePath:["#"],definitions:{},name:n}:{...dA,basePath:["#"],definitions:{},...n},ty=n=>"_def"in n?n._def:n;function WW(n){if(!n)return!0;for(const e in n)return!1;return!0}const qW=n=>{const e=KW(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[ty(s),{def:ty(s),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function U$(n,e,t,r){r!=null&&r.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function ft(n,e,t,r,s){n[e]=t,U$(n,e,r,s)}function GW(){return{}}function JW(n,e){var r,s;const t={type:"array"};return((s=(r=n.type)==null?void 0:r._def)==null?void 0:s.typeName)!==D.ZodAny&&(t.items=ct(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&ft(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&ft(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(ft(t,"minItems",n.exactLength.value,n.exactLength.message,e),ft(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function YW(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ft(t,"minimum",r.value,r.message,e):ft(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),ft(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ft(t,"maximum",r.value,r.message,e):ft(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),ft(t,"maximum",r.value,r.message,e));break;case"multipleOf":ft(t,"multipleOf",r.value,r.message,e);break}return t}function XW(){return{type:"boolean"}}function QW(n,e){return ct(n.type._def,e)}const eq=(n,e)=>ct(n.innerType._def,e);function z$(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,i)=>z$(n,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 tq(n,e)}}const tq=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":ft(t,"minimum",r.value,r.message,e);break;case"max":ft(t,"maximum",r.value,r.message,e);break}return t};function nq(n,e){return{...ct(n.innerType._def,e),default:n.defaultValue()}}function rq(n,e,t){return e.effectStrategy==="input"?ct(n.schema._def,e,t):{}}function sq(n){return{type:"string",enum:[...n.values]}}const iq=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function aq(n,e){const t=[ct(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ct(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(i=>{if(iq(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 oq(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let Wm;const Wi={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:()=>(Wm===void 0&&(Wm=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wm),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function F$(n,e){const t={type:"string"};function r(s){return e.patternStrategy==="escape"?cq(s):s}if(n.checks)for(const s of n.checks)switch(s.kind){case"min":ft(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e);break;case"max":ft(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Dr(t,"email",s.message,e);break;case"format:idn-email":Dr(t,"idn-email",s.message,e);break;case"pattern:zod":Ur(t,Wi.email,s.message,e);break}break;case"url":Dr(t,"uri",s.message,e);break;case"uuid":Dr(t,"uuid",s.message,e);break;case"regex":Ur(t,s.regex,s.message,e);break;case"cuid":Ur(t,Wi.cuid,s.message,e);break;case"cuid2":Ur(t,Wi.cuid2,s.message,e);break;case"startsWith":Ur(t,RegExp(`^${r(s.value)}`),s.message,e);break;case"endsWith":Ur(t,RegExp(`${r(s.value)}$`),s.message,e);break;case"datetime":Dr(t,"date-time",s.message,e);break;case"date":Dr(t,"date",s.message,e);break;case"time":Dr(t,"time",s.message,e);break;case"duration":Dr(t,"duration",s.message,e);break;case"length":ft(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e),ft(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"includes":{Ur(t,RegExp(r(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&Dr(t,"ipv4",s.message,e),s.version!=="v4"&&Dr(t,"ipv6",s.message,e);break}case"emoji":Ur(t,Wi.emoji,s.message,e);break;case"ulid":{Ur(t,Wi.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Dr(t,"binary",s.message,e);break}case"contentEncoding:base64":{ft(t,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{Ur(t,Wi.base64,s.message,e);break}}break}case"nanoid":Ur(t,Wi.nanoid,s.message,e)}return t}const cq=n=>Array.from(n).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Dr=(n,e,t,r)=>{var s;n.format||(s=n.anyOf)!=null&&s.some(i=>i.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):ft(n,"format",e,t,r)},Ur=(n,e,t,r)=>{var s;n.pattern||(s=n.allOf)!=null&&s.some(i=>i.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:hA(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):ft(n,"pattern",hA(e,r),t,r)},hA=(n,e)=>{var u;const t=typeof n=="function"?n():n;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=r.i?t.source.toLowerCase():t.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
|
|
388
|
+
]))`;continue}else if(s[l]==="$"){i+=`($|(?=[\r
|
|
389
|
+
]))`;continue}}if(r.s&&s[l]==="."){i+=o?`${s[l]}\r
|
|
390
|
+
`:`[${s[l]}\r
|
|
391
|
+
]`;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`),t.source}return i};function B$(n,e){var r,s,i,a;if(e.target==="openApi3"&&((r=n.keyType)==null?void 0:r._def.typeName)===D.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((o,c)=>({...o,[c]:ct(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",c]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:ct(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(((s=n.keyType)==null?void 0:s._def.typeName)===D.ZodString&&((i=n.keyType._def.checks)!=null&&i.length)){const o=Object.entries(F$(n.keyType._def,e)).reduce((c,[u,l])=>u==="type"?c:{...c,[u]:l},{});return{...t,propertyNames:o}}else if(((a=n.keyType)==null?void 0:a._def.typeName)===D.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};return t}function uq(n,e){if(e.mapStrategy==="record")return B$(n,e);const t=ct(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=ct(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function lq(n){const e=n.values,r=Object.keys(n.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 dq(){return{not:{}}}function hq(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const If={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function fq(n,e){if(e.target==="openApi3")return fA(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in If&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,i)=>{const a=If[i._def.typeName];return a&&!s.includes(a)?[...s,a]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.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===t.length){const s=r.filter((i,a,o)=>o.indexOf(i)===a);return{type:s.length>1?s:s[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(i=>!r.includes(i))],[])};return fA(n,e)}const fA=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>ct(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function pq(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:If[n.innerType._def.typeName],nullable:!0}:{type:[If[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=ct(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=ct(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function mq(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",U$(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ft(t,"minimum",r.value,r.message,e):ft(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),ft(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ft(t,"maximum",r.value,r.message,e):ft(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),ft(t,"maximum",r.value,r.message,e));break;case"multipleOf":ft(t,"multipleOf",r.value,r.message,e);break}return t}function gq(n,e){return e.removeAdditionalStrategy==="strict"?n.catchall._def.typeName==="ZodNever"?n.unknownKeys!=="strict":ct(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:n.catchall._def.typeName==="ZodNever"?n.unknownKeys==="passthrough":ct(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function _q(n,e){const t={type:"object",...Object.entries(n.shape()).reduce((r,[s,i])=>{var c;if(i===void 0||i._def===void 0)return r;const a=[...e.currentPath,"properties",s],o=ct(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:gq(n,e)};return t.required.length||delete t.required,t}const yq=(n,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return ct(n.innerType._def,{...e,currentPath:e.currentPath});const t=ct(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},wq=(n,e)=>{if(e.pipeStrategy==="input")return ct(n.in._def,e);if(e.pipeStrategy==="output")return ct(n.out._def,e);const t=ct(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=ct(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function bq(n,e){return ct(n.type._def,e)}function vq(n,e){const r={type:"array",uniqueItems:!0,items:ct(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&ft(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&ft(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function Sq(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>ct(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:ct(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>ct(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Aq(){return{not:{}}}function Tq(){return{}}const Eq=(n,e)=>ct(n.innerType._def,e);function ct(n,e,t=!1){var a;const r=e.seen.get(n);if(e.override){const o=(a=e.override)==null?void 0:a.call(e,n,e,r,t);if(o!==ZW)return o}if(r&&!t){const o=kq(r,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const i=xq(n,n.typeName,e,t);return i&&Oq(n,e,i),s.jsonSchema=i,i}const kq=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"extract-to-root":const t=n.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=n.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:Iq(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.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}},Iq=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},xq=(n,e,t,r)=>{switch(e){case D.ZodString:return F$(n,t);case D.ZodNumber:return mq(n,t);case D.ZodObject:return _q(n,t);case D.ZodBigInt:return YW(n,t);case D.ZodBoolean:return XW();case D.ZodDate:return z$(n,t);case D.ZodUndefined:return Aq();case D.ZodNull:return hq(t);case D.ZodArray:return JW(n,t);case D.ZodUnion:case D.ZodDiscriminatedUnion:return fq(n,t);case D.ZodIntersection:return aq(n,t);case D.ZodTuple:return Sq(n,t);case D.ZodRecord:return B$(n,t);case D.ZodLiteral:return oq(n,t);case D.ZodEnum:return sq(n);case D.ZodNativeEnum:return lq(n);case D.ZodNullable:return pq(n,t);case D.ZodOptional:return yq(n,t);case D.ZodMap:return uq(n,t);case D.ZodSet:return vq(n,t);case D.ZodLazy:return ct(n.getter()._def,t);case D.ZodPromise:return bq(n,t);case D.ZodNaN:case D.ZodNever:return dq();case D.ZodEffects:return rq(n,t,r);case D.ZodAny:return GW();case D.ZodUnknown:return Tq();case D.ZodDefault:return nq(n,t);case D.ZodBranded:return QW(n,t);case D.ZodReadonly:return Eq(n,t);case D.ZodCatch:return eq(n,t);case D.ZodPipeline:return wq(n,t);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(s=>{})()}},Oq=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),Cq=(n,e)=>{const t=qW(e),r=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=ct(n._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.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(WW(t.definitions))return;const c={},u=new Set;for(let l=0;l<500;l++){const d=Object.entries(t.definitions).filter(([f])=>!u.has(f));if(d.length===0)break;for(const[f,h]of d)c[f]=ct(ty(h),{...t,currentPath:[...t.basePath,t.definitionPath,f]},!0)??{},u.add(f)}return c})(),o=r===void 0?a?{...s,[t.definitionPath]:a}:s:t.nameStrategy==="duplicate-ref"?{...s,...a||t.seenRefs.size?{[t.definitionPath]:{...a,...t.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...a,[r]:s}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function $q(n){if(n.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${n.type?`'${n.type}'`:"undefined"}`);const e=structuredClone(n);return Ms(e,[],e)}function ny(n){if(typeof n=="boolean")return!1;if(n.type==="null")return!0;for(const e of n.oneOf??[])if(ny(e))return!0;for(const e of n.anyOf??[])if(ny(e))return!0;return!1}function Ms(n,e,t){if(typeof n=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!na(n))throw new TypeError(`Expected ${JSON.stringify(n)} to be an object; path=${e.join("/")}`);const r=n.$defs;if(na(r))for(const[f,h]of Object.entries(r))Ms(h,[...e,"$defs",f],t);const s=n.definitions;if(na(s))for(const[f,h]of Object.entries(s))Ms(h,[...e,"definitions",f],t);n.type==="object"&&!("additionalProperties"in n)&&(n.additionalProperties=!1);const a=n.required??[],o=n.properties;if(na(o)){for(const[f,h]of Object.entries(o))if(!ny(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`);n.required=Object.keys(o),n.properties=Object.fromEntries(Object.entries(o).map(([f,h])=>[f,Ms(h,[...e,"properties",f],t)]))}const c=n.items;na(c)&&(n.items=Ms(c,[...e,"items"],t));const u=n.anyOf;Array.isArray(u)&&(n.anyOf=u.map((f,h)=>Ms(f,[...e,"anyOf",String(h)],t)));const l=n.allOf;if(Array.isArray(l))if(l.length===1){const f=Ms(l[0],[...e,"allOf","0"],t);Object.assign(n,f),delete n.allOf}else n.allOf=l.map((f,h)=>Ms(f,[...e,"allOf",String(h)],t));n.default===null&&delete n.default;const d=n.$ref;if(d&&Pq(n,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);const f=Rq(t,d);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!na(f))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(n,{...f,...n}),delete n.$ref,Ms(n,e,t)}return n}function Rq(n,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const t=e.slice(2).split("/");let r=n;for(const s of t){if(!na(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 na(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Pq(n,e){let t=0;for(const r in n)if(t++,t>e)return!0;return!1}function Nq(n,e){return Cq(n,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Mq(n){return $q(zg(n,{target:"draft-7"}))}function jq(n){return"_zod"in n}function Lq(n,e,t){return XK({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:jq(n)?Mq(n):Nq(n,{name:e})}},r=>n.parse(JSON.parse(r)))}const pA=["jsonSchema","functionCalling","jsonMode"];function Dq(n,e){if(typeof e<"u"&&!pA.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${pA.join(", ")}`);const t=!n.startsWith("gpt-3")&&!n.startsWith("gpt-4-")&&n!=="gpt-4";if(t&&!e)return"jsonSchema";if(!t&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${n}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Uq(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function zq(n,e,t){if(Ht(n))return Lq(n,e,t);if(It(n))return Uq({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:At(n,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>Gf(n,JSON.parse(r)));throw new Error("Unsupported schema response format")}function Fq(n,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const t=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:n},...t]}return n}const Bq={"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 vb(n,e){return typeof n=="string"?{model:n,...e??{}}:n??e}var Sb=class extends Is{constructor(e){var r,s,i,a;super(e??{});p(this,"temperature");p(this,"topP");p(this,"frequencyPenalty");p(this,"presencePenalty");p(this,"n");p(this,"logitBias");p(this,"model","gpt-3.5-turbo");p(this,"modelKwargs");p(this,"stop");p(this,"stopSequences");p(this,"user");p(this,"timeout");p(this,"streaming",!1);p(this,"streamUsage",!0);p(this,"maxTokens");p(this,"logprobs");p(this,"topLogprobs");p(this,"apiKey");p(this,"organization");p(this,"__includeRawResponse");p(this,"client");p(this,"clientConfig");p(this,"supportsStrictToolCalling");p(this,"audio");p(this,"modalities");p(this,"reasoning");p(this,"zdrEnabled");p(this,"service_tier");p(this,"promptCacheKey");p(this,"promptCacheRetention");p(this,"verbosity");p(this,"defaultOptions");p(this,"lc_serializable",!0);const t=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)??t??Bt("OPENAI_API_KEY"),this.organization=((a=e==null?void 0:e.configuration)==null?void 0:a.organization)??Bt("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 t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!Gl(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),(e==null?void 0:e.reasoning)!==void 0&&(t={...t,...e.reasoning}),(e==null?void 0:e.reasoningEffort)!==void 0&&(t==null?void 0:t.effort)===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Xt(e.json_schema.schema)?zq(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 t=N$({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:t,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=M$(r.defaultHeaders),this.client=new Fe(r)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return kf(e)?VW(e.metadata.customTool):Sc(e)?(t==null?void 0:t.strict)!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:NW(e,t)}bindTools(e,t){let r;return(t==null?void 0:t.strict)!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>{var a;if(bb(s)||kf(s))return s;if(LW(s))return s.extras.providerToolDefinition;const i=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ys(s)&&((a=s.extras)==null?void 0:a.defer_loading)===!0?{...i,defer_loading:!0}:i}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,r)=>(r&&r.tokenUsage&&(t.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=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,m,g,y,b;const[o,c]=await Promise.all([this.getNumTokens(a.content),this.getNumTokens(Jl(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((m=d.additional_kwargs.function_call)==null?void 0:m.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 t+=l,l}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async t=>{var r;return(r=t.message.additional_kwargs)!=null&&r.function_call?(await this.getNumTokensFromMessages([t.message])).countPerMessage[0]:await this.getNumTokens(t.message.content)}))).reduce((t,r)=>t+r,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&r!=="auto"){const i=jW(t);s+=await this.getNumTokens(i),s+=9}return t&&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,t){const r=this._getClientOptions(t==null?void 0:t.options),s={input:e,model:(t==null?void 0:t.model)??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(i){throw wb(i)}})}get profile(){return Bq[this.model]??{}}_getStructuredOutputMethod(e){const t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if((t==null?void 0:t.method)===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let r,s;const{schema:i,name:a,includeRaw:o}={...t,schema:e};if((t==null?void 0:t.strict)!==void 0&&t.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const c=Dq(this.model,t==null?void 0:t.method);if(c==="jsonMode"){s=uc(i);const u=At(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=At(i),l={name:a??"extract",description:tc(u),schema:Xt(i)?i:u,strict:t==null?void 0:t.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}}}),Xt(i)||Or(i)){const d=uc(i);s=an.from(async f=>"parsed"in f.additional_kwargs?f.additional_kwargs.parsed:d.invoke(f.content))}else s=new bw}else{let u=a??"extract";const l=At(i);let d;Xt(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}},...(t==null?void 0:t.strict)!==void 0?{strict:t.strict}:{}}),s=zl(i,u)}return Ec(r,s,o)}};const H$={providerName:"ChatOpenAI",fromStandardTextBlock(n){return{type:"text",text:n.text}},fromStandardImageBlock(n){var e,t;if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url,...(e=n.metadata)!=null&&e.detail?{detail:n.metadata.detail}:{}}};if(n.source_type==="base64")return{type:"image_url",image_url:{url:`data:${n.mime_type??""};base64,${n.data}`,...(t=n.metadata)!=null&&t.detail?{detail:n.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(n){if(n.source_type==="url"){const e=Gr({dataUrl:n.url});if(!e)throw new Error(`URL audio blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);const t=e.mime_type||n.mime_type||"";let r;try{r=wg(t)}catch{throw new Error(`Audio blocks with source_type ${n.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 ${n.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(n.source_type==="base64"){let e;try{e=wg(n.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${n.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 ${n.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:n.data}}}throw new Error(`Audio content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(n){if(n.source_type==="url"){const e=Gr({dataUrl:n.url}),t=Tf(n);if(!e)throw new Error(`URL file blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:n.url,filename:t}}}if(n.source_type==="base64"){const e=Tf(n);return{type:"file",file:{file_data:`data:${n.mime_type??""};base64,${n.data}`,filename:e}}}if(n.source_type==="id")return{type:"file",file:{file_id:n.id}};throw new Error(`File content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)}},Hq=({message:n,rawResponse:e,includeRawResponse:t})=>{var i,a;const r=n.tool_calls,s=n.reasoning_content;switch(n.role){case"assistant":{const o=[],c=[];for(const d of r??[])try{o.push(dp(d,{returnId:!0}))}catch(f){c.push(Nu(d,f.message))}const u={function_call:n.function_call,tool_calls:r};t!==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 n.audio&&(u.audio=n.audio),new Ve({content:Fq(n.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 ks(n.content||"",n.role??"unknown")}},Vq=({delta:n,rawResponse:e,includeRawResponse:t,defaultRole:r})=>{var c,u;const s=n.role??r,i=n.content??"";let a;n.function_call?a={function_call:n.function_call}:n.tool_calls?a={tool_calls:n.tool_calls}:a={},t&&(a.__raw_response=e),n.reasoning_content!==void 0&&(a.reasoning_content=n.reasoning_content),n.audio&&(a.audio={...n.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(s==="user")return new Rl({content:i,response_metadata:o});if(s==="assistant"){const l=[];if(Array.isArray(n.tool_calls))for(const d of n.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 nt({content:i,tool_call_chunks:l,additional_kwargs:a,id:e.id,response_metadata:o})}else return s==="system"?new Pi({content:i,response_metadata:o}):s==="developer"?new Pi({content:i,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new $l({content:i,additional_kwargs:a,name:n.name,response_metadata:o}):s==="tool"?new Ol({content:i,additional_kwargs:a,tool_call_id:n.tool_call_id,response_metadata:o}):new Cl({content:i,role:s,response_metadata:o})},Zq=n=>{if(n.type==="image"){if(n.url)return{type:"image_url",image_url:{url:n.url}};if(n.data)return{type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.data}`}}}if(n.type==="audio"&&n.data){const e=wE(()=>{const[,t]=n.mimeType.split("/");return t==="wav"||t==="mp3"?t:"wav"});return{type:"input_audio",input_audio:{data:n.data.toString(),format:e}}}if(n.type==="file"){if(n.data){const e=Tf(n);return{type:"file",file:{file_data:`data:${n.mimeType};base64,${n.data}`,filename:e}}}if(n.fileId)return{type:"file",file:{file_id:n.fileId}}}},Kq=({message:n,model:e})=>{var s;let t=Jl(n);if(t==="system"&&Gl(e)&&(t="developer"),t==="developer")return{role:"developer",content:n.contentBlocks.filter(i=>i.type==="text")};if(t==="system")return{role:"system",content:n.contentBlocks.filter(i=>i.type==="text")};if(t==="assistant"){const i={role:"assistant",content:n.contentBlocks.filter(a=>a.type==="text")};return Ve.isInstance(n)&&((s=n.tool_calls)!=null&&s.length)?i.tool_calls=n.tool_calls.map(Sw):n.additional_kwargs.tool_calls!=null&&(i.tool_calls=n.additional_kwargs.tool_calls),i}else{if(t==="tool"&&_n.isInstance(n))return{role:"tool",tool_call_id:n.tool_call_id,content:n.contentBlocks.filter(i=>i.type==="text")};if(t==="function")return{role:"function",name:n.name??"",content:n.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=Zq(a);o&&(yield o)}}return{role:"user",content:Array.from(r(n.contentBlocks))}},mA=({messages:n,model:e})=>n.flatMap(t=>{var a,o;if("output_version"in t.response_metadata&&((a=t.response_metadata)==null?void 0:a.output_version)==="v1")return Kq({message:t});let r=Jl(t);r==="system"&&Gl(e)&&(r="developer");const s=typeof t.content=="string"?t.content:t.content.flatMap(c=>Ir(c)?xl(c,H$):typeof c=="object"&&c!==null&&"type"in c&&c.type==="tool_use"?[]:c),i={role:r,content:s};return t.name!=null&&(i.name=t.name),t.additional_kwargs.function_call!=null&&(i.function_call=t.additional_kwargs.function_call),Ve.isInstance(t)&&((o=t.tool_calls)!=null&&o.length)?i.tool_calls=t.tool_calls.map(Sw):(t.additional_kwargs.tool_calls!=null&&(i.tool_calls=t.additional_kwargs.tool_calls),_n.isInstance(t)&&t.tool_call_id!=null&&(i.tool_call_id=t.tool_call_id)),t.additional_kwargs.audio&&typeof t.additional_kwargs.audio=="object"&&"id"in t.additional_kwargs.audio?[i,{role:"assistant",audio:{id:t.additional_kwargs.audio.id}}]:i});var V$=class extends Sb{constructor(n,e){super(vb(n,e))}invocationParams(n,e){var a;let t;(n==null?void 0:n.strict)!==void 0?t=n.strict:this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let r={};(n==null?void 0:n.stream_options)!==void 0?r={stream_options:n.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:(n==null?void 0:n.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:n==null?void 0:n.functions,function_call:n==null?void 0:n.function_call,tools:(a=n==null?void 0:n.tools)!=null&&a.length?n.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:t})):void 0,tool_choice:L$(n==null?void 0:n.tool_choice),response_format:this._getResponseFormat(n==null?void 0:n.response_format),seed:n==null?void 0:n.seed,...r,parallel_tool_calls:n==null?void 0:n.parallel_tool_calls,...this.audio||n!=null&&n.audio?{audio:this.audio||(n==null?void 0:n.audio)}:{},...this.modalities||n!=null&&n.modalities?{modalities:this.modalities||(n==null?void 0:n.modalities)}:{},...this.modelKwargs,prompt_cache_key:(n==null?void 0:n.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(n==null?void 0:n.promptCacheRetention)??this.promptCacheRetention,verbosity:(n==null?void 0:n.verbosity)??this.verbosity};(n==null?void 0:n.prediction)!==void 0&&(s.prediction=n.prediction),this.service_tier!==void 0&&(s.service_tier=this.service_tier),(n==null?void 0:n.service_tier)!==void 0&&(s.service_tier=n.service_tier);const i=this._getReasoningParams(n);return i!==void 0&&i.effort!==void 0&&(s.reasoning_effort=i.effort),Gl(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(n,e,t){var a,o,c;(a=e.signal)==null||a.throwIfAborted();const r={},s=this.invocationParams(e),i=mA({messages:n,model:this.model});if(s.stream){const u=this._streamResponseChunks(n,e,t),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),m=await this._getEstimatedTokenCountFromPrompt(n,f,h),g=await this._getNumTokensFromGenerations(d);return r.input_tokens=m,r.output_tokens=g,r.total_tokens=m+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:m}=(u==null?void 0:u.usage)??{};l&&(r.output_tokens=(r.output_tokens??0)+l),d&&(r.input_tokens=(r.input_tokens??0)+d),f&&(r.total_tokens=(r.total_tokens??0)+f),((h==null?void 0:h.audio_tokens)!==null||(h==null?void 0:h.cached_tokens)!==null)&&(r.input_token_details={...(h==null?void 0:h.audio_tokens)!==null&&{audio:h==null?void 0:h.audio_tokens},...(h==null?void 0:h.cached_tokens)!==null&&{cache_read:h==null?void 0:h.cached_tokens}}),((m==null?void 0:m.audio_tokens)!==null||(m==null?void 0:m.reasoning_tokens)!==null)&&(r.output_token_details={...(m==null?void 0:m.audio_tokens)!==null&&{audio:m==null?void 0:m.audio_tokens},...(m==null?void 0:m.reasoning_tokens)!==null&&{reasoning:m==null?void 0:m.reasoning_tokens}});const 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}:{}},xr(b.message)&&(b.message.usage_metadata=r),b.message=new Ve(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(n,e,t){var c,u,l,d,f,h,m,g,y,b,_;const r=mA({messages:n,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 S=(u=w==null?void 0:w.choices)==null?void 0:u[0];if(w.usage&&(o=w.usage),!S)continue;const{delta:T}=S;if(!T)continue;const A=this._convertCompletionsDeltaToBaseMessageChunk(T,w,i);i=T.role??i;const I={prompt:e.promptIndex??0,completion:S.index??0};if(typeof A.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const k={...I};S.finish_reason!=null&&(k.finish_reason=S.finish_reason,k.system_fingerprint=w.system_fingerprint,k.model_name=w.model,k.service_tier=w.service_tier),this.logprobs&&(k.logprobs=S.logprobs);const R=new fr({message:A,text:A.content,generationInfo:k});yield R,await(t==null?void 0:t.handleLLMNewToken(R.text??"",I,void 0,void 0,void 0,{chunk:R}))}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}},S={...((m=o.completion_tokens_details)==null?void 0:m.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}},T=new fr({message:new nt({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(S).length>0&&{output_token_details:S}}}),text:""});yield T,await(t==null?void 0:t.handleLLMNewToken(T.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:T}))}if((_=e.signal)!=null&&_.aborted)throw new Error("AbortError")}async completionWithRetry(n,e){const t=this._getClientOptions(e),r=n.response_format&&n.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!n.stream?await this.client.chat.completions.parse(n,t):await this.client.chat.completions.create(n,t)}catch(s){throw wb(s)}})}_convertCompletionsDeltaToBaseMessageChunk(n,e,t){return Vq({delta:n,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:t})}_convertCompletionsMessageToBaseMessage(n,e){return Hq({message:n,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const Ab={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"},Eb=["azureOpenAIApiKey","azureOpenAIApiVersion","azureOpenAIBasePath","azureOpenAIEndpoint","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","deploymentName","openAIApiKey","openAIApiVersion"];function kb(n,e){return typeof n=="string"?{model:n,deploymentName:n,azureOpenAIApiDeploymentName:n,...e??{}}:n??e}function Ib(n){if(this.azureOpenAIApiKey=(n==null?void 0:n.azureOpenAIApiKey)??(typeof(n==null?void 0:n.openAIApiKey)=="string"?n==null?void 0:n.openAIApiKey:void 0)??(typeof(n==null?void 0:n.apiKey)=="string"?n==null?void 0:n.apiKey:void 0)??Bt("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiInstanceName=(n==null?void 0:n.azureOpenAIApiInstanceName)??Bt("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(n==null?void 0:n.azureOpenAIApiDeploymentName)??(n==null?void 0:n.deploymentName)??Bt("AZURE_OPENAI_API_DEPLOYMENT_NAME"),this.azureOpenAIApiVersion=(n==null?void 0:n.azureOpenAIApiVersion)??(n==null?void 0:n.openAIApiVersion)??Bt("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=(n==null?void 0:n.azureOpenAIBasePath)??Bt("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIEndpoint=(n==null?void 0:n.azureOpenAIEndpoint)??Bt("AZURE_OPENAI_ENDPOINT"),this.azureADTokenProvider=n==null?void 0:n.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw new Error("Azure OpenAI API key or Token Provider not found")}function Z$(n){if(!this.client){const t={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},r=N$(t),{apiKey:s,...i}=this.clientConfig,a={...i,baseURL:r,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(a.apiKey=t.azureOpenAIApiKey),a.baseURL||delete a.baseURL,a.defaultHeaders=M$(a.defaultHeaders,!0,"2.0.0"),this.client=new kW({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...a})}const e={...this.clientConfig,...n};return this.azureOpenAIApiKey&&(e.headers={"api-key":this.azureOpenAIApiKey,...e.headers},e.query={"api-version":this.azureOpenAIApiVersion,...e.query}),e}function xb(n){const e=n;function t(r){return typeof r=="object"&&r!=null}if(t(e)&&t(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 Wq=class extends V${constructor(e,t){const r=kb(e,t);super(r);p(this,"azureOpenAIApiVersion");p(this,"azureOpenAIApiKey");p(this,"azureADTokenProvider");p(this,"azureOpenAIApiInstanceName");p(this,"azureOpenAIApiDeploymentName");p(this,"azureOpenAIBasePath");p(this,"azureOpenAIEndpoint");Ib.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...Ab}}get lc_secrets(){return{...super.lc_secrets,...Tb}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...Eb]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}_getClientOptions(e){return Z$.call(this,e)}toJSON(){return xb.call(this,super.toJSON())}};const Ao="__openai_function_call_ids__",To="__openai_custom_tool_call_ids__";function K$(n){return n.type==="url_citation"?{type:"citation",source:"url_citation",url:n.url,title:n.title,startIndex:n.start_index,endIndex:n.end_index}:n.type==="file_citation"?{type:"citation",source:"file_citation",title:n.filename,startIndex:n.index,file_id:n.file_id}:n.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:n.filename,startIndex:n.start_index,endIndex:n.end_index,file_id:n.file_id,container_id:n.container_id}:n.type==="file_path"?{type:"citation",source:"file_path",startIndex:n.index,file_id:n.file_id}:{type:"non_standard",value:n}}function qq(n){if(n.type==="url_citation"||n.type==="file_citation"||n.type==="container_file_citation"||n.type==="file_path")return n;if(n.type==="citation"){const e=n;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 n.type==="non_standard"?n.value:n}const W$=n=>{var r,s,i,a;const e={...((r=n==null?void 0:n.input_tokens_details)==null?void 0:r.cached_tokens)!=null&&{cache_read:(s=n==null?void 0:n.input_tokens_details)==null?void 0:s.cached_tokens}},t={...((i=n==null?void 0:n.output_tokens_details)==null?void 0:i.reasoning_tokens)!=null&&{reasoning:(a=n==null?void 0:n.output_tokens_details)==null?void 0:a.reasoning_tokens}};return{input_tokens:(n==null?void 0:n.input_tokens)??0,output_tokens:(n==null?void 0:n.output_tokens)??0,total_tokens:(n==null?void 0:n.total_tokens)??0,input_token_details:e,output_token_details:t}},q$=n=>{var o;if(n.error){const c=new Error(n.error.message);throw c.name=n.error.code,c}const e=[],t=[],r=[],s=n.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:n.model,created_at:n.created_at,id:n.id,incomplete_details:n.incomplete_details,metadata:n.metadata,object:n.object,output:s,status:n.status,user:n.user,service_tier:n.service_tier,model_name:n.model},a={};for(const c of n.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(K$),...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{t.push(dp(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),r.push(Nu(u,d))}a[Ao]??(a[Ao]={}),c.id&&(a[Ao][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=UW(c);u?(t.push(u),a[To]??(a[To]={}),c.id&&c.call_id&&(a[To][c.call_id]=c.id)):r.push(Nu(c,"Malformed custom tool call"))}else if(c.type==="computer_call"){const u=zW(c);u?t.push(u):r.push(Nu(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 Ve({id:n.id,content:e,tool_calls:t,invalid_tool_calls:r,usage_metadata:W$(n.usage),additional_kwargs:a,response_metadata:i})},Gq=n=>{const e=(n.summary.length>1?n.summary.reduce((t,r)=>{const s=t[t.length-1];return s.index===r.index?s.text+=r.text:t.push(r),t},[{...n.summary[0]}]):n.summary).map(t=>Object.fromEntries(Object.entries(t).filter(([r])=>r!=="index")));return{...n,summary:e}},Jq=n=>{var c,u,l;const e=[];let t={},r;const s=[],i={model_provider:"openai"},a={};let o;if(n.type==="response.output_text.delta")e.push({type:"text",text:n.delta,index:n.content_index});else if(n.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[K$(n.annotation)],index:n.content_index});else if(n.type==="response.output_item.added"&&n.item.type==="message"){const d="phase"in n.item?n.item.phase:void 0;d&&e.push({type:"text",text:"",phase:d,index:0})}else if(n.type==="response.output_item.added"&&n.item.type==="function_call")s.push({type:"tool_call_chunk",name:n.item.name,args:n.item.arguments,id:n.item.call_id,index:n.output_index}),a[Ao]={[n.item.call_id]:n.item.id};else if(n.type==="response.output_item.added"&&n.item.type==="custom_tool_call")s.push({type:"tool_call_chunk",isCustomTool:!0,name:n.item.name,args:n.item.input,id:n.item.call_id,index:n.output_index}),a[To]={[n.item.call_id]:n.item.id};else if(n.type==="response.output_item.done"&&n.item.type==="computer_call")s.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:n.item.action}),id:n.item.call_id,index:n.output_index}),a.tool_outputs=[n.item];else if(n.type==="response.output_item.done"&&n.item.type==="image_generation_call")n.item.result&&e.push({type:"image",mimeType:"image/png",data:n.item.result,id:n.item.id,metadata:{status:n.item.status}}),a.tool_outputs=[n.item];else if(n.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(n.item.type))a.tool_outputs=[n.item];else if(n.type==="response.created")o=n.response.id,i.id=n.response.id,i.model_name=n.response.model,i.model=n.response.model;else if(n.type==="response.completed"||n.type==="response.incomplete"){o=n.response.id;const d=q$(n.response);if(r=W$(n.response.usage),((u=(c=n.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(n.response))f!=="id"&&(f==="output"?i[f]=d.response_metadata.output:i[f]=h)}else if(n.type==="response.function_call_arguments.delta"||n.type==="response.custom_tool_call_input.delta")s.push({type:"tool_call_chunk",args:n.delta,index:n.output_index,...n.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(n.type==="response.web_search_call.completed"||n.type==="response.file_search_call.completed")t={tool_outputs:{id:n.item_id,type:n.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(n.type==="response.refusal.done")a.refusal=n.refusal;else if(n.type==="response.output_item.added"&&"item"in n&&n.item.type==="reasoning"){const d=n.item.summary?n.item.summary.map((h,m)=>({...h,index:m})):void 0;a.reasoning={id:n.item.id,type:n.item.type,...d?{summary:d}:{}};const f=(l=n.item.summary)==null?void 0:l.map(h=>h.text).filter(Boolean).join("");f&&e.push({type:"reasoning",reasoning:f})}else if(n.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...n.part,index:n.summary_index}]},n.part.text&&e.push({type:"reasoning",reasoning:n.part.text,index:n.summary_index});else if(n.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:n.delta,type:"summary_text",index:n.summary_index}]},n.delta&&e.push({type:"reasoning",reasoning:n.delta,index:n.summary_index});else return n.type==="response.image_generation_call.partial_image",null;return new fr({text:e.map(d=>d.text).join(""),message:new nt({id:o,content:e,tool_call_chunks:s,usage_metadata:r,additional_kwargs:a,response_metadata:i}),generationInfo:t})},Yq=n=>{var r;const e=Ve.isInstance(n)&&((r=n.response_metadata)==null?void 0:r.model_provider)==="openai";function*t(){const s=Bs(()=>{try{const _=Jl(n);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=Bs(()=>{var T;const S=(T=_.metadata)==null?void 0:T.detail;return S==="low"||S==="high"||S==="auto"?S:"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 S=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64");return{type:"input_image",detail:w,image_url:`data:${_.mimeType??"image/png"};base64,${S}`}}},m=_=>{if(_.fileId){const w=uA(_);return{type:"input_file",file_id:_.fileId,...w?{filename:w}:{}}}if(_.url){const w=uA(_);return{...w?{filename:w}:{},type:"input_file",file_url:_.url}}if(_.data){const w=Tf(_),S=typeof _.data=="string"?_.data:Buffer.from(_.data).toString("base64");return{type:"input_file",file_data:`data:${_.mimeType??"application/octet-stream"};base64,${S}`,filename:w}}},g=_=>{const w=Bs(()=>{var A;if(Array.isArray(_.summary)){const I=((A=_.summary)==null?void 0:A.map(k=>k==null?void 0:k.text).filter(k=>typeof k=="string"))??[];if(I.length>0)return I}return _.reasoning?[_.reasoning]:[]}),S=w.length>0?w.map(A=>({type:"summary_text",text:A})):[{type:"summary_text",text:""}],T={type:"reasoning",id:_.id??"",summary:S};return _.reasoning&&(T.content=[{type:"reasoning_text",text:_.reasoning}]),T},y=_=>({type:"function_call",name:_.name??"",call_id:_.id??"",arguments:f(_.args)}),b=_=>{const w=f(_.output),S=_.status==="success"?"completed":_.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:_.toolCallId??"",output:w,...S?{status:S}:{}}};for(const _ of n.contentBlocks)if(_.type==="text"){const w=Bs(()=>{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=m(_);w&&d([w])}else if(_.type==="image"){const w=h(_);w&&d([w])}else if(_.type==="video"){const w=m(_);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 S=w.args.join("");!w.name&&!S||(yield{type:"function_call",call_id:_,name:w.name??"",arguments:S})}for(const[_,w]of u){if(!_||o.has(_))continue;const S=w.args.join("");!w.name&&!S||(yield{type:"function_call",call_id:_,name:w.name??"",arguments:S})}}return Array.from(t())},gA=({messages:n,zdrEnabled:e,model:t})=>n.flatMap(r=>{var o,c,u,l;const s=r.response_metadata;if((s==null?void 0:s.output_version)==="v1")return Yq(r);const i=r.additional_kwargs;let a=Jl(r);if(a==="system"&&Gl(t)&&(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 m=d.content.find(y=>y.type==="computer_screenshot");if(m)return m;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=Gq(f);d.push(w)}let{content:m}=r;if(i!=null&&i.refusal&&(typeof m=="string"&&(m=[{type:"output_text",text:m,annotations:[]}]),m=[...m,{type:"refusal",refusal:i.refusal}]),typeof m=="string"||m.length>0){const w={type:"message",role:"assistant",...r.id&&!e&&r.id.startsWith("msg_")?{id:r.id}:{},content:Bs(()=>typeof m=="string"?m:m.flatMap(S=>{if(S.type==="text"){const T=S;return{type:"output_text",text:T.text,annotations:(T.annotations??[]).map(qq)}}return S.type==="output_text"||S.type==="refusal"?S:[]})),phase:Bs(()=>{var S;if(Array.isArray(m))return(S=m.find(T=>"phase"in T&&typeof T.phase=="string"))==null?void 0:S.phase})};d.push(w)}const g=i==null?void 0:i[Ao],y=i==null?void 0:i[To];Ve.isInstance(r)&&((u=r.tool_calls)!=null&&u.length)?d.push(...r.tool_calls.map(w=>BW(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}:FW(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(S=>_.includes(S.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}),Ir(h)?xl(h,H$):h.type==="text"?{type:"input_text",text:h.text}:h.type==="image_url"?{type:"input_image",image_url:Bs(()=>{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:Bs(()=>{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 G$=class extends Sb{constructor(n,e){super(vb(n,e))}invocationParams(n){var s;let e;(n==null?void 0:n.strict)!==void 0&&(e=n.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const t={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:n==null?void 0:n.previous_response_id,truncation:n==null?void 0:n.truncation,include:n==null?void 0:n.include,tools:(s=n==null?void 0:n.tools)!=null&&s.length?this._reduceChatOpenAITools(n.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:DW(n==null?void 0:n.tool_choice)?n==null?void 0:n.tool_choice:(()=>{const i=L$(n==null?void 0:n.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(n!=null&&n.text)return n.text;const i=this._getResponseFormat(n==null?void 0:n.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:n==null?void 0:n.verbosity}:void 0:{format:i,verbosity:n==null?void 0:n.verbosity}})(),parallel_tool_calls:n==null?void 0:n.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:(n==null?void 0:n.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(n==null?void 0:n.promptCacheRetention)??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(n);return r!==void 0&&(t.reasoning=r),t}async _generate(n,e,t){var s,i;(s=e.signal)==null||s.throwIfAborted();const r=this.invocationParams(e);if(r.stream){const a=this._streamResponseChunks(n,e,t);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:gA({messages:n,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:q$(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(n,e,t){var s;const r=await this.completionWithRetry({...this.invocationParams(e),input:gA({messages:n,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=Jq(i);a!=null&&(yield a,await(t==null?void 0:t.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a})))}}async completionWithRetry(n,e){return this.caller.call(async()=>{var r,s;const t=this._getClientOptions(e);try{return((s=(r=n.text)==null?void 0:r.format)==null?void 0:s.type)==="json_schema"&&!n.stream?await this.client.responses.parse(n,t):await this.client.responses.create(n,t)}catch(i){throw wb(i)}})}_reduceChatOpenAITools(n,e){const t=[];for(const r of n)if(bb(r))r.type==="image_generation"&&(e!=null&&e.stream)&&(r.partial_images=1),t.push(r);else if(kf(r)){const s=r.metadata.customTool;t.push({type:"custom",name:s.name,description:s.description,format:s.format})}else if(Sc(r)){const s={};for(const[i,a]of Object.entries(r))i!=="type"&&i!=="function"&&(s[i]=a);t.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 D$(r)&&t.push(HW(r));return t}},Xq=class extends G${constructor(e,t){const r=kb(e,t);super(r);p(this,"azureOpenAIApiVersion");p(this,"azureOpenAIApiKey");p(this,"azureADTokenProvider");p(this,"azureOpenAIApiInstanceName");p(this,"azureOpenAIApiDeploymentName");p(this,"azureOpenAIBasePath");p(this,"azureOpenAIEndpoint");Ib.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...Ab}}get lc_secrets(){return{...super.lc_secrets,...Tb}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...Eb]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}_getClientOptions(e){return Z$.call(this,e)}toJSON(){return xb.call(this,super.toJSON())}},kh=class J$ extends Sb{constructor(t,r){const s=vb(t,r);super(s);p(this,"useResponsesApi",!1);p(this,"responses");p(this,"completions");p(this,"fields");this.fields=s,this.useResponsesApi=(s==null?void 0:s.useResponsesApi)??!1,this.responses=(s==null?void 0:s.responses)??new G$(s),this.completions=(s==null?void 0:s.completions)??new V$(s)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(t){var a,o,c,u,l;const r=(a=t==null?void 0:t.tools)==null?void 0:a.some(bb),s=(t==null?void 0:t.previous_response_id)!=null||(t==null?void 0:t.text)!=null||(t==null?void 0:t.truncation)!=null||(t==null?void 0:t.include)!=null||((o=t==null?void 0:t.reasoning)==null?void 0:o.summary)!=null||((c=this.reasoning)==null?void 0:c.summary)!=null,i=((u=t==null?void 0:t.tools)==null?void 0:u.some(D$))||((l=t==null?void 0:t.tools)==null?void 0:l.some(kf));return this.useResponsesApi||r||s||i||$W(this.model)}getLsParams(t){const r=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(t){const r=this._combineCallOptions(t);return this._useResponsesApi(t)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(t,r,s){return this._useResponsesApi(r)?this.responses._generate(t,r,s):this.completions._generate(t,r,s)}async*_streamResponseChunks(t,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(t,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(t,this._combineCallOptions(r),s)}withConfig(t){const r=new J$(this.fields);return r.defaultOptions={...this.defaultOptions,...t},r}},Qq=class extends kh{constructor(e,t){const r=kb(e,t);super({...r,completions:new Wq(r),responses:new Xq(r)});p(this,"azureOpenAIApiVersion");p(this,"azureOpenAIApiKey");p(this,"azureADTokenProvider");p(this,"azureOpenAIApiInstanceName");p(this,"azureOpenAIApiDeploymentName");p(this,"azureOpenAIBasePath");p(this,"azureOpenAIEndpoint");Ib.call(this,r)}_llmType(){return"azure_openai"}get lc_aliases(){return{...super.lc_aliases,...Ab}}get lc_secrets(){return{...super.lc_secrets,...Tb}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...Eb]}getLsParams(e){const t=super.getLsParams(e);return t.ls_provider="azure",t}_getStructuredOutputMethod(e){const t={...e};return this.model.startsWith("gpt-4o")&&(t==null?void 0:t.method)===void 0?"functionCalling":super._getStructuredOutputMethod(t)}toJSON(){return xb.call(this,super.toJSON())}};const eG=Me({type:Ze("screenshot")}),tG=Me({type:Ze("click"),x:gt(),y:gt(),button:mp(["left","right","wheel","back","forward"]).default("left")}),nG=Me({type:Ze("double_click"),x:gt(),y:gt(),button:mp(["left","right","wheel","back","forward"]).default("left")}),rG=Me({type:Ze("drag"),path:Ca(Me({x:gt(),y:gt()}))}),sG=Me({type:Ze("keypress"),keys:Ca(Xe())}),iG=Me({type:Ze("move"),x:gt(),y:gt()}),aG=Me({type:Ze("scroll"),x:gt(),y:gt(),scroll_x:gt(),scroll_y:gt()}),oG=Me({type:Ze("type"),text:Xe()}),cG=Me({type:Ze("wait"),duration:gt().optional()}),uG=Zl([eG,tG,nG,rG,sG,iG,aG,oG,cG]);Me({action:uG});const lG=Me({type:Ze("exec"),command:Ca(Xe()),env:iH(Xe(),Xe()).optional(),working_directory:Xe().optional(),timeout_ms:gt().optional(),user:Xe().optional()});Zl([lG]);Me({commands:Ca(Xe()).describe("Array of shell commands to execute"),timeout_ms:gt().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:gt().optional().describe("Optional maximum number of characters to return from each command")});const dG=Me({type:Ze("create_file"),path:Xe(),diff:Xe()}),hG=Me({type:Ze("update_file"),path:Xe(),diff:Xe()}),fG=Me({type:Ze("delete_file"),path:Xe()});Zl([dG,hG,fG]);function Na(n){if(typeof n=="object"&&n!==null){const e={...n};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const t in e)t in e&&(Array.isArray(e[t])?e[t]=e[t].map(Na):typeof e[t]=="object"&&e[t]!==null&&(e[t]=Na(e[t])));return e}return n}function ry(n){const{$schema:e,...t}=Na(Xt(n)||Or(n)?At(n):n);return t}function pG(n){const{$schema:e,...t}=Na(n);return t}function Eo(n,e,t=[]){if(n==null||typeof n!="object")return;const r=n;if(Array.isArray(r.enum)&&r.enum.some(s=>s==="")){const s=t.length?` at path "${t.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))Eo(i,e,[...t,s]);r.items&&Eo(r.items,e,[...t,"[]"]);for(const s of["anyOf","oneOf","allOf"]){const i=r[s];Array.isArray(i)&&i.forEach((a,o)=>Eo(a,e,[...t,`${s}[${o}]`]))}r.additionalProperties&&typeof r.additionalProperties=="object"&&Eo(r.additionalProperties,e,[...t,"additionalProperties"])}const Ob="__gemini_function_call_thought_signatures__",mG="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",gG=n=>n();function _G(n){return ks.isInstance(n)?n.role:n.type}function yG(n){switch(n){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: ${n}`)}}function wG(n){if("mimeType"in n&&"data"in n)return{inlineData:{mimeType:n.mimeType,data:n.data}};if("mimeType"in n&&"fileUri"in n)return{fileData:{mimeType:n.mimeType,fileUri:n.fileUri}};throw new Error("Invalid media content")}function bG(n,e){var t;return(t=e.map(r=>xr(r)?r.tool_calls??[]:[]).flat().find(r=>r.id===n.tool_call_id))==null?void 0:t.name}function Lc(n,e){if("data"in n&&n.data!==void 0){const t=n.data instanceof Uint8Array?btoa(String.fromCharCode(...n.data)):n.data;return{inlineData:{mimeType:n.mimeType||e,data:t}}}if("url"in n&&n.url!==void 0){const t=Gr({dataUrl:n.url});return t?{inlineData:{mimeType:t.mime_type,data:t.data}}:{fileData:{mimeType:n.mimeType||e,fileUri:n.url}}}throw"fileId"in n&&n.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(n)}`)}function vG(n){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!n)throw new Error("This model does not support images");if(e.source_type==="url"){const t=Gr({dataUrl:e.url});return t?{inlineData:{mimeType:t.mime_type,data:t.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(!n)throw new Error("This model does not support audio");if(e.source_type==="url"){const t=Gr({dataUrl:e.url});return t?{inlineData:{mimeType:t.mime_type,data:t.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(!n)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){const t=Gr({dataUrl:e.url});return t?{inlineData:{mimeType:t.mime_type,data:t.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 _A(n,e){var t;if(Ir(n))return xl(n,vG(e));if(n.type==="text")return{text:n.text};if(n.type==="executableCode")return{executableCode:n.executableCode};if(n.type==="codeExecutionResult")return{codeExecutionResult:n.codeExecutionResult};if(n.type==="image_url"){if(!e)throw new Error("This model does not support images");let r;if(typeof n.image_url=="string")r=n.image_url;else if(typeof n.image_url=="object"&&"url"in n.image_url)r=n.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(n.type==="media")return wG(n);if(n.type==="image")return Lc(n,"image/png");if(n.type==="video")return Lc(n,"video/mp4");if(n.type==="audio")return Lc(n,"audio/mpeg");if(n.type==="file")return Lc(n,"application/octet-stream");if(n.type==="text-plain")return"text"in n&&typeof n.text=="string"?{text:n.text}:Lc(n,"text/plain");if(n.type==="tool_use")return{functionCall:{name:n.name,args:n.input}};if(n.type==="tool_call")return{functionCall:{name:n.name,args:n.args}};if((t=n.type)!=null&&t.includes("/")&&n.type.split("/").length===2&&"data"in n&&typeof n.data=="string")return{inlineData:{mimeType:n.type,data:n.data}};if(n.type==="thinking"){const r=n;return{text:r.thinking,thought:!0,...r.signature?{thoughtSignature:r.signature}:{}}}else{if("functionCall"in n)return;throw"type"in n?new Error(`Unknown content type ${n.type}`):new Error(`Unknown content ${JSON.stringify(n)}`)}}}function SG(n,e,t,r){var o,c;if(_a(n)){const u=n.name??bG(n,t);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 "${n.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const l=Array.isArray(n.content)?n.content.map(d=>_A(d,e)).filter(d=>d!==void 0):n.content;return n.status==="error"?[{functionResponse:{name:u,response:{error:{details:l}}}}]:[{functionResponse:{name:u,response:{result:l}}}]}let s=[];const i=[];typeof n.content=="string"&&n.content&&i.push({text:n.content}),Array.isArray(n.content)&&i.push(...n.content.map(u=>_A(u,e)).filter(u=>u!==void 0));const a=(o=n.additional_kwargs)==null?void 0:o[Ob];return xr(n)&&((c=n.tool_calls)!=null&&c.length)&&(s=n.tool_calls.map(u=>{const l=gG(()=>{if(u.id){const d=a==null?void 0:a[u.id];if(d)return d}return r!=null&&r.includes("gemini-3")?mG:""});return{functionCall:{name:u.name,args:u.args},...l?{thoughtSignature:l}:{}}})),[...i,...s]}function yA(n,e,t=!1,r){return n.reduce((s,i,a)=>{if(!Rt(i))throw new Error("Unsupported message input");const o=_G(i);if(o==="system"&&a!==0)throw new Error("System message should be the first one");const c=yG(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=SG(i,e,n.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"&&!t)&&(d="user");const f={role:d,parts:l};return{mergeWithPreviousContent:o==="system"&&!t,content:[...s.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function AG(n,e){var l,d,f,h,m;if(!n.candidates||n.candidates.length===0||!n.candidates[0])return{generations:[],llmOutput:{filters:n.promptFeedback}};const[t]=n.candidates,{content:r,...s}=t,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:Ni()}),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 Ve({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,[Ob]:c},usage_metadata:e==null?void 0:e.usageMetadata}),generationInfo:s}],llmOutput:{tokenUsage:{promptTokens:(f=e==null?void 0:e.usageMetadata)==null?void 0:f.input_tokens,completionTokens:(h=e==null?void 0:e.usageMetadata)==null?void 0:h.output_tokens,totalTokens:(m=e==null?void 0:e.usageMetadata)==null?void 0:m.total_tokens}}}}function TG(n,e){var d,f;if(!n.candidates||n.candidates.length===0)return null;const[t]=n.candidates,{content:r,...s}=t,i=(d=r.parts)==null?void 0:d.reduce((h,m)=>("functionCall"in m&&m.functionCall&&h.push({...m,id:"id"in m.functionCall&&typeof m.functionCall.id=="string"?m.functionCall.id:Ni()}),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,m)=>("thoughtSignature"in m&&typeof m.thoughtSignature=="string"&&(h[m.id]=m.thoughtSignature),h),{});return new fr({text:c,message:new nt({content:a||"",name:r?r.role:void 0,tool_call_chunks:u,additional_kwargs:{[Ob]:l},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:s})}function EG(n){return n.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?n:[{functionDeclarations:n.map(e=>{if(Ys(e)){const t=ry(e.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(Eo(t,e.name),{name:e.name,description:e.description,parameters:t})}if(Sc(e)){const t=pG(e.function.parameters);return Eo(t,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:t}}return e})}]}function wA(n,e){const t={input_tokens:(n==null?void 0:n.promptTokenCount)??0,output_tokens:(n==null?void 0:n.candidatesTokenCount)??0,total_tokens:(n==null?void 0:n.totalTokenCount)??0};if(n!=null&&n.cachedContentTokenCount&&(t.input_token_details??(t.input_token_details={}),t.input_token_details.cache_read=n.cachedContentTokenCount),e==="gemini-3-pro-preview"){const r=Math.max(0,(n==null?void 0:n.promptTokenCount)??-2e5),s=Math.max(0,(n==null?void 0:n.cachedContentTokenCount)??-2e5);r&&(t.input_token_details={...t.input_token_details,over_200k:r}),s&&(t.input_token_details={...t.input_token_details,cache_read_over_200k:s})}return t}var kG=class extends Ac{constructor(e){super(e);p(this,"lc_namespace",["langchain","google_genai","output_parsers"]);p(this,"returnId",!1);p(this,"keyName");p(this,"returnSingle",!1);p(this,"zodSchema");p(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}async _validateResult(e){if(this.serializableSchema!==void 0){const r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new Tn(`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 t=await tp(this.zodSchema,e);if(t.success)return t.data;throw new Tn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const t=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(t[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[r]=t;return await this._validateResult(r.args)}},bA;(function(n){n.STRING="string",n.NUMBER="number",n.INTEGER="integer",n.BOOLEAN="boolean",n.ARRAY="array",n.OBJECT="object"})(bA||(bA={}));/**
|
|
392
|
+
* @license
|
|
393
|
+
* Copyright 2024 Google LLC
|
|
394
|
+
*
|
|
395
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
396
|
+
* you may not use this file except in compliance with the License.
|
|
397
|
+
* You may obtain a copy of the License at
|
|
398
|
+
*
|
|
399
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
400
|
+
*
|
|
401
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
402
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
403
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
404
|
+
* See the License for the specific language governing permissions and
|
|
405
|
+
* limitations under the License.
|
|
406
|
+
*/var vA;(function(n){n.LANGUAGE_UNSPECIFIED="language_unspecified",n.PYTHON="python"})(vA||(vA={}));var SA;(function(n){n.OUTCOME_UNSPECIFIED="outcome_unspecified",n.OUTCOME_OK="outcome_ok",n.OUTCOME_FAILED="outcome_failed",n.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(SA||(SA={}));/**
|
|
407
|
+
* @license
|
|
408
|
+
* Copyright 2024 Google LLC
|
|
409
|
+
*
|
|
410
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
411
|
+
* you may not use this file except in compliance with the License.
|
|
412
|
+
* You may obtain a copy of the License at
|
|
413
|
+
*
|
|
414
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
415
|
+
*
|
|
416
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
417
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
418
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
419
|
+
* See the License for the specific language governing permissions and
|
|
420
|
+
* limitations under the License.
|
|
421
|
+
*/const AA=["user","model","function","system"];var TA;(function(n){n.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",n.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",n.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",n.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",n.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",n.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(TA||(TA={}));var EA;(function(n){n.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",n.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",n.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",n.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",n.BLOCK_NONE="BLOCK_NONE"})(EA||(EA={}));var kA;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(kA||(kA={}));var IA;(function(n){n.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",n.SAFETY="SAFETY",n.OTHER="OTHER"})(IA||(IA={}));var Uu;(function(n){n.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",n.STOP="STOP",n.MAX_TOKENS="MAX_TOKENS",n.SAFETY="SAFETY",n.RECITATION="RECITATION",n.LANGUAGE="LANGUAGE",n.BLOCKLIST="BLOCKLIST",n.PROHIBITED_CONTENT="PROHIBITED_CONTENT",n.SPII="SPII",n.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",n.OTHER="OTHER"})(Uu||(Uu={}));var xA;(function(n){n.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",n.RETRIEVAL_QUERY="RETRIEVAL_QUERY",n.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",n.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",n.CLASSIFICATION="CLASSIFICATION",n.CLUSTERING="CLUSTERING"})(xA||(xA={}));var ko;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE"})(ko||(ko={}));var OA;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(OA||(OA={}));/**
|
|
422
|
+
* @license
|
|
423
|
+
* Copyright 2024 Google LLC
|
|
424
|
+
*
|
|
425
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
426
|
+
* you may not use this file except in compliance with the License.
|
|
427
|
+
* You may obtain a copy of the License at
|
|
428
|
+
*
|
|
429
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
430
|
+
*
|
|
431
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
432
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
433
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
434
|
+
* See the License for the specific language governing permissions and
|
|
435
|
+
* limitations under the License.
|
|
436
|
+
*/class Sn extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class Xa extends Sn{constructor(e,t){super(e),this.response=t}}class Y$ extends Sn{constructor(e,t,r,s){super(e),this.status=t,this.statusText=r,this.errorDetails=s}}class $i extends Sn{}class X$ extends Sn{}/**
|
|
437
|
+
* @license
|
|
438
|
+
* Copyright 2024 Google LLC
|
|
439
|
+
*
|
|
440
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
441
|
+
* you may not use this file except in compliance with the License.
|
|
442
|
+
* You may obtain a copy of the License at
|
|
443
|
+
*
|
|
444
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
445
|
+
*
|
|
446
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
447
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
448
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
449
|
+
* See the License for the specific language governing permissions and
|
|
450
|
+
* limitations under the License.
|
|
451
|
+
*/const IG="https://generativelanguage.googleapis.com",xG="v1beta",OG="0.24.1",CG="genai-js";var Ma;(function(n){n.GENERATE_CONTENT="generateContent",n.STREAM_GENERATE_CONTENT="streamGenerateContent",n.COUNT_TOKENS="countTokens",n.EMBED_CONTENT="embedContent",n.BATCH_EMBED_CONTENTS="batchEmbedContents"})(Ma||(Ma={}));class $G{constructor(e,t,r,s,i){this.model=e,this.task=t,this.apiKey=r,this.stream=s,this.requestOptions=i}toString(){var e,t;const r=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||xG;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||IG}/${r}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function RG(n){const e=[];return n!=null&&n.apiClient&&e.push(n.apiClient),e.push(`${CG}/${OG}`),e.join(" ")}async function PG(n){var e;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",RG(n.requestOptions)),t.append("x-goog-api-key",n.apiKey);let r=(e=n.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(r){if(!(r instanceof Headers))try{r=new Headers(r)}catch(s){throw new $i(`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 $i(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new $i(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function NG(n,e,t,r,s,i){const a=new $G(n,e,t,r,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},DG(i)),{method:"POST",headers:await PG(a),body:s})}}async function Yl(n,e,t,r,s,i={},a=fetch){const{url:o,fetchOptions:c}=await NG(n,e,t,r,s,i);return MG(o,c,a)}async function MG(n,e,t=fetch){let r;try{r=await t(n,e)}catch(s){jG(s,n)}return r.ok||await LG(r,n),r}function jG(n,e){let t=n;throw t.name==="AbortError"?(t=new X$(`Request aborted when fetching ${e.toString()}: ${n.message}`),t.stack=n.stack):n instanceof Y$||n instanceof $i||(t=new Sn(`Error fetching from ${e.toString()}: ${n.message}`),t.stack=n.stack),t}async function LG(n,e){let t="",r;try{const s=await n.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,r=s.error.details)}catch{}throw new Y$(`Error fetching from ${e.toString()}: [${n.status} ${n.statusText}] ${t}`,n.status,n.statusText,r)}function DG(n){const e={};if((n==null?void 0:n.signal)!==void 0||(n==null?void 0:n.timeout)>=0){const t=new AbortController;(n==null?void 0:n.timeout)>=0&&setTimeout(()=>t.abort(),n.timeout),n!=null&&n.signal&&n.signal.addEventListener("abort",()=>{t.abort()}),e.signal=t.signal}return e}/**
|
|
452
|
+
* @license
|
|
453
|
+
* Copyright 2024 Google LLC
|
|
454
|
+
*
|
|
455
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
456
|
+
* you may not use this file except in compliance with the License.
|
|
457
|
+
* You may obtain a copy of the License at
|
|
458
|
+
*
|
|
459
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
460
|
+
*
|
|
461
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
462
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
463
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
464
|
+
* See the License for the specific language governing permissions and
|
|
465
|
+
* limitations under the License.
|
|
466
|
+
*/function Cb(n){return n.text=()=>{if(n.candidates&&n.candidates.length>0){if(n.candidates.length>1&&console.warn(`This response had ${n.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),Ih(n.candidates[0]))throw new Xa(`${fi(n)}`,n);return UG(n)}else if(n.promptFeedback)throw new Xa(`Text not available. ${fi(n)}`,n);return""},n.functionCall=()=>{if(n.candidates&&n.candidates.length>0){if(n.candidates.length>1&&console.warn(`This response had ${n.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),Ih(n.candidates[0]))throw new Xa(`${fi(n)}`,n);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),CA(n)[0]}else if(n.promptFeedback)throw new Xa(`Function call not available. ${fi(n)}`,n)},n.functionCalls=()=>{if(n.candidates&&n.candidates.length>0){if(n.candidates.length>1&&console.warn(`This response had ${n.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),Ih(n.candidates[0]))throw new Xa(`${fi(n)}`,n);return CA(n)}else if(n.promptFeedback)throw new Xa(`Function call not available. ${fi(n)}`,n)},n}function UG(n){var e,t,r,s;const i=[];if(!((t=(e=n.candidates)===null||e===void 0?void 0:e[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(r=n.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+`
|
|
467
|
+
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function CA(n){var e,t,r,s;const i=[];if(!((t=(e=n.candidates)===null||e===void 0?void 0:e[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(r=n.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 zG=[Uu.RECITATION,Uu.SAFETY,Uu.LANGUAGE];function Ih(n){return!!n.finishReason&&zG.includes(n.finishReason)}function fi(n){var e,t,r;let s="";if((!n.candidates||n.candidates.length===0)&&n.promptFeedback)s+="Response was blocked",!((e=n.promptFeedback)===null||e===void 0)&&e.blockReason&&(s+=` due to ${n.promptFeedback.blockReason}`),!((t=n.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${n.promptFeedback.blockReasonMessage}`);else if(!((r=n.candidates)===null||r===void 0)&&r[0]){const i=n.candidates[0];Ih(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function dl(n){return this instanceof dl?(this.v=n,this):new dl(n)}function FG(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,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(m,g){i.push([f,h,m,g])>1||o(f,h)})})}function o(f,h){try{c(r[f](h))}catch(m){d(i[0][3],m)}}function c(f){f.value instanceof dl?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])}}/**
|
|
468
|
+
* @license
|
|
469
|
+
* Copyright 2024 Google LLC
|
|
470
|
+
*
|
|
471
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
472
|
+
* you may not use this file except in compliance with the License.
|
|
473
|
+
* You may obtain a copy of the License at
|
|
474
|
+
*
|
|
475
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
476
|
+
*
|
|
477
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
478
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
479
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
480
|
+
* See the License for the specific language governing permissions and
|
|
481
|
+
* limitations under the License.
|
|
482
|
+
*/const $A=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function BG(n){const e=n.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=ZG(e),[r,s]=t.tee();return{stream:VG(r),response:HG(s)}}async function HG(n){const e=[],t=n.getReader();for(;;){const{done:r,value:s}=await t.read();if(r)return Cb(KG(e));e.push(s)}}function VG(n){return FG(this,arguments,function*(){const t=n.getReader();for(;;){const{value:r,done:s}=yield dl(t.read());if(s)break;yield yield dl(Cb(r))}})}function ZG(n){const e=n.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 Sn("Failed to parse stream"));return}r.close();return}s+=a;let c=s.match($A),u;for(;c;){try{u=JSON.parse(c[1])}catch{r.error(new Sn(`Error parsing JSON response: "${c[1]}"`));return}r.enqueue(u),s=s.substring(c[0].length),c=s.match($A)}return i()}).catch(a=>{let o=a;throw o.stack=a.stack,o.name==="AbortError"?o=new X$("Request aborted when reading from the stream"):o=new Sn("Error reading from the stream"),o})}}})}function KG(n){const e=n[n.length-1],t={promptFeedback:e==null?void 0:e.promptFeedback};for(const r of n){if(r.candidates){let s=0;for(const i of r.candidates)if(t.candidates||(t.candidates=[]),t.candidates[s]||(t.candidates[s]={index:s}),t.candidates[s].citationMetadata=i.citationMetadata,t.candidates[s].groundingMetadata=i.groundingMetadata,t.candidates[s].finishReason=i.finishReason,t.candidates[s].finishMessage=i.finishMessage,t.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){t.candidates[s].content||(t.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=""),t.candidates[s].content.parts.push(a)}s++}r.usageMetadata&&(t.usageMetadata=r.usageMetadata)}return t}/**
|
|
483
|
+
* @license
|
|
484
|
+
* Copyright 2024 Google LLC
|
|
485
|
+
*
|
|
486
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
487
|
+
* you may not use this file except in compliance with the License.
|
|
488
|
+
* You may obtain a copy of the License at
|
|
489
|
+
*
|
|
490
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
491
|
+
*
|
|
492
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
493
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
494
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
495
|
+
* See the License for the specific language governing permissions and
|
|
496
|
+
* limitations under the License.
|
|
497
|
+
*/async function Q$(n,e,t,r){const s=await Yl(e,Ma.STREAM_GENERATE_CONTENT,n,!0,JSON.stringify(t),r);return BG(s)}async function eR(n,e,t,r){const i=await(await Yl(e,Ma.GENERATE_CONTENT,n,!1,JSON.stringify(t),r)).json();return{response:Cb(i)}}/**
|
|
498
|
+
* @license
|
|
499
|
+
* Copyright 2024 Google LLC
|
|
500
|
+
*
|
|
501
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
502
|
+
* you may not use this file except in compliance with the License.
|
|
503
|
+
* You may obtain a copy of the License at
|
|
504
|
+
*
|
|
505
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
506
|
+
*
|
|
507
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
508
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
509
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
510
|
+
* See the License for the specific language governing permissions and
|
|
511
|
+
* limitations under the License.
|
|
512
|
+
*/function tR(n){if(n!=null){if(typeof n=="string")return{role:"system",parts:[{text:n}]};if(n.text)return{role:"system",parts:[n]};if(n.parts)return n.role?n:{role:"system",parts:n.parts}}}function hl(n){let e=[];if(typeof n=="string")e=[{text:n}];else for(const t of n)typeof t=="string"?e.push({text:t}):e.push(t);return WG(e)}function WG(n){const e={role:"user",parts:[]},t={role:"function",parts:[]};let r=!1,s=!1;for(const i of n)"functionResponse"in i?(t.parts.push(i),s=!0):(e.parts.push(i),r=!0);if(r&&s)throw new Sn("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 Sn("No content is provided for sending chat message.");return r?e:t}function qG(n,e){var t;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:(t=e==null?void 0:e.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const s=n.generateContentRequest!=null;if(n.contents){if(s)throw new $i("CountTokensRequest must have one of contents or generateContentRequest, not both.");r.contents=n.contents}else if(s)r=Object.assign(Object.assign({},r),n.generateContentRequest);else{const i=hl(n);r.contents=[i]}return{generateContentRequest:r}}function RA(n){let e;return n.contents?e=n:e={contents:[hl(n)]},n.systemInstruction&&(e.systemInstruction=tR(n.systemInstruction)),e}function GG(n){return typeof n=="string"||Array.isArray(n)?{content:hl(n)}:n}/**
|
|
513
|
+
* @license
|
|
514
|
+
* Copyright 2024 Google LLC
|
|
515
|
+
*
|
|
516
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
517
|
+
* you may not use this file except in compliance with the License.
|
|
518
|
+
* You may obtain a copy of the License at
|
|
519
|
+
*
|
|
520
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
521
|
+
*
|
|
522
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
523
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
524
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
525
|
+
* See the License for the specific language governing permissions and
|
|
526
|
+
* limitations under the License.
|
|
527
|
+
*/const PA=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],JG={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function YG(n){let e=!1;for(const t of n){const{role:r,parts:s}=t;if(!e&&r!=="user")throw new Sn(`First content should be with role 'user', got ${r}`);if(!AA.includes(r))throw new Sn(`Each item should include role field. Got ${r} but valid roles are: ${JSON.stringify(AA)}`);if(!Array.isArray(s))throw new Sn("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new Sn("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 PA)c in o&&(i[c]+=1);const a=JG[r];for(const o of PA)if(!a.includes(o)&&i[o]>0)throw new Sn(`Content with role '${r}' can't contain '${o}' part`);e=!0}}function NA(n){var e;if(n.candidates===void 0||n.candidates.length===0)return!1;const t=(e=n.candidates[0])===null||e===void 0?void 0:e.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const r of t.parts)if(r===void 0||Object.keys(r).length===0||r.text!==void 0&&r.text==="")return!1;return!0}/**
|
|
528
|
+
* @license
|
|
529
|
+
* Copyright 2024 Google LLC
|
|
530
|
+
*
|
|
531
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
532
|
+
* you may not use this file except in compliance with the License.
|
|
533
|
+
* You may obtain a copy of the License at
|
|
534
|
+
*
|
|
535
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
536
|
+
*
|
|
537
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
538
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
539
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
540
|
+
* See the License for the specific language governing permissions and
|
|
541
|
+
* limitations under the License.
|
|
542
|
+
*/const MA="SILENT_ERROR";class XG{constructor(e,t,r,s={}){this.model=t,this.params=r,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,r!=null&&r.history&&(YG(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){var r,s,i,a,o,c;await this._sendPromise;const u=hl(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),t);let f;return this._sendPromise=this._sendPromise.then(()=>eR(this._apiKey,this.model,l,d)).then(h=>{var m;if(NA(h.response)){this._history.push(u);const g=Object.assign({parts:[],role:"model"},(m=h.response.candidates)===null||m===void 0?void 0:m[0].content);this._history.push(g)}else{const g=fi(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,t={}){var r,s,i,a,o,c;await this._sendPromise;const u=hl(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),t),f=Q$(this._apiKey,this.model,l,d);return this._sendPromise=this._sendPromise.then(()=>f).catch(h=>{throw new Error(MA)}).then(h=>h.response).then(h=>{if(NA(h)){this._history.push(u);const m=Object.assign({},h.candidates[0].content);m.role||(m.role="model"),this._history.push(m)}else{const m=fi(h);m&&console.warn(`sendMessageStream() was unsuccessful. ${m}. Inspect response object for details.`)}}).catch(h=>{h.message!==MA&&console.error(h)}),f}}/**
|
|
543
|
+
* @license
|
|
544
|
+
* Copyright 2024 Google LLC
|
|
545
|
+
*
|
|
546
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
547
|
+
* you may not use this file except in compliance with the License.
|
|
548
|
+
* You may obtain a copy of the License at
|
|
549
|
+
*
|
|
550
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
551
|
+
*
|
|
552
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
553
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
554
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
555
|
+
* See the License for the specific language governing permissions and
|
|
556
|
+
* limitations under the License.
|
|
557
|
+
*/async function QG(n,e,t,r){return(await Yl(e,Ma.COUNT_TOKENS,n,!1,JSON.stringify(t),r)).json()}/**
|
|
558
|
+
* @license
|
|
559
|
+
* Copyright 2024 Google LLC
|
|
560
|
+
*
|
|
561
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
562
|
+
* you may not use this file except in compliance with the License.
|
|
563
|
+
* You may obtain a copy of the License at
|
|
564
|
+
*
|
|
565
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
566
|
+
*
|
|
567
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
568
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
569
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
570
|
+
* See the License for the specific language governing permissions and
|
|
571
|
+
* limitations under the License.
|
|
572
|
+
*/async function eJ(n,e,t,r){return(await Yl(e,Ma.EMBED_CONTENT,n,!1,JSON.stringify(t),r)).json()}async function tJ(n,e,t,r){const s=t.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await Yl(e,Ma.BATCH_EMBED_CONTENTS,n,!1,JSON.stringify({requests:s}),r)).json()}/**
|
|
573
|
+
* @license
|
|
574
|
+
* Copyright 2024 Google LLC
|
|
575
|
+
*
|
|
576
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
577
|
+
* you may not use this file except in compliance with the License.
|
|
578
|
+
* You may obtain a copy of the License at
|
|
579
|
+
*
|
|
580
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
581
|
+
*
|
|
582
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
583
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
584
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
585
|
+
* See the License for the specific language governing permissions and
|
|
586
|
+
* limitations under the License.
|
|
587
|
+
*/class jA{constructor(e,t,r={}){this.apiKey=e,this._requestOptions=r,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=tR(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){var r;const s=RA(e),i=Object.assign(Object.assign({},this._requestOptions),t);return eR(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,t={}){var r;const s=RA(e),i=Object.assign(Object.assign({},this._requestOptions),t);return Q$(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 t;return new XG(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},e),this._requestOptions)}async countTokens(e,t={}){const r=qG(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),t);return QG(this.apiKey,this.model,r,s)}async embedContent(e,t={}){const r=GG(e),s=Object.assign(Object.assign({},this._requestOptions),t);return eJ(this.apiKey,this.model,r,s)}async batchEmbedContents(e,t={}){const r=Object.assign(Object.assign({},this._requestOptions),t);return tJ(this.apiKey,this.model,e,r)}}/**
|
|
588
|
+
* @license
|
|
589
|
+
* Copyright 2024 Google LLC
|
|
590
|
+
*
|
|
591
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
592
|
+
* you may not use this file except in compliance with the License.
|
|
593
|
+
* You may obtain a copy of the License at
|
|
594
|
+
*
|
|
595
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
596
|
+
*
|
|
597
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
598
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
599
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
600
|
+
* See the License for the specific language governing permissions and
|
|
601
|
+
* limitations under the License.
|
|
602
|
+
*/class LA{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new Sn("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new jA(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,r){if(!e.name)throw new $i("Cached content must contain a `name` field.");if(!e.model)throw new $i("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t!=null&&t[a]&&e[a]&&(t==null?void 0:t[a])!==e[a]){if(a==="model"){const o=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(o===c)continue}throw new $i(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${e[a]})`)}const i=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new jA(this.apiKey,i,r)}}function DA(n,e){const t=nJ(n);return{tools:t,toolConfig:sJ(t,e)}}function nJ(n){let e=[];const t=[];return n.forEach(r=>{if(Ys(r)){const[s]=EG([r]);s.functionDeclarations&&e.push(...s.functionDeclarations)}else if(Sc(r)){const{functionDeclarations:s}=rJ(r);if(s)e.push(...s);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(r)}),t.find(r=>"functionDeclarations"in r)?t.map(r=>{if((e==null?void 0:e.length)>0&&"functionDeclarations"in r){const s={functionDeclarations:[...r.functionDeclarations||[],...e]};return e=[],s}return r}):[...t,...e.length>0?[{functionDeclarations:e}]:[]]}function rJ(n){return{functionDeclarations:[{name:n.function.name,description:n.function.description,parameters:Na(n.function.parameters)}]}}function sJ(n,e){if(!n.length||!e)return;const{toolChoice:t,allowedFunctionNames:r}=e,s={any:ko.ANY,auto:ko.AUTO,none:ko.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:r}};if(typeof t=="string"||r)return{functionCallingConfig:{mode:ko.ANY,allowedFunctionNames:[...r??[],...t&&typeof t=="string"?[t]:[]]}}}const iJ={"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 aJ=class extends Is{constructor(e,t){const r=typeof e=="string"?{...t??{},model:e}:e;super(r);p(this,"lc_serializable",!0);p(this,"lc_namespace",["langchain","chat_models","google_genai"]);p(this,"model");p(this,"temperature");p(this,"maxOutputTokens");p(this,"topP");p(this,"topK");p(this,"stopSequences",[]);p(this,"safetySettings");p(this,"apiKey");p(this,"streaming",!1);p(this,"json");p(this,"streamUsage",!0);p(this,"convertSystemMessageToHumanContent");p(this,"thinkingConfig");p(this,"client");if(this._addVersion("@langchain/google-genai","2.1.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??Bt("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 LA(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,t,r){this.apiKey&&(this.client=new LA(this.apiKey).getGenerativeModelFromCachedContent(e,t,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,t){var r;return this.withConfig({tools:(r=DA(e))==null?void 0:r.tools,...t})}invocationParams(e){var r;const t=(r=e==null?void 0:e.tools)!=null&&r.length?DA(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),{...t!=null&&t.tools?{tools:t.tools}:{},...t!=null&&t.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,r){var l,d,f,h;(l=t.signal)==null||l.throwIfAborted();const s=yA(e,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[m]=s;this.client.systemInstruction=m,i=s.slice(1)}const a=this.invocationParams(t);if(this.streaming){const m={},g=this._streamResponseChunks(e,t,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:m}}}const o=await this.completionWithRetry({...a,contents:i});let c;"usageMetadata"in o.response&&(c=wA(o.response.usageMetadata,this.model));const u=AG(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,t,r){var f;const s=yA(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(t),contents:i},o=await this.caller.callWithOptions({signal:t==null?void 0:t.signal},async()=>{const{stream:h}=await this.client.generateContentStream(a,{signal:t==null?void 0:t.signal});return h});let c,u=0,l=0,d=0;for await(const h of o){if((f=t.signal)!=null&&f.aborted)return;if("usageMetadata"in h&&h.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){c=wA(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 m=TG(h,{usageMetadata:c});m&&(yield m,await(r==null?void 0:r.handleLLMNewToken(m.text??"")))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t==null?void 0:t.signal},async()=>{var r;try{return await this.client.generateContent(e,{signal:t==null?void 0:t.signal})}catch(s){throw(r=s.message)!=null&&r.includes("400 Bad Request")&&(s.status=400),s}})}get profile(){return iJ[this.model]??{}}withStructuredOutput(e,t){const r=e,s=t==null?void 0:t.name,i=t==null?void 0:t.method,a=t==null?void 0:t.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(Xt(r)||Or(r)){const f=ry(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=Na(r.parameters),u=r.name):l={name:u,description:r.description??"",parameters:Na(r)};const d=[{functionDeclarations:[l]}];o=this.bindTools(d).withConfig({allowedFunctionNames:[u]}),c=zl(r,u,kG)}else{const u=ry(r);o=this.withConfig({responseSchema:u}),c=uc(r)}return Ec(o,c,a,a?"StructuredOutputRunnable":"ChatGoogleGenerativeAIStructuredOutput")}},oJ=class extends Ac{constructor(e){super(e);p(this,"lc_namespace",["langchain","anthropic","output_parsers"]);p(this,"returnId",!1);p(this,"keyName");p(this,"returnSingle",!1);p(this,"zodSchema");p(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){throw new Tn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(s.message)}`,e)}else t=e;if(this.serializableSchema!==void 0){const s=await this.serializableSchema["~standard"].validate(t);if(s.issues)throw new Tn(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.issues)}`,JSON.stringify(t,null,2));return s.value}if(this.zodSchema===void 0)return t;const r=await tp(this.zodSchema,t);if(r.success)return r.data;throw new Tn(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){const t=e.flatMap(s=>{const{message:i}=s;return Array.isArray(i.content)?nR(i.content)[0]:[]});if(t[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[r]=t;return await this._validateResult(r.args)}};function nR(n){const e=[];for(const t of n)t.type==="tool_use"&&e.push({name:t.name,args:t.input,id:t.id,type:"tool_call"});return e}function cJ(n){if(n)return n==="any"||n==="required"?{type:"any"}:n==="auto"?{type:"auto"}:n==="none"?{type:"none"}:typeof n=="string"?{type:"tool",name:n}:n}const uJ=Me({cache_control:y_().optional().nullable(),defer_loading:q9().optional(),input_examples:Ca(cf()).optional(),allowed_callers:Ca(cf()).optional()}),UA={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 lJ(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="thinking"}function dJ(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="redacted_thinking"}function rR(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="compaction"}function hJ(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="search_result"}function fJ(n){return typeof n!="object"||n==null||!("type"in n)||n.type!=="image"||!("source"in n)||typeof n.source!="object"||n.source==null||!("type"in n.source)?!1:n.source.type==="base64"?!(!("media_type"in n.source)||typeof n.source.media_type!="string"||!("data"in n.source)||typeof n.source.data!="string"):n.source.type==="url"?!(!("url"in n.source)||typeof n.source.url!="string"):!1}const pJ={providerName:"anthropic",fromStandardTextBlock(n){return{type:"text",text:n.text,..."citations"in(n.metadata??{})?{citations:n.metadata.citations}:{},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{}}},fromStandardImageBlock(n){if(n.source_type==="url"){const e=Gr({dataUrl:n.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:n.url},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{}}}else{if(n.source_type==="base64")return{type:"image",source:{type:"base64",data:n.data,media_type:n.mime_type??""},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${n.source_type}`)}},fromStandardFileBlock(n){const e=(n.mime_type??"").split(";")[0];if(n.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:n.url},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{},..."citations"in(n.metadata??{})?{citations:n.metadata.citations}:{},..."context"in(n.metadata??{})?{context:n.metadata.context}:{},..."title"in(n.metadata??{})?{title:n.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${n.mime_type}`)}else if(n.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:n.text,media_type:n.mime_type??""},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{},..."citations"in(n.metadata??{})?{citations:n.metadata.citations}:{},..."context"in(n.metadata??{})?{context:n.metadata.context}:{},..."title"in(n.metadata??{})?{title:n.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${n.mime_type}`)}else if(n.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:n.data,media_type:"application/pdf"},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{},..."citations"in(n.metadata??{})?{citations:n.metadata.citations}:{},..."context"in(n.metadata??{})?{context:n.metadata.context}:{},..."title"in(n.metadata??{})?{title:n.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:n.data,media_type:e}}]},..."cache_control"in(n.metadata??{})?{cache_control:n.metadata.cache_control}:{},..."citations"in(n.metadata??{})?{citations:n.metadata.citations}:{},..."context"in(n.metadata??{})?{context:n.metadata.context}:{},..."title"in(n.metadata??{})?{title:n.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${n.mime_type}`)}else throw new Error(`Unsupported file source type: ${n.source_type}`)}},mJ=n=>n();function gJ(n){return typeof n=="object"&&n!==null&&"type"in n&&n.type==="citation"}function _J(n){function*e(){for(const t of n)gJ(t)&&(t.source==="char"?yield{type:"char_location",file_id:t.url??"",start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??""}:t.source==="page"?yield{type:"page_location",file_id:t.url??"",start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??""}:t.source==="block"?yield{type:"content_block_location",file_id:t.url??"",start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??""}:t.source==="url"?yield{type:"web_search_result_location",url:t.url??"",title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??""}:t.source==="search"&&(yield{type:"search_result_location",title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??"",cited_text:t.citedText??""}))}return Array.from(e())}function Dc(n){return typeof n=="string"?n:yJ(n)}function yJ(n){const e=[];for(let t=0,{length:r}=n;t<r;t++)e.push(String.fromCharCode(n[t]));return btoa(e.join(""))}function qm(n){return(n??"").split(";")[0].toLowerCase()}function vu(n,e){if(n!=null&&typeof n=="object"&&e in n)return n[e]}function Qa(n,e){const t=vu(e,"cache_control");t!==void 0&&(n.cache_control=t);const r=vu(e,"citations");r!==void 0&&(n.citations=r);const s=vu(e,"context");s!==void 0&&(n.context=s);const i=vu(e,"title");return i!==void 0&&(n.title=i),n}function Gm(n,e){const t=vu(e,"cache_control");return t!==void 0&&(n.cache_control=t),n}function zA(n){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(n)}function wJ(n){const e=[],t=n.response_metadata,r="model_provider"in t&&(t==null?void 0:t.model_provider)==="anthropic";for(const s of n.contentBlocks)if(s.type==="text")s.annotations?e.push({type:"text",text:s.text,citations:_J(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=mJ(()=>{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(Qa({type:"document",source:{type:"file",file_id:s.fileId}},i));continue}if(s.url){const a=qm(s.mimeType);if(a==="application/pdf"||a===""){e.push(Qa({type:"document",source:{type:"url",url:s.url}},i));continue}}if(s.data){const a=qm(s.mimeType);if(a===""||a==="application/pdf")e.push(Qa({type:"document",source:{type:"base64",data:Dc(s.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(Qa({type:"document",source:{type:"text",data:Dc(s.data),media_type:"text/plain"}},i));else if(zA(a))e.push(Qa({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:Dc(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(Gm({type:"image",source:{type:"file",file_id:s.fileId}},i));continue}if(s.url){e.push(Gm({type:"image",source:{type:"url",url:s.url}},i));continue}if(s.data){const a=qm(s.mimeType)||"image/png";zA(a)&&e.push(Gm({type:"image",source:{type:"base64",data:Dc(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(Qa({type:"document",source:{type:"text",data:Dc(s.data),media_type:"text/plain"}},s.metadata)):s.type==="non_standard"&&r&&e.push(s.value))}return e}function Jm(n){const e=Gr({dataUrl:n});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let t;try{t=new URL(n)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(n)}. 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(`
|
|
603
|
+
|
|
604
|
+
`))}if(t.protocol==="http:"||t.protocol==="https:")return{type:"url",url:n};throw new Error([`Invalid image URL protocol: ${JSON.stringify(t.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(`
|
|
605
|
+
|
|
606
|
+
`))}function bJ(n){const e=[];for(const t of n)if(t._getType()==="tool")if(typeof t.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:t.content,tool_use_id:t.tool_call_id}):e.push(new Dn({content:[{type:"tool_result",content:t.content,tool_use_id:t.tool_call_id}]}))}else e.push(new Dn({content:[{type:"tool_result",...t.content!=null?{content:sy(t)}:{},tool_use_id:t.tool_call_id}]}));else e.push(t);return e}function Ym(n){if(n.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:n.id,name:n.name,input:n.args}}function*vJ(n,e){const t=["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 n){Ir(s)&&(yield xl(s,pJ));const i="cache_control"in s?s.cache_control:void 0;if(s.type==="image_url"){let a;typeof s.image_url=="string"?a=Jm(s.image_url):typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(a=Jm(s.image_url.url)),a&&(yield{type:"image",source:a,...i?{cache_control:i}:{}})}else if(fJ(s))yield s;else if(s.type==="image"){let a;"url"in s&&typeof s.url=="string"?a=Jm(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(lJ(s))yield{type:"thinking",thinking:s.thinking,signature:s.signature,...i?{cache_control:i}:{}};else if(dJ(s))yield{type:"redacted_thinking",data:s.data,...i?{cache_control:i}:{}};else if(rR(s))yield{type:"compaction",content:s.content,...i?{cache_control:i}:{}};else if(hJ(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(t.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=n.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 sy(n,e){const{content:t}=n;return typeof t=="string"?t:Array.from(vJ(t,e))}function FA(n){const e=bJ(n);let t;return e.length>0&&e[0]._getType()==="system"&&(t=n[0].content),{messages:SJ((t!==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(Ve.isInstance(r)&&((i=r.response_metadata)==null?void 0:i.output_version)==="v1")return{role:s,content:wJ(r)};if(Ve.isInstance(r)&&((a=r.tool_calls)!=null&&a.length)){if(typeof r.content=="string")return r.content===""?{role:s,content:r.tool_calls.map(Ym)}:{role:s,content:[{type:"text",text:r.content},...r.tool_calls.map(Ym)]};{const{content:o}=r,c=sy(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(Ym)]}}}else return{role:s,content:sy(r,Ve.isInstance(r)?r.tool_calls:void 0)}})),system:t}}function BA(n,e){if(!n.messages||n.messages.length===0)return n;const t=[...n.messages],r=t.length-1,s=t[r];if(!s)return n;if(typeof s.content=="string")return t[r]={...s,content:[{type:"text",text:s.content,cache_control:e}]},{...n,messages:t};if(Array.isArray(s.content)&&s.content.length>0){const i=[...s.content],a=i.length-1;return i[a]={...i[a],cache_control:e},t[r]={...s,content:i},{...n,messages:t}}return n}function SJ(n){if(!n||n.length<=1)return n;const e=[];let t=n[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<n.length;i+=1){const a=n[i];s(t)&&s(a)?t={...t,content:[...r(t.content),...r(a.content)]}:(e.push(t),t=a)}return e.push(t),e}function sR(n){return n.type==="enabled"||n.type==="adaptive"}function $b(n){return(n==null?void 0:n.startsWith("claude-opus-4-7"))??!1}function AJ(n,e){const t=e&&typeof e=="object"&&"task_budget"in e&&e.task_budget!=null;return $b(n)&&t?["task-budgets-2026-03-13"]:[]}function TJ(n){const{model:e,thinking:t,topK:r,topP:s,temperature:i}=n,a=$b(e);if(a&&t.type==="enabled")throw new Error('thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead');if(a&&typeof t=="object"&&t!=null&&"budget_tokens"in t)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(sR(t)){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 EJ(n){const{model:e,thinking:t,topK:r,topP:s,temperature:i}=n,a={};return sR(t)||$b(e)||(i!==void 0&&(a.temperature=i),r!==void 0&&(a.top_k=r),s!==void 0&&(a.top_p=s)),a}function kJ(n,e){var r;const t={model_provider:"anthropic"};if(n.type==="message_start"){const{content:s,usage:i,...a}=n.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=iR(i);return{chunk:new nt({content:e.coerceContentToString?"":[],additional_kwargs:o,usage_metadata:e.streamUsage?d:void 0,response_metadata:{...t,usage:{...l}},id:n.message.id})}}else if(n.type==="message_delta"){const s={input_tokens:0,output_tokens:n.usage.output_tokens,total_tokens:n.usage.output_tokens},i="context_management"in n.delta?{context_management:n.delta.context_management}:void 0;return{chunk:new nt({content:e.coerceContentToString?"":[],response_metadata:i,additional_kwargs:{...n.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(n.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(n.content_block.type)){const s=n.content_block;let i;return s.type==="tool_use"?i=[{id:s.id,index:n.index,name:s.name,args:""}]:i=[],{chunk:new nt({content:e.coerceContentToString?"":[{index:n.index,...n.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:t,additional_kwargs:{},tool_call_chunks:i})}}else if(n.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(n.delta.type)){if(e.coerceContentToString&&"text"in n.delta)return{chunk:new nt({content:n.delta.text})};{const s=n.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new nt({content:[{index:n.index,...s,type:"thinking"}],response_metadata:t})}:{chunk:new nt({content:[{index:n.index,...s,type:"text"}],response_metadata:t})}}}else{if(n.type==="content_block_delta"&&n.delta.type==="input_json_delta")return{chunk:new nt({content:e.coerceContentToString?"":[{index:n.index,input:n.delta.partial_json,type:n.delta.type}],response_metadata:t,additional_kwargs:{},tool_call_chunks:[{index:n.index,args:n.delta.partial_json}]})};if(n.type==="content_block_start"&&n.content_block.type==="text"){const s=(r=n.content_block)==null?void 0:r.text;if(s!==void 0)return{chunk:new nt({content:e.coerceContentToString?s:[{index:n.index,...n.content_block}],response_metadata:t,additional_kwargs:{}})}}else{if(n.type==="content_block_start"&&n.content_block.type==="redacted_thinking")return{chunk:new nt({content:e.coerceContentToString?"":[{index:n.index,...n.content_block}],response_metadata:t})};if(n.type==="content_block_start"&&n.content_block.type==="thinking"){const s=n.content_block.thinking;return{chunk:new nt({content:e.coerceContentToString?s:[{index:n.index,...n.content_block}],response_metadata:t})}}else{if(n.type==="content_block_start"&&rR(n.content_block))return{chunk:new nt({content:e.coerceContentToString?"":[{index:n.index,...n.content_block}],response_metadata:t})};if(n.type==="content_block_delta"&&n.delta.type==="compaction_delta")return{chunk:new nt({content:e.coerceContentToString?"":[{index:n.index,...n.delta,type:"compaction"}],response_metadata:t})}}}}return null}function IJ(n,e){const t={...e,model_provider:"anthropic"},r=e.usage,s=r!=null?iR(r):void 0;return n.length===1&&n[0].type==="text"?[{text:n[0].text,message:new Ve({content:n[0].text,additional_kwargs:e,usage_metadata:s,response_metadata:t,id:e.id})}]:[{text:"",message:new Ve({content:n,additional_kwargs:e,tool_calls:nR(n),usage_metadata:s,response_metadata:t,id:e.id})}]}function iR(n){const e=n.cache_creation_input_tokens??0,t=n.cache_read_input_tokens??0,r=n.input_tokens+e+t;return{input_tokens:r,output_tokens:n.output_tokens,total_tokens:r+n.output_tokens,input_token_details:{cache_creation:e,cache_read:t}}}function Uc(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
607
|
+
|
|
608
|
+
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
609
|
+
`,n}function HA(n){let e;return n.status===400&&typeof n.message=="string"&&n.message.includes("prompt is too long")?e=Uc(wy.fromError(n),"CONTEXT_OVERFLOW"):n.status===400&&n.message.includes("tool")?e=Uc(n,"INVALID_TOOL_RESULTS"):n.status===401?e=Uc(n,"MODEL_AUTHENTICATION"):n.status===404?e=Uc(n,"MODEL_NOT_FOUND"):n.status===429?e=Uc(n,"MODEL_RATE_LIMIT"):e=n,e}const xJ={"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20240620":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};function ce(n,e,t,r,s){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function P(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let aR=function(){const{crypto:n}=globalThis;if(n!=null&&n.randomUUID)return aR=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function fl(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const iy=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class Ne extends Error{}class In extends Ne{constructor(e,t,r,s,i){super(`${In.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("request-id"),this.error=t,this.type=i??null}static makeMessage(e,t,r){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){var o;if(!e||!s)return new Np({message:r,cause:iy(t)});const i=t,a=(o=i==null?void 0:i.error)==null?void 0:o.type;return e===400?new cR(e,i,r,s,a):e===401?new uR(e,i,r,s,a):e===403?new lR(e,i,r,s,a):e===404?new dR(e,i,r,s,a):e===409?new hR(e,i,r,s,a):e===422?new fR(e,i,r,s,a):e===429?new pR(e,i,r,s,a):e>=500?new mR(e,i,r,s,a):new In(e,i,r,s,a)}}class qr extends In{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Np extends In{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class oR extends Np{constructor({message:e}={}){super({message:e??"Request timed out."})}}class cR extends In{}class uR extends In{}class lR extends In{}class dR extends In{}class hR extends In{}class fR extends In{}class pR extends In{}class mR extends In{}const OJ=/^[a-z][a-z0-9+.-]*:/i,CJ=n=>OJ.test(n);let ay=n=>(ay=Array.isArray,ay(n)),VA=ay;function oy(n){return typeof n!="object"?{}:n??{}}function ZA(n){if(!n)return!0;for(const e in n)return!1;return!0}function $J(n,e){return Object.prototype.hasOwnProperty.call(n,e)}const RJ=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ne(`${n} must be an integer`);if(e<0)throw new Ne(`${n} must be a positive integer`);return e},gR=n=>{try{return JSON.parse(n)}catch{return}},PJ=n=>new Promise(e=>setTimeout(e,n)),fo="0.90.0",NJ=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function MJ(){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 jJ=()=>{var t;const n=MJ();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":WA(Deno.build.os),"X-Stainless-Arch":KA(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((t=Deno.version)==null?void 0:t.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"X-Stainless-OS":WA(globalThis.process.platform??"unknown"),"X-Stainless-Arch":KA(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=LJ();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fo,"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":fo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function LJ(){if(typeof navigator>"u"||!navigator)return null;const n=[{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:t}of n){const r=t.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 KA=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",WA=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let qA;const DJ=()=>qA??(qA=jJ());function UJ(){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 _R(...n){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(...n)}function yR(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return _R({start(){},async pull(t){const{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function Rb(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function zJ(n){var r,s;if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await((s=(r=n[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const FJ=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function BJ(n){return Object.entries(n).filter(([e,t])=>typeof t<"u").map(([e,t])=>{if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new Ne(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function HJ(n){let e=0;for(const s of n)e+=s.length;const t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}let GA;function Pb(n){let e;return(GA??(e=new globalThis.TextEncoder,GA=e.encode.bind(e)))(n)}let JA;function YA(n){let e;return(JA??(e=new globalThis.TextDecoder,JA=e.decode.bind(e)))(n)}var tr,nr;class Xl{constructor(){tr.set(this,void 0),nr.set(this,void 0),ce(this,tr,new Uint8Array),ce(this,nr,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Pb(e):e;ce(this,tr,HJ([P(this,tr,"f"),t]));const r=[];let s;for(;(s=VJ(P(this,tr,"f"),P(this,nr,"f")))!=null;){if(s.carriage&&P(this,nr,"f")==null){ce(this,nr,s.index);continue}if(P(this,nr,"f")!=null&&(s.index!==P(this,nr,"f")+1||s.carriage)){r.push(YA(P(this,tr,"f").subarray(0,P(this,nr,"f")-1))),ce(this,tr,P(this,tr,"f").subarray(P(this,nr,"f"))),ce(this,nr,null);continue}const i=P(this,nr,"f")!==null?s.preceding-1:s.preceding,a=YA(P(this,tr,"f").subarray(0,i));r.push(a),ce(this,tr,P(this,tr,"f").subarray(s.index)),ce(this,nr,null)}return r}flush(){return P(this,tr,"f").length?this.decode(`
|
|
610
|
+
`):[]}}tr=new WeakMap,nr=new WeakMap;Xl.NEWLINE_CHARS=new Set([`
|
|
611
|
+
`,"\r"]);Xl.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function VJ(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function ZJ(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const xf={off:0,error:200,warn:300,info:400,debug:500},XA=(n,e,t)=>{if(n){if($J(xf,n))return n;Nn(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(xf))}`)}};function Su(){}function Md(n,e,t){return!e||xf[n]>xf[t]?Su:e[n].bind(e)}const KJ={error:Su,warn:Su,info:Su,debug:Su};let QA=new WeakMap;function Nn(n){const e=n.logger,t=n.logLevel??"off";if(!e)return KJ;const r=QA.get(e);if(r&&r[0]===t)return r[1];const s={error:Md("error",e,t),warn:Md("warn",e,t),info:Md("info",e,t),debug:Md("debug",e,t)};return QA.set(e,[t,s]),s}const ra=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var zc;class _s{constructor(e,t,r){this.iterator=e,zc.set(this,void 0),this.controller=t,ce(this,zc,r)}static fromSSEResponse(e,t,r){let s=!1;const i=r?Nn(r):console;async function*a(){var c;if(s)throw new Ne("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of WJ(e,t)){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")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=gR(u.data)??u.data,d=(c=l==null?void 0:l.error)==null?void 0:c.type;throw new In(void 0,l,void 0,e.headers,d)}}o=!0}catch(u){if(fl(u))return;throw u}finally{o||t.abort()}}return new _s(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*i(){const o=new Xl,c=Rb(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 Ne("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(fl(c))return;throw c}finally{o||t.abort()}}return new _s(a,t,r)}[(zc=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){const a=r.next();e.push(a),t.push(a)}return i.shift()}});return[new _s(()=>s(e),this.controller,P(this,zc,"f")),new _s(()=>s(t),this.controller,P(this,zc,"f"))]}toReadableStream(){const e=this;let t;return _R({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:i}=await t.next();if(i)return r.close();const a=Pb(JSON.stringify(s)+`
|
|
612
|
+
`);r.enqueue(a)}catch(s){r.error(s)}},async cancel(){var r;await((r=t.return)==null?void 0:r.call(t))}})}}async function*WJ(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ne("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 Ne("Attempted to iterate over a response with no body");const t=new GJ,r=new Xl,s=Rb(n.body);for await(const i of qJ(s))for(const a of r.decode(i)){const o=t.decode(a);o&&(yield o)}for(const i of r.flush()){const a=t.decode(i);a&&(yield a)}}async function*qJ(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Pb(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let i;for(;(i=ZJ(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class GJ{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(`
|
|
613
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=JJ(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function JJ(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function wR(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:i}=e,a=await(async()=>{var d;if(e.options.stream)return Nn(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):_s.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const o=t.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(t.headers.get("content-length")==="0")return;const h=await t.json();return bR(h,t)}return await t.text()})();return Nn(n).debug(`[${r}] response parsed`,ra({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function bR(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Au;class Mp extends Promise{constructor(e,t,r=wR){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Au.set(this,void 0),ce(this,Au,e)}_thenUnwrap(e){return new Mp(P(this,Au,"f"),this.responsePromise,async(t,r)=>bR(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(P(this,Au,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Au=new WeakMap;var jd;class vR{constructor(e,t,r,s){jd.set(this,void 0),ce(this,jd,e),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Ne("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await P(this,jd,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(jd=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class YJ extends Mp{constructor(e,t,r){super(e,t,async(s,i)=>new r(s,i.response,await wR(s,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class Ql extends vR{constructor(e,t,r,s){super(e,t,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 t;if((t=this.options.query)!=null&&t.before_id){const r=this.first_id;return r?{...this.options,query:{...oy(this.options.query),before_id:r}}:null}const e=this.last_id;return e?{...this.options,query:{...oy(this.options.query),after_id:e}}:null}}class es extends vR{constructor(e,t,r,s){super(e,t,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:{...oy(this.options.query),page:e}}:null}}const SR=()=>{var n;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((n=e==null?void 0:e.versions)==null?void 0:n.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Po(n,e,t){return SR(),new File(n,e??"unknown_file",t)}function xh(n,e){const t=typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"";return e?t.split(/[\\/]/).pop()||void 0:t}const AR=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Nb=async(n,e,t=!0)=>({...n,body:await QJ(n.body,e,t)}),eT=new WeakMap;function XJ(n){const e=typeof n=="function"?n:n.fetch,t=eT.get(e);if(t)return t;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 eT.set(e,r),r}const QJ=async(n,e,t=!0)=>{if(!await XJ(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(n||{}).map(([s,i])=>cy(r,s,i,t))),r},e7=n=>n instanceof Blob&&"name"in n,cy=async(n,e,t,r)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response){let s={};const i=t.headers.get("Content-Type");i&&(s={type:i}),n.append(e,Po([await t.blob()],xh(t,r),s))}else if(AR(t))n.append(e,Po([await new Response(yR(t)).blob()],xh(t,r)));else if(e7(t))n.append(e,Po([t],xh(t,r),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(s=>cy(n,e+"[]",s,r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,i])=>cy(n,`${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 ${t} instead`)}},TR=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",t7=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&TR(n),n7=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function r7(n,e,t){if(SR(),n=await n,e||(e=xh(n,!0)),t7(n))return n instanceof File&&e==null&&t==null?n:Po([await n.arrayBuffer()],e??n.name,{type:n.type,lastModified:n.lastModified,...t});if(n7(n)){const s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),Po(await uy(s),e,t)}const r=await uy(n);if(!(t!=null&&t.type)){const s=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(t={...t,type:s})}return Po(r,e,t)}async function uy(n){var t;let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(TR(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(AR(n))for await(const r of n)e.push(...await uy(r));else{const r=(t=n==null?void 0:n.constructor)==null?void 0:t.name;throw new Error(`Unexpected data type: ${typeof n}${r?`; constructor: ${r}`:""}${s7(n)}`)}return e}function s7(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class Vt{constructor(e){this._client=e}}const ER=Symbol.for("brand.privateNullableHeaders");function*i7(n){if(!n)return;if(ER in n){const{values:r,nulls:s}=n;yield*r.entries();for(const i of s)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():VA(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=VA(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 te=n=>{const e=new Headers,t=new Set;for(const r of n){const s=new Set;for(const[i,a]of i7(r)){const o=i.toLowerCase();s.has(o)||(e.delete(i),s.add(o)),a===null?(e.delete(i),t.add(o)):(e.append(i,a),t.delete(o))}}return{[ER]:!0,values:e,nulls:t}};function kR(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const tT=Object.freeze(Object.create(null)),a7=(n=kR)=>function(t,...r){if(t.length===1)return t[0];let s=!1;const i=[],a=t.reduce((l,d,f)=>{var g;/[?#]/.test(d)&&(s=!0);const h=r[f];let m=(s?encodeURIComponent:n)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??tT)??tT))==null?void 0:g.toString))&&(m=h+"",i.push({start:l.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),l+d+(f===r.length?"":m)},""),o=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 m=" ".repeat(h.start-l),g="^".repeat(h.length);return l=h.start+h.length,f+m+g},"");throw new Ne(`Path parameters result in path with invalid segments:
|
|
614
|
+
${i.map(f=>f.error).join(`
|
|
615
|
+
`)}
|
|
616
|
+
${a}
|
|
617
|
+
${d}`)}return a},$e=a7(kR);class IR extends Vt{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/environments/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/environments/${e}?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",es,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete($e`/v1/environments/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post($e`/v1/environments/${e}/archive?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}const zu=Symbol("anthropic.sdk.stainlessHelper");function Oh(n){return typeof n=="object"&&n!==null&&zu in n}function xR(n,e){const t=new Set;if(n)for(const r of n)Oh(r)&&t.add(r[zu]);if(e){for(const r of e)if(Oh(r)&&t.add(r[zu]),Array.isArray(r.content))for(const s of r.content)Oh(s)&&t.add(s[zu])}return Array.from(t)}function OR(n,e){const t=xR(n,e);return t.length===0?{}:{"x-stainless-helper":t.join(", ")}}function o7(n){return Oh(n)?{"x-stainless-helper":n[zu]}:{}}class CR extends Vt{list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files",Ql,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete($e`/v1/files/${e}`,{...r,headers:te([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}download(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/files/${e}/content`,{...r,headers:te([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/files/${e}`,{...r,headers:te([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}upload(e,t){const{betas:r,...s}=e;return this._client.post("/v1/files",Nb({body:s,...t,headers:te([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},o7(s.file),t==null?void 0:t.headers])},this._client))}}let $R=class extends Vt{retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/models/${e}?beta=true`,{...r,headers:te([{...(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={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",Ql,{query:s,...t,headers:te([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers])})}};class RR extends Vt{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:te([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/user_profiles/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/user_profiles/${e}?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",es,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t==null?void 0:t.headers])})}createEnrollmentURL(e,t={},r){const{betas:s}=t??{};return this._client.post($e`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r==null?void 0:r.headers])})}}let PR=class extends Vt{list(e,t={},r){const{betas:s,...i}=t??{};return this._client.getAPIList($e`/v1/agents/${e}/versions?beta=true`,es,{query:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}};class Mb extends Vt{constructor(){super(...arguments),this.versions=new PR(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){const{betas:s,...i}=t??{};return this._client.get($e`/v1/agents/${e}?beta=true`,{query:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/agents/${e}?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",es,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post($e`/v1/agents/${e}/archive?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}Mb.Versions=PR;const NR={"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 MR(n){var e;return(n==null?void 0:n.output_format)??((e=n==null?void 0:n.output_config)==null?void 0:e.format)}function nT(n,e,t){const r=MR(e);return!e||!("parse"in(r??{}))?{...n,content:n.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 t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return s}),parsed_output:null}:jR(n,e,t)}function jR(n,e,t){let r=null;const s=n.content.map(i=>{if(i.type==="text"){const a=c7(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 t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return i});return{...n,content:s,parsed_output:r}}function c7(n,e){const t=MR(n);if((t==null?void 0:t.type)!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(r){throw new Ne(`Failed to parse structured output: ${r}`)}}const u7=n=>{let e=0,t=[];for(;e<n.length;){let r=n[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let o="",c=!1;for(r=n[++e];r!=='"';){if(e===n.length){c=!0;break}if(r==="\\"){if(e++,e===n.length){c=!0;break}o+=r+n[e],r=n[++e]}else o+=r,r=n[++e]}r=n[++e],c||t.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=n[++e]);r&&i.test(r)||r===".";)o+=r,r=n[++e];t.push({type:"number",value:o});continue}let a=/[a-z]/i;if(r&&a.test(r)){let o="";for(;r&&a.test(r)&&e!==n.length;)o+=r,r=n[++e];if(o=="true"||o=="false"||o==="null")t.push({type:"name",value:o});else{e++;continue}continue}e++}return t},po=n=>{if(n.length===0)return n;let e=n[n.length-1];switch(e.type){case"separator":return n=n.slice(0,n.length-1),po(n);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return n=n.slice(0,n.length-1),po(n);case"string":let r=n[n.length-2];if((r==null?void 0:r.type)==="delimiter")return n=n.slice(0,n.length-1),po(n);if((r==null?void 0:r.type)==="brace"&&r.value==="{")return n=n.slice(0,n.length-1),po(n);break;case"delimiter":return n=n.slice(0,n.length-1),po(n)}return n},l7=n=>{let e=[];return n.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?n.push({type:"brace",value:"}"}):t==="]"&&n.push({type:"paren",value:"]"})}),n},d7=n=>{let e="";return n.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},LR=n=>JSON.parse(d7(l7(po(u7(n)))));var br,ai,eo,Fc,Ld,Bc,Hc,Dd,Vc,$s,Zc,Ud,zd,qi,Fd,Bd,Kc,Xm,rT,Hd,Qm,eg,tg,sT;const iT="__json_buf";function aT(n){return n.type==="tool_use"||n.type==="server_tool_use"||n.type==="mcp_tool_use"}class Of{constructor(e,t){br.add(this),this.messages=[],this.receivedMessages=[],ai.set(this,void 0),eo.set(this,null),this.controller=new AbortController,Fc.set(this,void 0),Ld.set(this,()=>{}),Bc.set(this,()=>{}),Hc.set(this,void 0),Dd.set(this,()=>{}),Vc.set(this,()=>{}),$s.set(this,{}),Zc.set(this,!1),Ud.set(this,!1),zd.set(this,!1),qi.set(this,!1),Fd.set(this,void 0),Bd.set(this,void 0),Kc.set(this,void 0),Hd.set(this,r=>{if(ce(this,Ud,!0),fl(r)&&(r=new qr),r instanceof qr)return ce(this,zd,!0),this._emit("abort",r);if(r instanceof Ne)return this._emit("error",r);if(r instanceof Error){const s=new Ne(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new Ne(String(r)))}),ce(this,Fc,new Promise((r,s)=>{ce(this,Ld,r,"f"),ce(this,Bc,s,"f")})),ce(this,Hc,new Promise((r,s)=>{ce(this,Dd,r,"f"),ce(this,Vc,s,"f")})),P(this,Fc,"f").catch(()=>{}),P(this,Hc,"f").catch(()=>{}),ce(this,eo,e),ce(this,Kc,(t==null?void 0:t.logger)??console)}get response(){return P(this,Fd,"f")}get request_id(){return P(this,Bd,"f")}async withResponse(){ce(this,qi,!0);const e=await P(this,Fc,"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 t=new Of(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){const i=new Of(t,{logger:s});for(const a of t.messages)i._addMessageParam(a);return ce(i,eo,{...t,stream:!0}),i._run(()=>i._createMessage(e,{...t,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,Hd,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,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",Qm).call(this);const{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(const u of c)P(this,br,"m",eg).call(this,u);if((a=c.controller.signal)!=null&&a.aborted)throw new qr;P(this,br,"m",tg).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}_connected(e){this.ended||(ce(this,Fd,e),ce(this,Bd,e==null?void 0:e.headers.get("request-id")),P(this,Ld,"f").call(this,e),this._emit("connect"))}get ended(){return P(this,Zc,"f")}get errored(){return P(this,Ud,"f")}get aborted(){return P(this,zd,"f")}abort(){this.controller.abort()}on(e,t){return(P(this,$s,"f")[e]||(P(this,$s,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=P(this,$s,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(P(this,$s,"f")[e]||(P(this,$s,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{ce(this,qi,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){ce(this,qi,!0),await P(this,Hc,"f")}get currentMessage(){return P(this,ai,"f")}async finalMessage(){return await this.done(),P(this,br,"m",Xm).call(this)}async finalText(){return await this.done(),P(this,br,"m",rT).call(this)}_emit(e,...t){if(P(this,Zc,"f"))return;e==="end"&&(ce(this,Zc,!0),P(this,Dd,"f").call(this));const r=P(this,$s,"f")[e];if(r&&(P(this,$s,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!P(this,qi,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,Bc,"f").call(this,s),P(this,Vc,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!P(this,qi,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,Bc,"f").call(this,s),P(this,Vc,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",P(this,br,"m",Xm).call(this))}async _fromReadableStream(e,t){var i;const r=t==null?void 0:t.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",Qm).call(this),this._connected(null);const a=_s.fromReadableStream(e,this.controller);for await(const o of a)P(this,br,"m",eg).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new qr;P(this,br,"m",tg).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}[(ai=new WeakMap,eo=new WeakMap,Fc=new WeakMap,Ld=new WeakMap,Bc=new WeakMap,Hc=new WeakMap,Dd=new WeakMap,Vc=new WeakMap,$s=new WeakMap,Zc=new WeakMap,Ud=new WeakMap,zd=new WeakMap,qi=new WeakMap,Fd=new WeakMap,Bd=new WeakMap,Kc=new WeakMap,Hd=new WeakMap,br=new WeakSet,Xm=function(){if(this.receivedMessages.length===0)throw new Ne("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},rT=function(){if(this.receivedMessages.length===0)throw new Ne("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new Ne("stream ended without producing a content block with type=text");return t.join(" ")},Qm=function(){this.ended||ce(this,ai,void 0)},eg=function(t){if(this.ended)return;const r=P(this,br,"m",sT).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{const s=r.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{aT(s)&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.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:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(nT(r,P(this,eo,"f"),{logger:P(this,Kc,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{ce(this,ai,r);break}}},tg=function(){if(this.ended)throw new Ne("stream has ended, this shouldn't happen");const t=P(this,ai,"f");if(!t)throw new Ne("request ended without sending any chunks");return ce(this,ai,void 0),nT(t,P(this,eo,"f"),{logger:P(this,Kc,"f")})},sT=function(t){let r=P(this,ai,"f");if(t.type==="message_start"){if(r)throw new Ne(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new Ne(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.container=t.delta.container,r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r.context_management=t.context_management,t.usage.input_tokens!=null&&(r.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(r.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(r.usage.iterations=t.usage.iterations),r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{const s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(r.content[t.index]={...s,text:(s.text||"")+t.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]});break}case"input_json_delta":{if(s&&aT(s)){let i=s[iT]||"";i+=t.delta.partial_json;const a={...s};if(Object.defineProperty(a,iT,{value:i,enumerable:!1,writable:!0}),i)try{a.input=LR(i)}catch(o){const c=new Ne(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${o}. JSON: ${i}`);P(this,Hd,"f").call(this,c)}r.content[t.index]=a}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[t.index]={...s,signature:t.delta.signature});break}case"compaction_delta":{(s==null?void 0:s.type)==="compaction"&&(r.content[t.index]={...s,content:(s.content||"")+t.delta.content});break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>t.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 _s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class DR extends Error{constructor(e){const t=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}}const h7=1e5,f7=`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:
|
|
618
|
+
1. Task Overview
|
|
619
|
+
The user's core request and success criteria
|
|
620
|
+
Any clarifications or constraints they specified
|
|
621
|
+
2. Current State
|
|
622
|
+
What has been completed so far
|
|
623
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
624
|
+
Key outputs or artifacts produced
|
|
625
|
+
3. Important Discoveries
|
|
626
|
+
Technical constraints or requirements uncovered
|
|
627
|
+
Decisions made and their rationale
|
|
628
|
+
Errors encountered and how they were resolved
|
|
629
|
+
What approaches were tried that didn't work (and why)
|
|
630
|
+
4. Next Steps
|
|
631
|
+
Specific actions needed to complete the task
|
|
632
|
+
Any blockers or open questions to resolve
|
|
633
|
+
Priority order if multiple steps remain
|
|
634
|
+
5. Context to Preserve
|
|
635
|
+
User preferences or style requirements
|
|
636
|
+
Domain-specific details that aren't obvious
|
|
637
|
+
Any promises made to the user
|
|
638
|
+
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.
|
|
639
|
+
Wrap your summary in <summary></summary> tags.`;var Wc,to,Gi,qt,Fn,Xn,zs,oi,qc,oT,ly;function cT(){let n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}class UR{constructor(e,t,r){var a;Wc.add(this),this.client=e,to.set(this,!1),Gi.set(this,!1),qt.set(this,void 0),Fn.set(this,void 0),Xn.set(this,void 0),zs.set(this,void 0),oi.set(this,void 0),qc.set(this,0),ce(this,qt,{params:{...t,messages:structuredClone(t.messages)}});const i=["BetaToolRunner",...xR(t.tools,t.messages)].join(", ");ce(this,Fn,{...r,headers:te([{"x-stainless-helper":i},r==null?void 0:r.headers])}),ce(this,oi,cT()),(a=t.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*[(to=new WeakMap,Gi=new WeakMap,qt=new WeakMap,Fn=new WeakMap,Xn=new WeakMap,zs=new WeakMap,oi=new WeakMap,qc=new WeakMap,Wc=new WeakSet,oT=async function(){var u;const t=P(this,qt,"f").params.compactionControl;if(!t||!t.enabled)return!1;let r=0;if(P(this,Xn,"f")!==void 0)try{const l=await P(this,Xn,"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=t.contextTokenThreshold??h7;if(r<s)return!1;const i=t.model??P(this,qt,"f").params.model,a=t.summaryPrompt??f7,o=P(this,qt,"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,qt,"f").params.max_tokens},{signal:P(this,Fn,"f").signal,headers:te([P(this,Fn,"f").headers,{"x-stainless-helper":"compaction"}])});if(((u=c.content[0])==null?void 0:u.type)!=="text")throw new Ne("Expected text response for compaction");return P(this,qt,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(P(this,to,"f"))throw new Ne("Cannot iterate over a consumed stream");ce(this,to,!0),ce(this,Gi,!0),ce(this,zs,void 0);try{for(;;){let t;try{if(P(this,qt,"f").params.max_iterations&&P(this,qc,"f")>=P(this,qt,"f").params.max_iterations)break;ce(this,Gi,!1,"f"),ce(this,zs,void 0,"f"),ce(this,qc,(e=P(this,qc,"f"),e++,e),"f"),ce(this,Xn,void 0,"f");const{max_iterations:r,compactionControl:s,...i}=P(this,qt,"f").params;if(i.stream?(t=this.client.beta.messages.stream({...i},P(this,Fn,"f")),ce(this,Xn,t.finalMessage(),"f"),P(this,Xn,"f").catch(()=>{}),yield t):(ce(this,Xn,this.client.beta.messages.create({...i,stream:!1},P(this,Fn,"f")),"f"),yield P(this,Xn,"f")),!await P(this,Wc,"m",oT).call(this)){if(!P(this,Gi,"f")){const{role:c,content:u}=await P(this,Xn,"f");P(this,qt,"f").params.messages.push({role:c,content:u})}const o=await P(this,Wc,"m",ly).call(this,P(this,qt,"f").params.messages.at(-1));if(o)P(this,qt,"f").params.messages.push(o);else if(!P(this,Gi,"f"))break}}finally{t&&t.abort()}}if(!P(this,Xn,"f"))throw new Ne("ToolRunner concluded without a message from the server");P(this,oi,"f").resolve(await P(this,Xn,"f"))}catch(t){throw ce(this,to,!1),P(this,oi,"f").promise.catch(()=>{}),P(this,oi,"f").reject(t),ce(this,oi,cT()),t}}setMessagesParams(e){typeof e=="function"?P(this,qt,"f").params=e(P(this,qt,"f").params):P(this,qt,"f").params=e,ce(this,Gi,!0),ce(this,zs,void 0)}setRequestOptions(e){typeof e=="function"?ce(this,Fn,e(P(this,Fn,"f"))):ce(this,Fn,{...P(this,Fn,"f"),...e})}async generateToolResponse(e=P(this,Fn,"f").signal){const t=await P(this,Xn,"f")??this.params.messages.at(-1);return t?P(this,Wc,"m",ly).call(this,t,e):null}done(){return P(this,oi,"f").promise}async runUntilDone(){if(!P(this,to,"f"))for await(const e of this);return this.done()}get params(){return P(this,qt,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}ly=async function(e,t=P(this,Fn,"f").signal){return P(this,zs,"f")!==void 0?P(this,zs,"f"):(ce(this,zs,p7(P(this,qt,"f").params,e,{...P(this,Fn,"f"),signal:t})),P(this,zs,"f"))};async function p7(n,e=n.messages.at(-1),t){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=n.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:t==null?void 0:t.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 DR?o.content:`Error: ${o instanceof Error?o.message:String(o)}`,is_error:!0}}}))}}class jp{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Xl;for await(const t of this.iterator)for(const r of e.decode(t))yield JSON.parse(r);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ne("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 Ne("Attempted to iterate over a response with no body");return new jp(Rb(e.body),t)}}let zR=class extends Vt{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:te([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/messages/batches/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Ql,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete($e`/v1/messages/batches/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}cancel(e,t={},r){const{betas:s}=t??{};return this._client.post($e`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}async results(e,t={},r){const s=await this.retrieve(e);if(!s.results_url)throw new Ne(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);const{betas:i}=t??{};return this._client.get(s.results_url,{...r,headers:te([{"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)=>jp.fromResponse(o.response,o.controller))}};const uT={"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"},m7=["claude-mythos-preview","claude-opus-4-6"];let ed=class extends Vt{constructor(){super(...arguments),this.batches=new zR(this._client)}create(e,t){const r=lT(e),{betas:s,...i}=r;i.model in uT&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${uT[i.model]}
|
|
640
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),m7.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=NR[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,c)}const o=OR(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:a??6e5,...t,headers:te([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},o,t==null?void 0:t.headers]),stream:r.stream??!1})}parse(e,t){return t={...t,headers:te([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t==null?void 0:t.headers])},this.create(e,t).then(r=>jR(r,e,{logger:this._client.logger??console}))}stream(e,t){return Of.createMessage(this,e,t)}countTokens(e,t){const r=lT(e),{betas:s,...i}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:te([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},t==null?void 0:t.headers])})}toolRunner(e,t){return new UR(this._client,e,t)}};function lT(n){var r;if(!n.output_format)return n;if((r=n.output_config)!=null&&r.format)throw new Ne("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");const{output_format:e,...t}=n;return{...t,output_config:{...n.output_config,format:e}}}ed.Batches=zR;ed.BetaToolRunner=UR;ed.ToolError=DR;class FR extends Vt{list(e,t={},r){const{betas:s,...i}=t??{};return this._client.getAPIList($e`/v1/sessions/${e}/events?beta=true`,es,{query:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}send(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}stream(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers]),stream:!0})}}class BR extends Vt{retrieve(e,t,r){const{session_id:s,betas:i}=t;return this._client.get($e`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{session_id:s,betas:i,...a}=t;return this._client.post($e`/v1/sessions/${s}/resources/${e}?beta=true`,{body:a,...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,t={},r){const{betas:s,...i}=t??{};return this._client.getAPIList($e`/v1/sessions/${e}/resources?beta=true`,es,{query:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,t,r){const{session_id:s,betas:i}=t;return this._client.delete($e`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}add(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class Lp extends Vt{constructor(){super(...arguments),this.events=new FR(this._client),this.resources=new BR(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/sessions?beta=true",{body:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/sessions/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",es,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete($e`/v1/sessions/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post($e`/v1/sessions/${e}/archive?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}Lp.Events=FR;Lp.Resources=BR;class HR extends Vt{create(e,t={},r){const{betas:s,...i}=t??{};return this._client.post($e`/v1/skills/${e}/versions?beta=true`,Nb({body:i,...r,headers:te([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])},this._client))}retrieve(e,t,r){const{skill_id:s,betas:i}=t;return this._client.get($e`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e,t={},r){const{betas:s,...i}=t??{};return this._client.getAPIList($e`/v1/skills/${e}/versions?beta=true`,es,{query:i,...r,headers:te([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}delete(e,t,r){const{skill_id:s,betas:i}=t;return this._client.delete($e`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}}class jb extends Vt{constructor(){super(...arguments),this.versions=new HR(this._client)}create(e={},t){const{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",Nb({body:s,...t,headers:te([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t==null?void 0:t.headers])},this._client,!1))}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/skills/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",es,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete($e`/v1/skills/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r==null?void 0:r.headers])})}}jb.Versions=HR;class VR extends Vt{create(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/vaults/${e}/credentials?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}retrieve(e,t,r){const{vault_id:s,betas:i}=t;return this._client.get($e`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{vault_id:s,betas:i,...a}=t;return this._client.post($e`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:a,...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e,t={},r){const{betas:s,...i}=t??{};return this._client.getAPIList($e`/v1/vaults/${e}/credentials?beta=true`,es,{query:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}delete(e,t,r){const{vault_id:s,betas:i}=t;return this._client.delete($e`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,t,r){const{vault_id:s,betas:i}=t;return this._client.post($e`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:te([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}class Lb extends Vt{constructor(){super(...arguments),this.credentials=new VR(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/vaults?beta=true",{body:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/vaults/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}update(e,t,r){const{betas:s,...i}=t;return this._client.post($e`/v1/vaults/${e}?beta=true`,{body:i,...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",es,{query:s,...t,headers:te([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t==null?void 0:t.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete($e`/v1/vaults/${e}?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post($e`/v1/vaults/${e}/archive?beta=true`,{...r,headers:te([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r==null?void 0:r.headers])})}}Lb.Credentials=VR;class ts extends Vt{constructor(){super(...arguments),this.models=new $R(this._client),this.messages=new ed(this._client),this.agents=new Mb(this._client),this.environments=new IR(this._client),this.sessions=new Lp(this._client),this.vaults=new Lb(this._client),this.files=new CR(this._client),this.skills=new jb(this._client),this.userProfiles=new RR(this._client)}}ts.Models=$R;ts.Messages=ed;ts.Agents=Mb;ts.Environments=IR;ts.Sessions=Lp;ts.Vaults=Lb;ts.Files=CR;ts.Skills=jb;ts.UserProfiles=RR;class ZR extends Vt{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??6e5,...t,headers:te([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers]),stream:e.stream??!1})}}function KR(n){var e;return(e=n==null?void 0:n.output_config)==null?void 0:e.format}function dT(n,e,t){const r=KR(e);return!e||!("parse"in(r??{}))?{...n,content:n.content.map(s=>s.type==="text"?Object.defineProperty({...s},"parsed_output",{value:null,enumerable:!1}):s),parsed_output:null}:WR(n,e)}function WR(n,e,t){let r=null;const s=n.content.map(i=>{if(i.type==="text"){const a=g7(e,i.text);return r===null&&(r=a),Object.defineProperty({...i},"parsed_output",{value:a,enumerable:!1})}return i});return{...n,content:s,parsed_output:r}}function g7(n,e){const t=KR(n);if((t==null?void 0:t.type)!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(r){throw new Ne(`Failed to parse structured output: ${r}`)}}var vr,ci,no,Gc,Vd,Jc,Yc,Zd,Xc,Rs,Qc,Kd,Wd,Ji,qd,Gd,eu,ng,hT,rg,sg,ig,ag,fT;const pT="__json_buf";function mT(n){return n.type==="tool_use"||n.type==="server_tool_use"}class Cf{constructor(e,t){vr.add(this),this.messages=[],this.receivedMessages=[],ci.set(this,void 0),no.set(this,null),this.controller=new AbortController,Gc.set(this,void 0),Vd.set(this,()=>{}),Jc.set(this,()=>{}),Yc.set(this,void 0),Zd.set(this,()=>{}),Xc.set(this,()=>{}),Rs.set(this,{}),Qc.set(this,!1),Kd.set(this,!1),Wd.set(this,!1),Ji.set(this,!1),qd.set(this,void 0),Gd.set(this,void 0),eu.set(this,void 0),rg.set(this,r=>{if(ce(this,Kd,!0),fl(r)&&(r=new qr),r instanceof qr)return ce(this,Wd,!0),this._emit("abort",r);if(r instanceof Ne)return this._emit("error",r);if(r instanceof Error){const s=new Ne(r.message);return s.cause=r,this._emit("error",s)}return this._emit("error",new Ne(String(r)))}),ce(this,Gc,new Promise((r,s)=>{ce(this,Vd,r,"f"),ce(this,Jc,s,"f")})),ce(this,Yc,new Promise((r,s)=>{ce(this,Zd,r,"f"),ce(this,Xc,s,"f")})),P(this,Gc,"f").catch(()=>{}),P(this,Yc,"f").catch(()=>{}),ce(this,no,e),ce(this,eu,(t==null?void 0:t.logger)??console)}get response(){return P(this,qd,"f")}get request_id(){return P(this,Gd,"f")}async withResponse(){ce(this,Ji,!0);const e=await P(this,Gc,"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 t=new Cf(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r,{logger:s}={}){const i=new Cf(t,{logger:s});for(const a of t.messages)i._addMessageParam(a);return ce(i,no,{...t,stream:!0}),i._run(()=>i._createMessage(e,{...t,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,rg,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,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,vr,"m",sg).call(this);const{response:o,data:c}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(o);for await(const u of c)P(this,vr,"m",ig).call(this,u);if((a=c.controller.signal)!=null&&a.aborted)throw new qr;P(this,vr,"m",ag).call(this)}finally{s&&i&&s.removeEventListener("abort",i)}}_connected(e){this.ended||(ce(this,qd,e),ce(this,Gd,e==null?void 0:e.headers.get("request-id")),P(this,Vd,"f").call(this,e),this._emit("connect"))}get ended(){return P(this,Qc,"f")}get errored(){return P(this,Kd,"f")}get aborted(){return P(this,Wd,"f")}abort(){this.controller.abort()}on(e,t){return(P(this,Rs,"f")[e]||(P(this,Rs,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=P(this,Rs,"f")[e];if(!r)return this;const s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(P(this,Rs,"f")[e]||(P(this,Rs,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{ce(this,Ji,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){ce(this,Ji,!0),await P(this,Yc,"f")}get currentMessage(){return P(this,ci,"f")}async finalMessage(){return await this.done(),P(this,vr,"m",ng).call(this)}async finalText(){return await this.done(),P(this,vr,"m",hT).call(this)}_emit(e,...t){if(P(this,Qc,"f"))return;e==="end"&&(ce(this,Qc,!0),P(this,Zd,"f").call(this));const r=P(this,Rs,"f")[e];if(r&&(P(this,Rs,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!P(this,Ji,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,Jc,"f").call(this,s),P(this,Xc,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!P(this,Ji,"f")&&!(r!=null&&r.length)&&Promise.reject(s),P(this,Jc,"f").call(this,s),P(this,Xc,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",P(this,vr,"m",ng).call(this))}async _fromReadableStream(e,t){var i;const r=t==null?void 0:t.signal;let s;r&&(r.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),r.addEventListener("abort",s));try{P(this,vr,"m",sg).call(this),this._connected(null);const a=_s.fromReadableStream(e,this.controller);for await(const o of a)P(this,vr,"m",ig).call(this,o);if((i=a.controller.signal)!=null&&i.aborted)throw new qr;P(this,vr,"m",ag).call(this)}finally{r&&s&&r.removeEventListener("abort",s)}}[(ci=new WeakMap,no=new WeakMap,Gc=new WeakMap,Vd=new WeakMap,Jc=new WeakMap,Yc=new WeakMap,Zd=new WeakMap,Xc=new WeakMap,Rs=new WeakMap,Qc=new WeakMap,Kd=new WeakMap,Wd=new WeakMap,Ji=new WeakMap,qd=new WeakMap,Gd=new WeakMap,eu=new WeakMap,rg=new WeakMap,vr=new WeakSet,ng=function(){if(this.receivedMessages.length===0)throw new Ne("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},hT=function(){if(this.receivedMessages.length===0)throw new Ne("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new Ne("stream ended without producing a content block with type=text");return t.join(" ")},sg=function(){this.ended||ce(this,ci,void 0)},ig=function(t){if(this.ended)return;const r=P(this,vr,"m",fT).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{const s=r.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{mT(s)&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(dT(r,P(this,no,"f"),{logger:P(this,eu,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{ce(this,ci,r);break}}},ag=function(){if(this.ended)throw new Ne("stream has ended, this shouldn't happen");const t=P(this,ci,"f");if(!t)throw new Ne("request ended without sending any chunks");return ce(this,ci,void 0),dT(t,P(this,no,"f"),{logger:P(this,eu,"f")})},fT=function(t){let r=P(this,ci,"f");if(t.type==="message_start"){if(r)throw new Ne(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new Ne(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(r.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(r.usage.server_tool_use=t.usage.server_tool_use),r;case"content_block_start":return r.content.push({...t.content_block}),r;case"content_block_delta":{const s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{(s==null?void 0:s.type)==="text"&&(r.content[t.index]={...s,text:(s.text||"")+t.delta.text});break}case"citations_delta":{(s==null?void 0:s.type)==="text"&&(r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]});break}case"input_json_delta":{if(s&&mT(s)){let i=s[pT]||"";i+=t.delta.partial_json;const a={...s};Object.defineProperty(a,pT,{value:i,enumerable:!1,writable:!0}),i&&(a.input=LR(i)),r.content[t.index]=a}break}case"thinking_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking});break}case"signature_delta":{(s==null?void 0:s.type)==="thinking"&&(r.content[t.index]={...s,signature:t.delta.signature});break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("streamEvent",s=>{const i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,a)=>t.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 _s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class qR extends Vt{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get($e`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",Ql,{query:e,...t})}delete(e,t){return this._client.delete($e`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post($e`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const r=await this.retrieve(e);if(!r.results_url)throw new Ne(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:te([{Accept:"application/binary"},t==null?void 0:t.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,i)=>jp.fromResponse(i.response,i.controller))}}class Db extends Vt{constructor(){super(...arguments),this.batches=new qR(this._client)}create(e,t){e.model in gT&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${gT[e.model]}
|
|
641
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),_7.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=NR[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}const s=OR(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...t,headers:te([s,t==null?void 0:t.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(r=>WR(r,e,{logger:this._client.logger??console}))}stream(e,t){return Cf.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const gT={"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"},_7=["claude-mythos-preview","claude-opus-4-6"];Db.Batches=qR;class GR extends Vt{retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get($e`/v1/models/${e}`,{...r,headers:te([{...(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={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models",Ql,{query:s,...t,headers:te([{...(r==null?void 0:r.toString())!=null?{"anthropic-beta":r==null?void 0:r.toString()}:void 0},t==null?void 0:t.headers])})}}var og={};const Jd=n=>{var e,t,r,s;if(typeof globalThis.process<"u")return((e=og==null?void 0:og[n])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(r=(t=globalThis.Deno.env)==null?void 0:t.get)==null?void 0:r.call(t,n))==null?void 0:s.trim())||void 0};var dy,Ub,Ch,JR;const y7="\\n\\nHuman:",w7="\\n\\nAssistant:";class Zt{constructor({baseURL:e=Jd("ANTHROPIC_BASE_URL"),apiKey:t=Jd("ANTHROPIC_API_KEY")??null,authToken:r=Jd("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){dy.add(this),Ch.set(this,void 0);const i={apiKey:t,authToken:r,...s,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&NJ())throw new Ne(`It looks like you're running in a browser-like environment.
|
|
642
|
+
|
|
643
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
644
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
645
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
646
|
+
|
|
647
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
648
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Ub.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=XA(i.logLevel,"ClientOptions.logLevel",this)??XA(Jd("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??UJ(),ce(this,Ch,FJ),this._options=i,this.apiKey=typeof t=="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return te([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return te([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return te([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return BJ(e)}getUserAgent(){return`${this.constructor.name}/JS ${fo}`}defaultIdempotencyKey(){return`stainless-node-retry-${aR()}`}makeStatusError(e,t,r,s){return In.generate(e,t,r,s)}buildURL(e,t,r){const s=!P(this,dy,"m",JR).call(this)&&r||this.baseURL,i=CJ(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!ZA(a)||!ZA(o))&&(t={...o,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Ne("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Mp(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var b,_;const s=await e,i=s.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(s);const{req:a,url:o,timeout:c}=await this.buildRequest(s,{retryCount:i-t});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(Nn(this).debug(`[${u}] sending request`,ra({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(iy),m=Date.now();if(h instanceof globalThis.Error){const w=`retrying, ${t} attempts remaining`;if((_=s.signal)!=null&&_.aborted)throw new qr;const S=fl(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Nn(this).info(`[${u}] connection ${S?"timed out":"failed"} - ${w}`),Nn(this).debug(`[${u}] connection ${S?"timed out":"failed"} (${w})`,ra({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),this.retryRequest(s,t,r??u);throw Nn(this).info(`[${u}] connection ${S?"timed out":"failed"} - error; no more retries left`),Nn(this).debug(`[${u}] connection ${S?"timed out":"failed"} (error; no more retries left)`,ra({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),S?new oR:new Np({cause:h})}const g=[...h.headers.entries()].filter(([w])=>w==="request-id").map(([w,S])=>", "+w+": "+JSON.stringify(S)).join(""),y=`[${u}${l}${g}] ${a.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${m-d}ms`;if(!h.ok){const w=await this.shouldRetry(h);if(t&&w){const R=`retrying, ${t} attempts remaining`;return await zJ(h.body),Nn(this).info(`${y} - ${R}`),Nn(this).debug(`[${u}] response error (${R})`,ra({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),this.retryRequest(s,t,r??u,h.headers)}const S=w?"error; no more retries left":"error; not retryable";Nn(this).info(`${y} - ${S}`);const T=await h.text().catch(R=>iy(R).message),A=gR(T),I=A?void 0:T;throw Nn(this).debug(`[${u}] response error (${S})`,ra({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:I,durationMs:Date.now()-d})),this.makeStatusError(h.status,A,I,h.headers)}return Nn(this).info(y),Nn(this).debug(`[${u}] response start`,ra({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),{response:h,options:s,controller:f,requestLogID:u,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new YJ(this,r,e)}async fetchWithTimeout(e,t,r,s){const{signal:i,method:a,...o}=t||{},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 t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,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(t,c)}return await PJ(i),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return a*o*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new Ne("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:t=0}={}){const r={...e},{method:s,path:i,query:a,defaultBaseURL:o}=r,c=this.buildURL(i,a,o);"timeout"in r&&RJ("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:t});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:t,bodyHeaders:r,retryCount:s}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=te([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))}:{},...DJ(),...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:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=te([t]);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:yR(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,Ch,"f").call(this,{body:e,headers:r})}}Ub=Zt,Ch=new WeakMap,dy=new WeakSet,JR=function(){return this.baseURL!=="https://api.anthropic.com"};Zt.Anthropic=Ub;Zt.HUMAN_PROMPT=y7;Zt.AI_PROMPT=w7;Zt.DEFAULT_TIMEOUT=6e5;Zt.AnthropicError=Ne;Zt.APIError=In;Zt.APIConnectionError=Np;Zt.APIConnectionTimeoutError=oR;Zt.APIUserAbortError=qr;Zt.NotFoundError=dR;Zt.ConflictError=hR;Zt.RateLimitError=pR;Zt.BadRequestError=cR;Zt.AuthenticationError=uR;Zt.InternalServerError=mR;Zt.PermissionDeniedError=lR;Zt.UnprocessableEntityError=fR;Zt.toFile=r7;class td extends Zt{constructor(){super(...arguments),this.completions=new ZR(this),this.messages=new Db(this),this.models=new GR(this),this.beta=new ts(this)}}td.Completions=ZR;td.Messages=Db;td.Models=GR;td.Beta=ts;const b7=n=>n,v7={"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},_T=4096;function S7(n){var e;return n?((e=Object.entries(v7).find(([t])=>n.startsWith(t)))==null?void 0:e[1])??_T:_T}function A7(n){return!!(n.tools&&n.tools.length>0)}function T7(n){var e;for(const t of n.messages??[])if(typeof t.content!="string"){for(const r of t.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 E7(n){return!!(n.thinking&&(n.thinking.type==="enabled"||n.thinking.type==="adaptive"))}function k7(n){var e,t;return!!((t=(e=n.context_management)==null?void 0:e.edits)!=null&&t.some(r=>r.type==="compact_20260112"))}function I7(n){return"input_schema"in n}function x7(n){return typeof n=="object"&&n!==null&&"type"in n&&("name"in n||"mcp_server_name"in n)&&typeof n.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 n.type=="string"&&n.type.startsWith(e))}function O7(n,e,...t){return Array.from(new Set([...n??[],...e??[],...t.flatMap(r=>Array.from(r))]))}function C7(n){if(typeof n.content=="string")return n.content;if(Array.isArray(n.content)&&n.content.length>=1&&"input"in n.content[0])return typeof n.content[0].input=="string"?n.content[0].input:JSON.stringify(n.content[0].input);if(Array.isArray(n.content)&&n.content.length>=1&&"text"in n.content[0]&&typeof n.content[0].text=="string")return n.content[0].text}var $7=class extends Is{constructor(e,t){const r=typeof e=="string"?{...t??{},model:e}:e??{};super(r??{});p(this,"lc_serializable",!0);p(this,"anthropicApiKey");p(this,"apiKey");p(this,"apiUrl");p(this,"temperature");p(this,"topK");p(this,"topP");p(this,"maxTokens");p(this,"modelName","claude-sonnet-4-5-20250929");p(this,"model","claude-sonnet-4-5-20250929");p(this,"invocationKwargs");p(this,"stopSequences");p(this,"streaming",!1);p(this,"clientOptions");p(this,"thinking",{type:"disabled"});p(this,"contextManagement");p(this,"outputConfig");p(this,"inferenceGeo");p(this,"batchClient");p(this,"streamingClient");p(this,"streamUsage",!0);p(this,"betas");p(this,"createClient");if(this._addVersion("@langchain/anthropic","1.3.28"),this.anthropicApiKey=(r==null?void 0:r.apiKey)??(r==null?void 0:r.anthropicApiKey)??Bt("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)??S7(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 td(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 t=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(t=>{var r;if(Ys(t)&&((r=t.extras)!=null&&r.providerToolDefinition))return t.extras.providerToolDefinition;if(x7(t)||I7(t))return t;if(Sc(t))return{name:t.function.name,description:t.function.description,input_schema:t.function.parameters};if(Ys(t))return{name:t.name,description:t.description,input_schema:Xt(t.schema)?At(t.schema):t.schema,...t.extras?uJ.parse(t.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(t,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){var c,u,l;const t=cJ(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 UA){const h=UA[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=AJ(this.model,s),o={model:this.model,stop_sequences:(e==null?void 0:e.stop)??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e==null?void 0:e.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e==null?void 0:e.container,betas:O7(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};return TJ({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,EJ({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,r){var u;const s=this.invocationParams(t);let i=FA(e);t.cache_control&&(i=BA(i,t.cache_control));const a={...s,...i,stream:!0},o=!A7(a)&&!T7(a)&&!E7(a)&&!k7(a),c=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal});for await(const l of c){if((u=t.signal)!=null&&u.aborted){c.controller.abort();return}const d=this.streamUsage??t.streamUsage,f=kJ(l,{streamUsage:d,coerceContentToString:o});if(!f)continue;const{chunk:h}=f,m=C7(h),g=new fr({message:new nt({content:h.content,additional_kwargs:h.additional_kwargs,tool_call_chunks:h.tool_call_chunks,usage_metadata:d?h.usage_metadata:void 0,response_metadata:h.response_metadata,id:h.id}),text:m??""});yield g,await(r==null?void 0:r.handleLLMNewToken(m??"",void 0,void 0,void 0,void 0,{chunk:g}))}}async _generateNonStreaming(e,t,r,s){let i=FA(e);s&&(i=BA(i,s));const{content:a,...o}=await this.completionWithRetry({...t,stream:!1,...i},r),c=IJ(a,o),{role:u,type:l,...d}=o;return{generations:c,llmOutput:d}}async _generate(e,t,r){var i;if((i=t.signal)==null||i.throwIfAborted(),this.stopSequences&&t.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(t);if(s.stream){let a;const o=this._streamResponseChunks(e,t,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:t.signal,headers:t.headers},t.cache_control)}async createStreamWithRetry(e,t){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},t):await this.streamingClient.messages.create({...s,...this.invocationKwargs,stream:!0},t)}catch(o){throw HA(o)}};return this.caller.call(i)}async completionWithRetry(e,t){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},t):await this.batchClient.messages.create({...s,...this.invocationKwargs},t)}catch(o){throw HA(o)}};return this.caller.callWithOptions({signal:t.signal??void 0},i)}_llmType(){return"anthropic"}get profile(){return xJ[this.model]??{}}withStructuredOutput(e,t){var u,l;let r,s;const{schema:i,name:a,includeRaw:o}={...t,schema:e};let c=(t==null?void 0:t.method)??"functionCalling";if(c==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),c="jsonSchema"),c==="jsonSchema"){s=uc(i);const d=b7(At(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(Xt(i)||Or(i)){const h=At(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=zl(i,d,oJ),((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:At(i)}});const m=g=>{if(!g.tool_calls||g.tool_calls.length===0)throw new Error(h);return g};r=r.pipe(m)}else r=this.withConfig({outputVersion:"v0",tools:f,tool_choice:{type:"tool",name:d},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:At(i)}})}else throw new TypeError(`Unrecognized structured output method '${c}'. Expected 'functionCalling' or 'jsonSchema'`);return Ec(r,s,o,o?"StructuredOutputRunnable":"ChatAnthropicStructuredOutput")}},yT=class extends $7{};const R7=Me({command:Ze("view"),path:Xe()}),P7=Me({command:Ze("create"),path:Xe(),file_text:Xe()}),N7=Me({command:Ze("str_replace"),path:Xe(),old_str:Xe(),new_str:Xe()}),M7=Me({command:Ze("insert"),path:Xe(),insert_line:gt(),insert_text:Xe()}),j7=Me({command:Ze("delete"),path:Xe()}),L7=Me({command:Ze("rename"),old_path:Xe(),new_path:Xe()});pp("command",[R7,P7,N7,M7,j7,L7]);const D7=Me({command:Ze("view"),path:Xe(),view_range:Lw([gt(),gt()]).optional()}),U7=Me({command:Ze("str_replace"),path:Xe(),old_str:Xe(),new_str:Xe()}),z7=Me({command:Ze("create"),path:Xe(),file_text:Xe()}),F7=Me({command:Ze("insert"),path:Xe(),insert_line:gt(),new_str:Xe()});pp("command",[D7,U7,z7,F7]);const Qr=Lw([gt(),gt()]),YR=Me({action:Ze("screenshot")}),XR=Me({action:Ze("left_click"),coordinate:Qr}),QR=Me({action:Ze("right_click"),coordinate:Qr}),eP=Me({action:Ze("middle_click"),coordinate:Qr}),tP=Me({action:Ze("double_click"),coordinate:Qr}),nP=Me({action:Ze("triple_click"),coordinate:Qr}),rP=Me({action:Ze("left_click_drag"),start_coordinate:Qr,end_coordinate:Qr}),sP=Me({action:Ze("left_mouse_down"),coordinate:Qr}),iP=Me({action:Ze("left_mouse_up"),coordinate:Qr}),aP=Me({action:Ze("scroll"),coordinate:Qr,scroll_direction:mp(["up","down","left","right"]),scroll_amount:gt()}),oP=Me({action:Ze("type"),text:Xe()}),cP=Me({action:Ze("key"),key:Xe()}),uP=Me({action:Ze("mouse_move"),coordinate:Qr}),lP=Me({action:Ze("hold_key"),key:Xe()}),dP=Me({action:Ze("wait"),duration:gt().optional()}),B7=Me({action:Ze("zoom"),region:Lw([gt(),gt(),gt(),gt()])});pp("action",[YR,XR,QR,eP,tP,nP,rP,sP,iP,aP,oP,cP,uP,lP,dP]);pp("action",[YR,XR,QR,eP,tP,nP,rP,sP,iP,aP,oP,cP,uP,lP,dP,B7]);const H7=Me({command:Xe().describe("The bash command to run")}),V7=Me({restart:Ze(!0).describe("Set to true to restart the bash session")});Zl([H7,V7]);function Z7(n,e){var t;return new nt({content:n.content??"",additional_kwargs:n.thinking&&n.thinking!==""?{reasoning_content:n.thinking}:{},tool_call_chunks:(t=n.tool_calls)==null?void 0:t.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:Ni()})),response_metadata:{...e==null?void 0:e.responseMetadata,model_provider:"ollama"},usage_metadata:e==null?void 0:e.usageMetadata})}function wT(n){const e=n.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function K7(n){var r,s,i,a;if(typeof n.content=="string"){if((r=n.tool_calls)!=null&&r.length){const o=n.tool_calls.map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:c.args}}));return[{role:"assistant",content:n.content,tool_calls:o}]}return[{role:"assistant",content:n.content}]}const e=n.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>({role:"assistant",content:o.text}));let t;if(n.content.find(o=>o.type==="tool_use")&&((s=n.tool_calls)!=null&&s.length)){const o=(i=n.tool_calls)==null?void 0:i.map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:c.args}}));o&&(t={role:"assistant",tool_calls:o,content:""})}else if(n.content.find(o=>o.type==="tool_use")&&!((a=n.tool_calls)!=null&&a.length))throw new Error("'tool_use' content type is not supported without tool calls.");return[...e,...t?[t]:[]]}function W7(n){return typeof n.content=="string"?[{role:"user",content:n.content}]:n.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:[wT(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url=="string")return{role:"user",content:"",images:[wT(e.image_url.url)]}}throw new Error(`Unsupported content type: ${e.type}`)})}function q7(n){if(typeof n.content=="string")return[{role:"system",content:n.content}];if(n.content.every(e=>e.type==="text"&&typeof e.text=="string"))return n.content.map(e=>({role:"system",content:e.text}));throw new Error(`Unsupported content type(s): ${n.content.map(e=>e.type).join(", ")}`)}function G7(n){if(typeof n.content!="string")throw new Error("Non string tool message content is not supported");return[{role:"tool",content:n.content}]}function J7(n){return n.flatMap(e=>{if(["human","generic"].includes(e._getType()))return W7(e);if(e._getType()==="ai")return K7(e);if(e._getType()==="system")return q7(e);if(e._getType()==="tool")return G7(e);throw new Error(`Unsupported message type: ${e._getType()}`)})}var fn=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},jn={searchParams:"URLSearchParams"in fn,iterable:"Symbol"in fn&&"iterator"in Symbol,blob:"FileReader"in fn&&"Blob"in fn&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in fn,arrayBuffer:"ArrayBuffer"in fn};function Y7(n){return n&&DataView.prototype.isPrototypeOf(n)}if(jn.arrayBuffer)var X7=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Q7=ArrayBuffer.isView||function(n){return n&&X7.indexOf(Object.prototype.toString.call(n))>-1};function Cc(n){if(typeof n!="string"&&(n=String(n)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(n)||n==="")throw new TypeError('Invalid character in header field name: "'+n+'"');return n.toLowerCase()}function zb(n){return typeof n!="string"&&(n=String(n)),n}function Fb(n){var e={next:function(){var t=n.shift();return{done:t===void 0,value:t}}};return jn.iterable&&(e[Symbol.iterator]=function(){return e}),e}function Qt(n){this.map={},n instanceof Qt?n.forEach(function(e,t){this.append(t,e)},this):Array.isArray(n)?n.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):n&&Object.getOwnPropertyNames(n).forEach(function(e){this.append(e,n[e])},this)}Qt.prototype.append=function(n,e){n=Cc(n),e=zb(e);var t=this.map[n];this.map[n]=t?t+", "+e:e};Qt.prototype.delete=function(n){delete this.map[Cc(n)]};Qt.prototype.get=function(n){return n=Cc(n),this.has(n)?this.map[n]:null};Qt.prototype.has=function(n){return this.map.hasOwnProperty(Cc(n))};Qt.prototype.set=function(n,e){this.map[Cc(n)]=zb(e)};Qt.prototype.forEach=function(n,e){for(var t in this.map)this.map.hasOwnProperty(t)&&n.call(e,this.map[t],t,this)};Qt.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),Fb(n)};Qt.prototype.values=function(){var n=[];return this.forEach(function(e){n.push(e)}),Fb(n)};Qt.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),Fb(n)};jn.iterable&&(Qt.prototype[Symbol.iterator]=Qt.prototype.entries);function cg(n){if(!n._noBody){if(n.bodyUsed)return Promise.reject(new TypeError("Already read"));n.bodyUsed=!0}}function hP(n){return new Promise(function(e,t){n.onload=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function eY(n){var e=new FileReader,t=hP(e);return e.readAsArrayBuffer(n),t}function tY(n){var e=new FileReader,t=hP(e),r=/charset=([A-Za-z0-9_-]+)/.exec(n.type),s=r?r[1]:"utf-8";return e.readAsText(n,s),t}function nY(n){for(var e=new Uint8Array(n),t=new Array(e.length),r=0;r<e.length;r++)t[r]=String.fromCharCode(e[r]);return t.join("")}function bT(n){if(n.slice)return n.slice(0);var e=new Uint8Array(n.byteLength);return e.set(new Uint8Array(n)),e.buffer}function fP(){return this.bodyUsed=!1,this._initBody=function(n){this.bodyUsed=this.bodyUsed,this._bodyInit=n,n?typeof n=="string"?this._bodyText=n:jn.blob&&Blob.prototype.isPrototypeOf(n)?this._bodyBlob=n:jn.formData&&FormData.prototype.isPrototypeOf(n)?this._bodyFormData=n:jn.searchParams&&URLSearchParams.prototype.isPrototypeOf(n)?this._bodyText=n.toString():jn.arrayBuffer&&jn.blob&&Y7(n)?(this._bodyArrayBuffer=bT(n.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):jn.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(n)||Q7(n))?this._bodyArrayBuffer=bT(n):this._bodyText=n=Object.prototype.toString.call(n):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof n=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):jn.searchParams&&URLSearchParams.prototype.isPrototypeOf(n)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},jn.blob&&(this.blob=function(){var n=cg(this);if(n)return n;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 n=cg(this);return n||(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(jn.blob)return this.blob().then(eY);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var n=cg(this);if(n)return n;if(this._bodyBlob)return tY(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(nY(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},jn.formData&&(this.formData=function(){return this.text().then(iY)}),this.json=function(){return this.text().then(JSON.parse)},this}var rY=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function sY(n){var e=n.toUpperCase();return rY.indexOf(e)>-1?e:n}function ja(n,e){if(!(this instanceof ja))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var t=e.body;if(n instanceof ja){if(n.bodyUsed)throw new TypeError("Already read");this.url=n.url,this.credentials=n.credentials,e.headers||(this.headers=new Qt(n.headers)),this.method=n.method,this.mode=n.mode,this.signal=n.signal,!t&&n._bodyInit!=null&&(t=n._bodyInit,n.bodyUsed=!0)}else this.url=String(n);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new Qt(e.headers)),this.method=sY(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in fn){var i=new AbortController;return i.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&t)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(t),(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()}}}ja.prototype.clone=function(){return new ja(this,{body:this._bodyInit})};function iY(n){var e=new FormData;return n.trim().split("&").forEach(function(t){if(t){var r=t.split("="),s=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(s),decodeURIComponent(i))}}),e}function aY(n){var e=new Qt,t=n.replace(/\r?\n[\t ]+/g," ");return t.split("\r").map(function(r){return r.indexOf(`
|
|
649
|
+
`)===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}fP.call(ja.prototype);function Es(n,e){if(!(this instanceof Es))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 Qt(e.headers),this.url=e.url||"",this._initBody(n)}fP.call(Es.prototype);Es.prototype.clone=function(){return new Es(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Qt(this.headers),url:this.url})};Es.error=function(){var n=new Es(null,{status:200,statusText:""});return n.ok=!1,n.status=0,n.type="error",n};var oY=[301,302,303,307,308];Es.redirect=function(n,e){if(oY.indexOf(e)===-1)throw new RangeError("Invalid status code");return new Es(null,{status:e,headers:{location:n}})};var aa=fn.DOMException;try{new aa}catch{aa=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},aa.prototype=Object.create(Error.prototype),aa.prototype.constructor=aa}function pP(n,e){return new Promise(function(t,r){var s=new ja(n,e);if(s.signal&&s.signal.aborted)return r(new aa("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var u={statusText:i.statusText,headers:aY(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(){t(new Es(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 aa("Aborted","AbortError"))},0)};function o(u){try{return u===""&&fn.location.href?fn.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&&(jn.blob?i.responseType="blob":jn.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Qt||fn.Headers&&e.headers instanceof fn.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(u){c.push(Cc(u)),i.setRequestHeader(u,zb(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)})}pP.polyfill=!0;fn.fetch||(fn.fetch=pP,fn.Headers=Qt,fn.Request=ja,fn.Response=Es);var ug={};const mP="11434",gP=`http://127.0.0.1:${mP}`,cY="0.6.3";var uY=Object.defineProperty,lY=(n,e,t)=>e in n?uY(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,lg=(n,e,t)=>(lY(n,typeof e!="symbol"?e+"":e,t),t);class Bb extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,Bb)}}class dY{constructor(e,t,r){lg(this,"abortController"),lg(this,"itr"),lg(this,"doneCallback"),this.abortController=e,this.itr=t,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 Hb=async n=>{var r;if(n.ok)return;let e=`Error ${n.status}: ${n.statusText}`,t=null;if((r=n.headers.get("content-type"))!=null&&r.includes("application/json"))try{t=await n.json(),e=t.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await n.text()||e}catch{console.log("Failed to get text from error response")}throw new Bb(e,n.status)};function hY(){var n;if(typeof window<"u"&&window.navigator){const e=navigator;return"userAgentData"in e&&((n=e.userAgentData)!=null&&n.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 fY(n){if(n instanceof Headers){const e={};return n.forEach((t,r)=>{e[r]=t}),e}else return Array.isArray(n)?Object.fromEntries(n):n||{}}const pY=(n,e)=>n[e],Vb=async(n,e,t={})=>{const r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${cY} (${hY()})`};t.headers=fY(t.headers);try{const i=new URL(e);if(i.protocol==="https:"&&i.hostname==="ollama.com"){const a=typeof process=="object"&&process!==null&&typeof ug=="object"&&ug!==null?pY(ug,"OLLAMA_API_KEY"):void 0;!(t.headers.authorization||t.headers.Authorization)&&a&&(t.headers.Authorization=`Bearer ${a}`)}}catch(i){console.error("error parsing url",i)}const s=Object.fromEntries(Object.entries(t.headers).filter(([i])=>!Object.keys(r).some(a=>a.toLowerCase()===i.toLowerCase())));return t.headers={...r,...s},n(e,t)},dg=async(n,e,t)=>{const r=await Vb(n,e,{headers:t==null?void 0:t.headers});return await Hb(r),r},ui=async(n,e,t,r)=>{const i=(o=>o!==null&&typeof o=="object"&&!Array.isArray(o))(t)?JSON.stringify(t):t,a=await Vb(n,e,{method:"POST",body:i,signal:r==null?void 0:r.signal,headers:r==null?void 0:r.headers});return await Hb(a),a},mY=async(n,e,t,r)=>{const s=await Vb(n,e,{method:"DELETE",body:JSON.stringify(t),headers:r==null?void 0:r.headers});return await Hb(s),s},gY=async function*(n){const e=new TextDecoder("utf-8");let t="";const r=n.getReader();for(;;){const{done:s,value:i}=await r.read();if(s)break;t+=e.decode(i,{stream:!0});const a=t.split(`
|
|
650
|
+
`);t=a.pop()??"";for(const o of a)try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}}t+=e.decode();for(const s of t.split(`
|
|
651
|
+
`).filter(i=>i!==""))try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}},_Y=n=>{if(!n)return gP;let e=n.includes("://");n.startsWith(":")&&(n=`http://127.0.0.1${n}`,e=!0),e||(n=`http://${n}`);const t=new URL(n);let r=t.port;r||(e?r=t.protocol==="https:"?"443":"80":r=mP);let s="";t.username&&(s=t.username,t.password&&(s+=`:${t.password}`),s+="@");let i=`${t.protocol}//${s}${t.hostname}:${r}${t.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i};var yY=Object.defineProperty,wY=(n,e,t)=>e in n?yY(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,hg=(n,e,t)=>(wY(n,typeof e!="symbol"?e+"":e,t),t);let _P=class{constructor(e){hg(this,"config"),hg(this,"fetch"),hg(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=_Y((e==null?void 0:e.host)??gP)),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,t){t.stream=t.stream??!1;const r=`${this.config.host}/api/${e}`;if(t.stream){const i=new AbortController,a=await ui(this.fetch,r,t,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");const o=gY(a.body),c=new dY(i,o,()=>{const u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await ui(this.fetch,r,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){const t=new Uint8Array(e);let r="";const s=t.byteLength;for(let i=0;i<s;i++)r+=String.fromCharCode(t[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 t of e.messages)t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await mY(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await ui(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await dg(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await ui(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await ui(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await ui(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await dg(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await dg(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 ui(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 ui(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}};new _P;var bY=class extends Is{constructor(e,t){const r=typeof e=="string"?{...t??{},model:e}:e??{};super(r);p(this,"model","llama3");p(this,"numa");p(this,"numCtx");p(this,"numBatch");p(this,"numGpu");p(this,"mainGpu");p(this,"lowVram");p(this,"f16Kv");p(this,"logitsAll");p(this,"vocabOnly");p(this,"useMmap");p(this,"useMlock");p(this,"embeddingOnly");p(this,"numThread");p(this,"numKeep");p(this,"seed");p(this,"numPredict");p(this,"topK");p(this,"topP");p(this,"tfsZ");p(this,"typicalP");p(this,"repeatLastN");p(this,"temperature");p(this,"repeatPenalty");p(this,"presencePenalty");p(this,"frequencyPenalty");p(this,"mirostat");p(this,"mirostatTau");p(this,"mirostatEta");p(this,"penalizeNewline");p(this,"streaming");p(this,"format");p(this,"keepAlive");p(this,"client");p(this,"checkOrPullModel",!1);p(this,"baseUrl","http://127.0.0.1:11434");p(this,"think");this._addVersion("@langchain/ollama","1.2.7"),this.baseUrl=r.baseUrl??Bt("OLLAMA_BASE_URL")??this.baseUrl,this.client=new _P({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,t){const{stream:r,insecure:s,logProgress:i}={stream:!0,...t};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,t){return this.withConfig({tools:e.map(r=>uf(r)),...t})}getLsParams(e){var r,s;const t=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:((r=t.options)==null?void 0:r.temperature)??void 0,ls_max_tokens:((s=t.options)==null?void 0:s.num_predict)??void 0,ls_stop:e.stop}}invocationParams(e){var t;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:(t=e==null?void 0:e.tools)!=null&&t.length?e.tools.map(r=>uf(r)):void 0}}async checkModelExistsOnMachine(e){const{models:t}=await this.client.list();return!!t.find(r=>r.name===e||r.name===`${e}:latest`)}async _generate(e,t,r){var a;(a=t.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,t,r))s?s=Ws(s,o.message):s=o.message;const i=new Ve({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,t,r){var u;this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));const s=this.invocationParams(t),i=J7(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=t.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??"",m=new fr({text:h,message:Z7(d)});yield m,await(r==null?void 0:r.handleLLMNewToken(h,void 0,void 0,void 0,void 0,{chunk:m}))}yield new fr({text:"",message:new nt({content:"",response_metadata:{...c,model_provider:"ollama"},usage_metadata:a})})}withStructuredOutput(e,t){let r,s;const{schema:i,name:a,includeRaw:o}={...t,schema:e},c=(t==null?void 0:t.method)??"jsonSchema";if(c==="functionCalling"){let u=a??"extract",l;const d=At(i);Xt(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:Xt(i)||Or(i)?d:i}}),s=zl(i,u)}else if(c==="jsonMode"||c==="jsonSchema"){s=uc(i);const u=At(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 Ec(r,s,o,o?"StructuredOutputRunnable":"ChatOllamaStructuredOutput")}},ot;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},n.getValidEnumValues=s=>{const i=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return n.objectValues(a)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.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},n.find=(s,i)=>{for(const a of s)if(i(a))return a},n.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)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ot||(ot={}));var vT;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(vT||(vT={}));const be=ot.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pi=n=>{switch(typeof n){case"undefined":return be.undefined;case"string":return be.string;case"number":return Number.isNaN(n)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(n)?be.array:n===null?be.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?be.promise:typeof Map<"u"&&n instanceof Map?be.map:typeof Set<"u"&&n instanceof Set?be.set:typeof Date<"u"&&n instanceof Date?be.date:be.object;default:return be.unknown}},J=ot.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 Xs 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=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(t(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(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),r}static assert(e){if(!(e instanceof Xs))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ot.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Xs.create=n=>new Xs(n);const hy=(n,e)=>{let t;switch(n.code){case J.invalid_type:n.received===be.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case J.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,ot.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:t=`Unrecognized key(s) in object: ${ot.joinValues(n.keys,", ")}`;break;case J.invalid_union:t="Invalid input";break;case J.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ot.joinValues(n.options)}`;break;case J.invalid_enum_value:t=`Invalid enum value. Expected ${ot.joinValues(n.options)}, received '${n.received}'`;break;case J.invalid_arguments:t="Invalid function arguments";break;case J.invalid_return_type:t="Invalid function return type";break;case J.invalid_date:t="Invalid date";break;case J.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:ot.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case J.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case J.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case J.custom:t="Invalid input";break;case J.invalid_intersection_types:t="Intersection results could not be merged";break;case J.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case J.not_finite:t="Number must be finite";break;default:t=e.defaultError,ot.assertNever(n)}return{message:t}};let vY=hy;function SY(){return vY}const AY=n=>{const{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...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 le(n,e){const t=SY(),r=AY({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===hy?void 0:hy].filter(s=>!!s)});n.common.issues.push(r)}class mr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if(s.status==="aborted")return Le;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return mr.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return Le;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 Le=Object.freeze({status:"aborted"}),Tu=n=>({status:"dirty",value:n}),Rr=n=>({status:"valid",value:n}),ST=n=>n.status==="aborted",AT=n=>n.status==="dirty",mc=n=>n.status==="valid",$f=n=>typeof Promise<"u"&&n instanceof Promise;var Se;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Se||(Se={}));class zi{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,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 TT=(n,e)=>{if(mc(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Xs(n.common.issues);return this._error=t,this._error}}};function qe(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||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}=n;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??t??o.defaultError}},description:s}}class it{get description(){return this._def.description}_getType(e){return pi(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:pi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new mr,ctx:{common:e.parent.common,data:e.data,parsedType:pi(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if($f(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pi(e)},s=this._parseSync({data:e,path:r.path,parent:r});return TT(r,s)}"~validate"(e){var r,s;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pi(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return mc(i)?{value:i.value}:{issues:t.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),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>mc(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pi(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await($f(s)?s:Promise.resolve(s));return TT(r,i)}refine(e,t){const r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:J.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new yc({schema:this,typeName:De.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:t=>this["~validate"](t)}}optional(){return Ri.create(this,this._def)}nullable(){return wc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ss.create(this)}promise(){return Mf.create(this,this._def)}or(e){return Pf.create([this,e],this._def)}and(e){return Nf.create(this,e,this._def)}transform(e){return new yc({...qe(this._def),schema:this,typeName:De.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new my({...qe(this._def),innerType:this,defaultValue:t,typeName:De.ZodDefault})}brand(){return new KY({typeName:De.ZodBranded,type:this,...qe(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new gy({...qe(this._def),innerType:this,catchValue:t,typeName:De.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Zb.create(this,e)}readonly(){return _y.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const TY=/^c[^\s-]{8,}$/i,EY=/^[0-9a-z]+$/,kY=/^[0-9A-HJKMNP-TV-Z]{26}$/i,IY=/^[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,xY=/^[a-z0-9_-]{21}$/i,OY=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,CY=/^[-+]?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)?)??$/,$Y=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,RY="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let fg;const PY=/^(?:(?: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])$/,NY=/^(?:(?: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])$/,MY=/^(([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]))$/,jY=/^(([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])$/,LY=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,DY=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yP="((\\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])))",UY=new RegExp(`^${yP}$`);function wP(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function zY(n){return new RegExp(`^${wP(n)}$`)}function FY(n){let e=`${yP}T${wP(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function BY(n,e){return!!((e==="v4"||!e)&&PY.test(n)||(e==="v6"||!e)&&MY.test(n))}function HY(n,e){if(!OY.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.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 VY(n,e){return!!((e==="v4"||!e)&&NY.test(n)||(e==="v6"||!e)&&jY.test(n))}class Ai extends it{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==be.string){const i=this._getOrReturnCtx(e);return le(i,{code:J.invalid_type,expected:be.string,received:i.parsedType}),Le}const r=new mr;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),le(s,{code:J.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),le(s,{code:J.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?le(s,{code:J.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&le(s,{code:J.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")$Y.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"email",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")fg||(fg=new RegExp(RY,"u")),fg.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"emoji",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")IY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"uuid",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")xY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"nanoid",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")TY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"cuid",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")EY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"cuid2",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")kY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"ulid",code:J.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),le(s,{validation:"url",code:J.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),le(s,{validation:"regex",code:J.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),le(s,{code:J.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),le(s,{code:J.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),le(s,{code:J.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?FY(i).test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{code:J.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?UY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{code:J.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?zY(i).test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{code:J.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?CY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"duration",code:J.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?BY(e.data,i.version)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"ip",code:J.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?HY(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"jwt",code:J.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?VY(e.data,i.version)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"cidr",code:J.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?LY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"base64",code:J.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?DY.test(e.data)||(s=this._getOrReturnCtx(e,s),le(s,{validation:"base64url",code:J.invalid_string,message:i.message}),r.dirty()):ot.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:J.invalid_string,...Se.errToObj(r)})}_addCheck(e){return new Ai({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Se.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,...Se.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,...Se.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Se.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Se.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...Se.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Se.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Se.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Se.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Se.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Se.errToObj(t)})}nonempty(e){return this.min(1,Se.errToObj(e))}trim(){return new Ai({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ai({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ai({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Ai.create=n=>new Ai({checks:[],typeName:De.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...qe(n)});function ZY(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class gc extends it{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)!==be.number){const i=this._getOrReturnCtx(e);return le(i,{code:J.invalid_type,expected:be.number,received:i.parsedType}),Le}let r;const s=new mr;for(const i of this._def.checks)i.kind==="int"?ot.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),le(r,{code:J.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),le(r,{code:J.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),le(r,{code:J.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ZY(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),le(r,{code:J.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),le(r,{code:J.not_finite,message:i.message}),s.dirty()):ot.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Se.toString(t))}setLimit(e,t,r,s){return new gc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Se.toString(s)}]})}_addCheck(e){return new gc({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Se.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ot.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}gc.create=n=>new gc({checks:[],typeName:De.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...qe(n)});class pl extends it{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)!==be.bigint)return this._getInvalidInput(e);let r;const s=new mr;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),le(r,{code:J.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),le(r,{code:J.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),le(r,{code:J.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ot.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return le(t,{code:J.invalid_type,expected:be.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,Se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Se.toString(t))}setLimit(e,t,r,s){return new pl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Se.toString(s)}]})}_addCheck(e){return new pl({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}pl.create=n=>new pl({checks:[],typeName:De.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...qe(n)});class fy extends it{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==be.boolean){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:be.boolean,received:r.parsedType}),Le}return Rr(e.data)}}fy.create=n=>new fy({typeName:De.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...qe(n)});class Rf extends it{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==be.date){const i=this._getOrReturnCtx(e);return le(i,{code:J.invalid_type,expected:be.date,received:i.parsedType}),Le}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return le(i,{code:J.invalid_date}),Le}const r=new mr;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),le(s,{code:J.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),le(s,{code:J.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ot.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Rf({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Se.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Se.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Rf.create=n=>new Rf({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:De.ZodDate,...qe(n)});class ET extends it{_parse(e){if(this._getType(e)!==be.symbol){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:be.symbol,received:r.parsedType}),Le}return Rr(e.data)}}ET.create=n=>new ET({typeName:De.ZodSymbol,...qe(n)});class kT extends it{_parse(e){if(this._getType(e)!==be.undefined){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:be.undefined,received:r.parsedType}),Le}return Rr(e.data)}}kT.create=n=>new kT({typeName:De.ZodUndefined,...qe(n)});class IT extends it{_parse(e){if(this._getType(e)!==be.null){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:be.null,received:r.parsedType}),Le}return Rr(e.data)}}IT.create=n=>new IT({typeName:De.ZodNull,...qe(n)});class xT extends it{constructor(){super(...arguments),this._any=!0}_parse(e){return Rr(e.data)}}xT.create=n=>new xT({typeName:De.ZodAny,...qe(n)});class OT extends it{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Rr(e.data)}}OT.create=n=>new OT({typeName:De.ZodUnknown,...qe(n)});class Fi extends it{_parse(e){const t=this._getOrReturnCtx(e);return le(t,{code:J.invalid_type,expected:be.never,received:t.parsedType}),Le}}Fi.create=n=>new Fi({typeName:De.ZodNever,...qe(n)});class CT extends it{_parse(e){if(this._getType(e)!==be.undefined){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:be.void,received:r.parsedType}),Le}return Rr(e.data)}}CT.create=n=>new CT({typeName:De.ZodVoid,...qe(n)});class Ss extends it{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==be.array)return le(t,{code:J.invalid_type,expected:be.array,received:t.parsedType}),Le;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(le(t,{code:a?J.too_big:J.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&&t.data.length<s.minLength.value&&(le(t,{code:J.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(le(t,{code:J.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new zi(t,a,t.path,o)))).then(a=>mr.mergeArray(r,a));const i=[...t.data].map((a,o)=>s.type._parseSync(new zi(t,a,t.path,o)));return mr.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new Ss({...this._def,minLength:{value:e,message:Se.toString(t)}})}max(e,t){return new Ss({...this._def,maxLength:{value:e,message:Se.toString(t)}})}length(e,t){return new Ss({...this._def,exactLength:{value:e,message:Se.toString(t)}})}nonempty(e){return this.min(1,e)}}Ss.create=(n,e)=>new Ss({type:n,minLength:null,maxLength:null,exactLength:null,typeName:De.ZodArray,...qe(e)});function mo(n){if(n instanceof zt){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=Ri.create(mo(r))}return new zt({...n._def,shape:()=>e})}else return n instanceof Ss?new Ss({...n._def,type:mo(n.element)}):n instanceof Ri?Ri.create(mo(n.unwrap())):n instanceof wc?wc.create(mo(n.unwrap())):n instanceof La?La.create(n.items.map(e=>mo(e))):n}class zt extends it{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(),t=ot.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==be.object){const u=this._getOrReturnCtx(e);return le(u,{code:J.invalid_type,expected:be.object,received:u.parsedType}),Le}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Fi&&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 zi(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Fi){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&&(le(s,{code:J.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 zi(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=>mr.mergeObjectSync(r,u)):mr.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Se.errToObj,new zt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var i,a;const s=((a=(i=this._def).errorMap)==null?void 0:a.call(i,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:Se.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new zt({...this._def,unknownKeys:"strip"})}passthrough(){return new zt({...this._def,unknownKeys:"passthrough"})}extend(e){return new zt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new zt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:De.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new zt({...this._def,catchall:e})}pick(e){const t={};for(const r of ot.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new zt({...this._def,shape:()=>t})}omit(e){const t={};for(const r of ot.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new zt({...this._def,shape:()=>t})}deepPartial(){return mo(this)}partial(e){const t={};for(const r of ot.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new zt({...this._def,shape:()=>t})}required(e){const t={};for(const r of ot.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ri;)i=i._def.innerType;t[r]=i}return new zt({...this._def,shape:()=>t})}keyof(){return bP(ot.objectKeys(this.shape))}}zt.create=(n,e)=>new zt({shape:()=>n,unknownKeys:"strip",catchall:Fi.create(),typeName:De.ZodObject,...qe(e)});zt.strictCreate=(n,e)=>new zt({shape:()=>n,unknownKeys:"strict",catchall:Fi.create(),typeName:De.ZodObject,...qe(e)});zt.lazycreate=(n,e)=>new zt({shape:n,unknownKeys:"strip",catchall:Fi.create(),typeName:De.ZodObject,...qe(e)});class Pf extends it{_parse(e){const{ctx:t}=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 t.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new Xs(o.ctx.common.issues));return le(t,{code:J.invalid_union,unionErrors:a}),Le}if(t.common.async)return Promise.all(r.map(async i=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of r){const u={...t,common:{...t.common,issues:[]},parent:null},l=c._parseSync({data:t.data,path:t.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 t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new Xs(c));return le(t,{code:J.invalid_union,unionErrors:o}),Le}}get options(){return this._def.options}}Pf.create=(n,e)=>new Pf({options:n,typeName:De.ZodUnion,...qe(e)});function py(n,e){const t=pi(n),r=pi(e);if(n===e)return{valid:!0,data:n};if(t===be.object&&r===be.object){const s=ot.objectKeys(e),i=ot.objectKeys(n).filter(o=>s.indexOf(o)!==-1),a={...n,...e};for(const o of i){const c=py(n[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===be.array&&r===be.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<n.length;i++){const a=n[i],o=e[i],c=py(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===be.date&&r===be.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Nf extends it{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(ST(i)||ST(a))return Le;const o=py(i.value,a.value);return o.valid?((AT(i)||AT(a))&&t.dirty(),{status:t.value,value:o.data}):(le(r,{code:J.invalid_intersection_types}),Le)};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}))}}Nf.create=(n,e,t)=>new Nf({left:n,right:e,typeName:De.ZodIntersection,...qe(t)});class La extends it{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.array)return le(r,{code:J.invalid_type,expected:be.array,received:r.parsedType}),Le;if(r.data.length<this._def.items.length)return le(r,{code:J.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;!this._def.rest&&r.data.length>this._def.items.length&&(le(r,{code:J.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...r.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new zi(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>mr.mergeArray(t,a)):mr.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new La({...this._def,rest:e})}}La.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new La({items:n,typeName:De.ZodTuple,rest:null,...qe(e)})};class $T extends it{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.map)return le(r,{code:J.invalid_type,expected:be.map,received:r.parsedType}),Le;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,c],u)=>({key:s._parse(new zi(r,o,r.path,[u,"key"])),value:i._parse(new zi(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 Le;(u.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(u.value,l.value)}return{status:t.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 Le;(u.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(u.value,l.value)}return{status:t.value,value:o}}}}$T.create=(n,e,t)=>new $T({valueType:e,keyType:n,typeName:De.ZodMap,...qe(t)});class ml extends it{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==be.set)return le(r,{code:J.invalid_type,expected:be.set,received:r.parsedType}),Le;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(le(r,{code:J.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(le(r,{code:J.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const l of c){if(l.status==="aborted")return Le;l.status==="dirty"&&t.dirty(),u.add(l.value)}return{status:t.value,value:u}}const o=[...r.data.values()].map((c,u)=>i._parse(new zi(r,c,r.path,u)));return r.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new ml({...this._def,minSize:{value:e,message:Se.toString(t)}})}max(e,t){return new ml({...this._def,maxSize:{value:e,message:Se.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ml.create=(n,e)=>new ml({valueType:n,minSize:null,maxSize:null,typeName:De.ZodSet,...qe(e)});class RT extends it{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}RT.create=(n,e)=>new RT({getter:n,typeName:De.ZodLazy,...qe(e)});class PT extends it{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return le(t,{received:t.data,code:J.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}}PT.create=(n,e)=>new PT({value:n,typeName:De.ZodLiteral,...qe(e)});function bP(n,e){return new _c({values:n,typeName:De.ZodEnum,...qe(e)})}class _c extends it{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return le(t,{expected:ot.joinValues(r),received:t.parsedType,code:J.invalid_type}),Le}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return le(t,{received:t.data,code:J.invalid_enum_value,options:r}),Le}return Rr(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return _c.create(e,{...this._def,...t})}exclude(e,t=this._def){return _c.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}_c.create=bP;class NT extends it{_parse(e){const t=ot.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==be.string&&r.parsedType!==be.number){const s=ot.objectValues(t);return le(r,{expected:ot.joinValues(s),received:r.parsedType,code:J.invalid_type}),Le}if(this._cache||(this._cache=new Set(ot.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=ot.objectValues(t);return le(r,{received:r.data,code:J.invalid_enum_value,options:s}),Le}return Rr(e.data)}get enum(){return this._def.values}}NT.create=(n,e)=>new NT({values:n,typeName:De.ZodNativeEnum,...qe(e)});class Mf extends it{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==be.promise&&t.common.async===!1)return le(t,{code:J.invalid_type,expected:be.promise,received:t.parsedType}),Le;const r=t.parsedType===be.promise?t.data:Promise.resolve(t.data);return Rr(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Mf.create=(n,e)=>new Mf({type:n,typeName:De.ZodPromise,...qe(e)});class yc extends it{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===De.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{le(r,a),a.fatal?t.abort():t.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(t.value==="aborted")return Le;const c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?Le:c.status==="dirty"||t.value==="dirty"?Tu(c.value):c});{if(t.value==="aborted")return Le;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?Le:o.status==="dirty"||t.value==="dirty"?Tu(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"?Le:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?Le:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.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(!mc(a))return Le;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:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>mc(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:t.value,value:o})):Le);ot.assertNever(s)}}yc.create=(n,e,t)=>new yc({schema:n,typeName:De.ZodEffects,effect:e,...qe(t)});yc.createWithPreprocess=(n,e,t)=>new yc({schema:e,effect:{type:"preprocess",transform:n},typeName:De.ZodEffects,...qe(t)});class Ri extends it{_parse(e){return this._getType(e)===be.undefined?Rr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ri.create=(n,e)=>new Ri({innerType:n,typeName:De.ZodOptional,...qe(e)});class wc extends it{_parse(e){return this._getType(e)===be.null?Rr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}wc.create=(n,e)=>new wc({innerType:n,typeName:De.ZodNullable,...qe(e)});class my extends it{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}my.create=(n,e)=>new my({innerType:n,typeName:De.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...qe(e)});class gy extends it{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return $f(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Xs(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Xs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}gy.create=(n,e)=>new gy({innerType:n,typeName:De.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...qe(e)});class MT extends it{_parse(e){if(this._getType(e)!==be.nan){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:be.nan,received:r.parsedType}),Le}return{status:"valid",value:e.data}}}MT.create=n=>new MT({typeName:De.ZodNaN,...qe(n)});class KY extends it{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Zb extends it{_parse(e){const{status:t,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"?Le:i.status==="dirty"?(t.dirty(),Tu(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"?Le:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new Zb({in:e,out:t,typeName:De.ZodPipeline})}}class _y extends it{_parse(e){const t=this._def.innerType._parse(e),r=s=>(mc(s)&&(s.value=Object.freeze(s.value)),s);return $f(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}}_y.create=(n,e)=>new _y({innerType:n,typeName:De.ZodReadonly,...qe(e)});var De;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(De||(De={}));const Ps=Ai.create,Yd=gc.create,pg=fy.create;Fi.create;const WY=Ss.create,Yi=zt.create;Pf.create;Nf.create;La.create;const jT=_c.create;Mf.create;Ri.create;wc.create;const qY=n=>$P.includes(n),GY=n=>JT.includes(n),JY=n=>{const{executeQuery:e,search:t,grep:r,readFile:s,fetchFeatureClusters:i,fetchFeatureClusterDetail:a}=n,o=li(async({query:m,limit:g,groupByProcess:y})=>{const b=g??10,_=y??!0;let w;try{w=await t(m,{limit:b,enrich:!0})}catch{return"Search is not available. Please load a repository first."}if(w.length===0)return`No code found matching "${m}". Try different terms or use grep for exact patterns.`;const S=w.slice(0,b).map((x,O)=>{var X,ie;const U=x.nodeId||"",B=x.name||((X=x.filePath)==null?void 0:X.split("/").pop())||"Unknown",F=x.label||"File",Y=x.filePath||"",Z=x.startLine?` (lines ${x.startLine}-${x.endLine})`:"",ge=((ie=x.sources)==null?void 0:ie.join("+"))||"hybrid",M=x.score?` [score: ${x.score.toFixed(2)}]`:"";let K="";if(x.connections){const Ee=(x.connections.outgoing||[]).filter(C=>C==null?void 0:C.name).slice(0,3),de=(x.connections.incoming||[]).filter(C=>C==null?void 0:C.name).slice(0,3),E=(C,_e)=>{const xe=C.confidence?Math.round(C.confidence*100):100;return _e==="out"?`-[${C.type} ${xe}%]-> ${C.name}`:`<-[${C.type} ${xe}%]- ${C.name}`},v=Ee.map(C=>E(C,"out")),j=de.map(C=>E(C,"in"));(v.length||j.length)&&(K=`
|
|
652
|
+
Connections: ${[...v,...j].join(", ")}`)}const se=x.cluster||"Unclustered",oe=(x.processes||[]).filter(Ee=>Ee.id&&Ee.label);return{idx:O+1,nodeId:U,name:B,label:F,filePath:Y,location:Z,sources:ge,score:M,connections:K,clusterLabel:se,processes:oe}}),T=(x,O)=>{const U=O!=null&&O.step?` (step ${O.step}/${O.stepCount??"?"})`:"";return`[${x.idx}] ${x.label}: ${x.name}${x.score}${U}
|
|
653
|
+
ID: ${x.nodeId}
|
|
654
|
+
File: ${x.filePath}${x.location}
|
|
655
|
+
Cluster: ${x.clusterLabel}
|
|
656
|
+
Found by: ${x.sources}${x.connections}`};if(!_)return`Found ${w.length} matches:
|
|
657
|
+
|
|
658
|
+
${S.map(x=>T(x)).join(`
|
|
659
|
+
|
|
660
|
+
`)}`;const A=new Map,I="__no_process__";for(const x of S){if(x.processes.length===0){A.has(I)||A.set(I,{label:"No process",entries:[]}),A.get(I).entries.push({result:x});continue}for(const O of x.processes)A.has(O.id)||A.set(O.id,{label:O.label,stepCount:O.stepCount,entries:[]}),A.get(O.id).entries.push({result:x,step:O.step,stepCount:O.stepCount})}const k=Array.from(A.entries()).sort((x,O)=>{const U=x[1].entries.length;return O[1].entries.length-U}),R=[];R.push(`Found ${w.length} matches grouped by process:`),R.push("");for(const[x,O]of k){const U=O.stepCount?`, ${O.stepCount} steps`:"",B=x===I?`NO PROCESS (${O.entries.length} matches)`:`PROCESS: ${O.label} (${O.entries.length} matches${U})`;R.push(B),O.entries.forEach(F=>{const Y=F.step?{id:x,label:O.label,step:F.step,stepCount:F.stepCount}:void 0;R.push(T(F.result,Y))}),R.push("")}return R.join(`
|
|
661
|
+
`).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:Yi({query:Ps().describe('What you are looking for (e.g., "authentication middleware", "database connection")'),groupByProcess:pg().optional().nullable().describe("Group results by process (default: true)"),limit:Yd().optional().nullable().describe("Max results to return (default: 10)")})}),c=li(async({query:m,cypher:g})=>{try{if(g.includes("{{QUERY_VECTOR}}")){if(!m)return"Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.";try{const T=await t(m,{limit:10,mode:"semantic"});if(T.length===0)return"Semantic search returned no results. Embeddings may not be generated yet.";const A=T.map((I,k)=>{var R;return`[${k+1}] ${I.label||"File"}: ${I.name||((R=I.filePath)==null?void 0:R.split("/").pop())||"?"} (score: ${(I.score??0).toFixed(3)})
|
|
662
|
+
File: ${I.filePath||"n/a"}`}).join(`
|
|
663
|
+
`);return`Semantic search for "${m}" (${T.length} results):
|
|
664
|
+
|
|
665
|
+
${A}`}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 T=`| ${_.join(" | ")} |`,A=`|${_.map(()=>"---").join("|")}|`,I=y.slice(0,50).map(R=>`| ${_.map(O=>{const U=R[O];if(U==null)return"";if(typeof U=="object")return JSON.stringify(U);const B=String(U).replace(/\|/g,"\\|");return B.length>60?B.slice(0,57)+"...":B}).join(" | ")} |`).join(`
|
|
666
|
+
`),k=y.length>50?`
|
|
667
|
+
|
|
668
|
+
_(${y.length-50} more rows)_`:"";return`**${y.length} results:**
|
|
669
|
+
|
|
670
|
+
${T}
|
|
671
|
+
${A}
|
|
672
|
+
${I}${k}`}const w=y.slice(0,50).map((T,A)=>`[${A+1}] ${JSON.stringify(T)}`),S=y.length>50?`
|
|
673
|
+
... (${y.length-50} more)`:"";return`${y.length} results:
|
|
674
|
+
${w.join(`
|
|
675
|
+
`)}${S}`}catch(y){return`Cypher error: ${y instanceof Error?y.message:String(y)}
|
|
676
|
+
|
|
677
|
+
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.
|
|
678
|
+
|
|
679
|
+
Node tables: File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process, FeatureCluster, Route, Tool, Section
|
|
680
|
+
Relation: CodeRelation (single table with 'type' property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON)
|
|
681
|
+
|
|
682
|
+
Example queries:
|
|
683
|
+
- Functions calling a function: MATCH (caller:Function)-[:CodeRelation {type: 'CALLS'}]->(fn:Function {name: 'validate'}) RETURN caller.name, caller.filePath
|
|
684
|
+
- Feature members: MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {name: 'Settings'}) RETURN m.name, m.filePath, m.startLine
|
|
685
|
+
- Feature dependencies: MATCH (a:FeatureCluster)-[:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(b:FeatureCluster) RETURN a.name, b.name
|
|
686
|
+
- Class inheritance: MATCH (child:Class)-[:CodeRelation {type: 'EXTENDS'}]->(parent:Class) RETURN child.name, parent.name
|
|
687
|
+
- Classes implementing interface: MATCH (c:Class)-[:CodeRelation {type: 'IMPLEMENTS'}]->(i:Interface) RETURN c.name, i.name
|
|
688
|
+
- Files importing a file: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(target:File) WHERE target.name = 'utils.ts' RETURN f.name
|
|
689
|
+
- 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
|
|
690
|
+
- Find fuzzy matches: MATCH (n)-[r:CodeRelation]-(m) WHERE r.confidence < 0.8 RETURN n.name, r.reason
|
|
691
|
+
|
|
692
|
+
For semantic+graph queries, include {{QUERY_VECTOR}} placeholder and provide a 'query' parameter:
|
|
693
|
+
CALL QUERY_VECTOR_INDEX('CodeEmbedding', 'code_embedding_idx', {{QUERY_VECTOR}}, 10) YIELD node AS emb, distance
|
|
694
|
+
WITH emb, distance WHERE distance < 0.5
|
|
695
|
+
MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:Yi({cypher:Ps().describe("The Cypher query to execute"),query:Ps().optional().nullable().describe("Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})")})}),u=li(async({pattern:m,fileFilter:g,caseSensitive:y,maxResults:b})=>{try{try{new RegExp(m,y?"g":"gi")}catch(I){return`Invalid regex: ${m}. Error: ${I instanceof Error?I.message:String(I)}`}const _=b??100,w=g?`(?=.*${g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).*${m}`:m,S=await r(w,_);if(S.length===0)return`No matches for "${m}"${g?` in files matching "${g}"`:""}`;const T=S.map(I=>`${I.filePath}:${I.line}: ${I.text}`).join(`
|
|
696
|
+
`),A=S.length>=_?`
|
|
697
|
+
|
|
698
|
+
(Showing first ${_} results)`:"";return`Found ${S.length} matches:
|
|
699
|
+
|
|
700
|
+
${T}${A}`}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:Yi({pattern:Ps().describe('Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")'),fileFilter:Ps().optional().nullable().describe('Only search files containing this string (e.g., ".ts", "src/api")'),caseSensitive:pg().optional().nullable().describe("Case-sensitive search (default: false)"),maxResults:Yd().optional().nullable().describe("Max results (default: 100)")})}),l=li(async({filePath:m})=>{try{const g=await s(m),y=5e4;if(g.length>y){const _=g.split(`
|
|
701
|
+
`).length;return`File: ${m} (${_} lines, truncated)
|
|
702
|
+
|
|
703
|
+
${g.slice(0,y)}
|
|
704
|
+
|
|
705
|
+
... [truncated]`}const b=g.split(`
|
|
706
|
+
`).length;return`File: ${m} (${b} lines)
|
|
707
|
+
|
|
708
|
+
${g}`}catch(g){const y=g instanceof Error?g.message:String(g);return y.includes("not found")||y.includes("404")?`File not found: "${m}". Use grep to search for the correct path.`:`Error reading file: ${y}`}},{name:"read",description:"Read the full content of a file. Use to see source code after finding files via search or grep.",schema:Yi({filePath:Ps().describe('File path to read (can be partial like "src/utils.ts")')})}),d=li(async()=>{try{const m=`
|
|
709
|
+
MATCH (f:FeatureCluster)
|
|
710
|
+
RETURN f.id AS id, f.name AS name, f.slug AS slug, f.featureKind AS featureKind,
|
|
711
|
+
f.description AS description, f.signals AS signals, f.memberCount AS memberCount,
|
|
712
|
+
f.confidence AS confidence
|
|
713
|
+
ORDER BY f.memberCount DESC
|
|
714
|
+
LIMIT 200
|
|
715
|
+
`,g=`
|
|
716
|
+
MATCH (c:Community)
|
|
717
|
+
RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
|
|
718
|
+
ORDER BY c.symbolCount DESC
|
|
719
|
+
LIMIT 200
|
|
720
|
+
`,y=`
|
|
721
|
+
MATCH (p:Process)
|
|
722
|
+
RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount, p.communities AS communities
|
|
723
|
+
ORDER BY p.stepCount DESC
|
|
724
|
+
LIMIT 200
|
|
725
|
+
`,b=`
|
|
726
|
+
MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b)
|
|
727
|
+
MATCH (a)-[:CodeRelation {type: 'MEMBER_OF'}]->(c1:Community)
|
|
728
|
+
MATCH (b)-[:CodeRelation {type: 'MEMBER_OF'}]->(c2:Community)
|
|
729
|
+
WHERE c1.id <> c2.id
|
|
730
|
+
RETURN c1.label AS \`from\`, c2.label AS \`to\`, COUNT(*) AS calls
|
|
731
|
+
ORDER BY calls DESC
|
|
732
|
+
LIMIT 15
|
|
733
|
+
`,_=`
|
|
734
|
+
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
735
|
+
RETURN p.label AS label, COUNT(r) AS steps
|
|
736
|
+
ORDER BY steps DESC
|
|
737
|
+
LIMIT 10
|
|
738
|
+
`,w=`
|
|
739
|
+
MATCH (a:FeatureCluster)-[:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(b:FeatureCluster)
|
|
740
|
+
RETURN a.name AS \`from\`, b.name AS \`to\`, COUNT(*) AS edges
|
|
741
|
+
ORDER BY edges DESC
|
|
742
|
+
LIMIT 15
|
|
743
|
+
`,S=i?i().catch(()=>({clusters:[]})):e(m).then(M=>({clusters:M.map(K=>({id:Array.isArray(K)?K[0]:K.id,name:Array.isArray(K)?K[1]:K.name,slug:Array.isArray(K)?K[2]:K.slug,featureKind:Array.isArray(K)?K[3]:K.featureKind,description:Array.isArray(K)?K[4]:K.description,signals:Array.isArray(K)?K[5]:K.signals,memberCount:Array.isArray(K)?K[6]:K.memberCount,confidence:Array.isArray(K)?K[7]:K.confidence}))})),[T,A,I,k,R,x]=await Promise.all([S,e(g),e(y),e(b),e(_),e(w)]),O=Array.isArray(T.clusters)?T.clusters:[],U=O.map(M=>{const K=M.confidence!==null&&M.confidence!==void 0?Number(M.confidence).toFixed(2):"";return`| ${M.name||M.slug||M.id||""} | ${M.featureKind||""} | ${M.memberCount??""} | ${K} | ${M.description??""} |`}),B=x.map(M=>{const K=Array.isArray(M)?M[0]:M.from,se=Array.isArray(M)?M[1]:M.to,oe=Array.isArray(M)?M[2]:M.edges;return`- ${K} -> ${se} (${oe} edges)`}),F=A.map(M=>{const K=Array.isArray(M)?M[1]:M.label,se=Array.isArray(M)?M[3]:M.symbolCount,oe=Array.isArray(M)?M[2]:M.cohesion,X=Array.isArray(M)?M[4]:M.description,ie=oe!=null?Number(oe).toFixed(2):"";return`| ${K||""} | ${se??""} | ${ie} | ${X??""} |`}),Y=I.map(M=>{const K=Array.isArray(M)?M[1]:M.label,se=Array.isArray(M)?M[3]:M.stepCount,oe=Array.isArray(M)?M[2]:M.type,X=Array.isArray(M)?M[4]:M.communities,ie=Array.isArray(X)?X.length:X?1:0;return`| ${K||""} | ${se??""} | ${oe??""} | ${ie} |`}),Z=k.map(M=>{const K=Array.isArray(M)?M[0]:M.from,se=Array.isArray(M)?M[1]:M.to,oe=Array.isArray(M)?M[2]:M.calls;return`- ${K} -> ${se} (${oe} calls)`}),ge=R.map(M=>{const K=Array.isArray(M)?M[0]:M.label,se=Array.isArray(M)?M[1]:M.steps;return`- ${K} (${se} steps)`});return[`FEATURE CLUSTERS (${O.length} total):`,"| Feature | Kind | Members | Confidence | Description |","| --- | --- | --- | --- | --- |",...U,"",`CLUSTERS (${A.length} total):`,"| Cluster | Symbols | Cohesion | Description |","| --- | --- | --- | --- |",...F,"",`PROCESSES (${I.length} total):`,"| Process | Steps | Type | Clusters |","| --- | --- | --- | --- |",...Y,"","CLUSTER DEPENDENCIES:",...Z.length>0?Z:["- None found"],"","FEATURE DEPENDENCIES:",...B.length>0?B:["- None found"],"","CRITICAL PATHS:",...ge.length>0?ge:["- None found"]].join(`
|
|
744
|
+
`)}catch(m){return`Overview error: ${m instanceof Error?m.message:String(m)}`}},{name:"overview",description:"Codebase map showing feature clusters, structural clusters, processes, and dependencies.",schema:Yi({})}),f=li(async({target:m,type:g})=>{var k,R;const y=m.replace(/'/g,"''");let b=g??null,_=null,w=null,S=null,T=null;const A=(x,O,U)=>Array.isArray(x)?x[O]:x[U],I=x=>(x==null?void 0:x.name)||(x==null?void 0:x.slug)||(x==null?void 0:x.id)||"Unknown feature";if(!b||b==="process"){const x=`
|
|
745
|
+
MATCH (p:Process)
|
|
746
|
+
WHERE p.id = '${y}' OR p.label = '${y}'
|
|
747
|
+
RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount
|
|
748
|
+
LIMIT 1
|
|
749
|
+
`,O=await e(x);O.length>0&&(_=O[0],b="process")}if(!b||b==="feature"){const x=`
|
|
750
|
+
MATCH (f:FeatureCluster)
|
|
751
|
+
WHERE f.id = '${y}' OR f.name = '${y}' OR f.slug = '${y}'
|
|
752
|
+
RETURN f.id AS id, f.name AS name, f.slug AS slug, f.featureKind AS featureKind,
|
|
753
|
+
f.description AS description, f.memberCount AS memberCount, f.confidence AS confidence,
|
|
754
|
+
f.signals AS signals
|
|
755
|
+
LIMIT 1
|
|
756
|
+
`,O=await e(x);O.length>0&&(w=O[0],b="feature")}if(!b||b==="cluster"){const x=`
|
|
757
|
+
MATCH (c:Community)
|
|
758
|
+
WHERE c.id = '${y}' OR c.label = '${y}' OR c.heuristicLabel = '${y}'
|
|
759
|
+
RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
|
|
760
|
+
LIMIT 1
|
|
761
|
+
`,O=await e(x);O.length>0&&(S=O[0],b="cluster")}if(!b||b==="symbol"){const x=`
|
|
762
|
+
MATCH (n)
|
|
763
|
+
WHERE n.name = '${y}' OR n.id = '${y}' OR n.filePath = '${y}'
|
|
764
|
+
RETURN n.id AS id, n.name AS name, n.filePath AS filePath, label(n) AS nodeType
|
|
765
|
+
LIMIT 5
|
|
766
|
+
`,O=await e(x);O.length>0&&(T=O[0],b="symbol")}if(!b)return`Could not find "${m}" as a symbol, feature cluster, structural cluster, or process. Try search first.`;if(b==="process"){const x=A(_,0,"id"),O=A(_,1,"label"),U=A(_,2,"type"),B=A(_,3,"stepCount"),F=`
|
|
767
|
+
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${x.replace(/'/g,"''")}'})
|
|
768
|
+
RETURN s.name AS name, s.filePath AS filePath, r.step AS step
|
|
769
|
+
ORDER BY r.step
|
|
770
|
+
`,Y=`
|
|
771
|
+
MATCH (c:Community)<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
|
|
772
|
+
MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${x.replace(/'/g,"''")}'})
|
|
773
|
+
RETURN DISTINCT c.id AS id, c.label AS label, c.description AS description
|
|
774
|
+
ORDER BY c.label
|
|
775
|
+
LIMIT 20
|
|
776
|
+
`,[Z,ge]=await Promise.all([e(F),e(Y)]),M=Z.map(se=>{const oe=A(se,0,"name"),X=A(se,1,"filePath");return`- ${A(se,2,"step")}. ${oe} (${X||"n/a"})`}),K=ge.map(se=>{const oe=A(se,1,"label"),X=A(se,2,"description");return`- ${oe}${X?` — ${X}`:""}`});return[`PROCESS: ${O}`,`Type: ${U||"n/a"}`,`Steps: ${B??Z.length}`,"","STEPS:",...M.length>0?M:["- None found"],"","CLUSTERS TOUCHED:",...K.length>0?K:["- None found"]].join(`
|
|
777
|
+
`)}if(b==="feature"){const x=A(w,0,"id"),O=A(w,1,"name"),U=A(w,2,"slug"),B=A(w,3,"featureKind"),F=A(w,4,"description"),Y=A(w,5,"memberCount"),Z=A(w,6,"confidence"),ge=A(w,7,"signals");let M=null;if(a)try{const L=await a(String(O||U||x));!L.error&&L.cluster&&(M=L)}catch{M=null}const K=`
|
|
778
|
+
MATCH (m)-[r:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {id: '${String(x).replace(/'/g,"''")}'})
|
|
779
|
+
RETURN m.id AS id, m.name AS name, label(m) AS type, m.filePath AS filePath,
|
|
780
|
+
m.startLine AS startLine, m.endLine AS endLine, r.confidence AS confidence,
|
|
781
|
+
r.reason AS reason
|
|
782
|
+
ORDER BY type, filePath, startLine
|
|
783
|
+
LIMIT 80
|
|
784
|
+
`,se=`
|
|
785
|
+
MATCH (f:FeatureCluster {id: '${String(x).replace(/'/g,"''")}'})-[r:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(d:FeatureCluster)
|
|
786
|
+
RETURN d.id AS id, d.name AS name, d.slug AS slug, r.confidence AS confidence
|
|
787
|
+
ORDER BY d.name
|
|
788
|
+
`,oe=`
|
|
789
|
+
MATCH (s:FeatureCluster)-[r:CodeRelation {type: 'FEATURE_DEPENDS_ON'}]->(f:FeatureCluster {id: '${String(x).replace(/'/g,"''")}'})
|
|
790
|
+
RETURN s.id AS id, s.name AS name, s.slug AS slug, r.confidence AS confidence
|
|
791
|
+
ORDER BY s.name
|
|
792
|
+
`,X=`
|
|
793
|
+
MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {id: '${String(x).replace(/'/g,"''")}'}),
|
|
794
|
+
(m)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
795
|
+
RETURN DISTINCT p.id AS id, p.label AS label, p.processType AS processType, p.stepCount AS stepCount
|
|
796
|
+
ORDER BY p.stepCount DESC
|
|
797
|
+
LIMIT 20
|
|
798
|
+
`,[ie,Ee,de,E]=M?[[],[],[],[]]:await Promise.all([e(K),e(se),e(oe),e(X)]),v=M==null?void 0:M.dependencies,j=Array.isArray(v)?[]:(v==null?void 0:v.outgoing)??[],C=Array.isArray(v)?[]:(v==null?void 0:v.incoming)??[],_e=((k=M==null?void 0:M.members)==null?void 0:k.map(L=>({name:L.name||L.id||L.nodeId||"Unknown",type:L.type||L.label||"Node",filePath:L.filePath||"n/a",startLine:L.startLine,endLine:L.endLine,confidence:L.confidence})))??ie.map(L=>({name:A(L,1,"name")||A(L,0,"id"),type:A(L,2,"type"),filePath:A(L,3,"filePath")||"n/a",startLine:A(L,4,"startLine"),endLine:A(L,5,"endLine"),confidence:A(L,6,"confidence")})),xe=_e.map(L=>{const vn=L.startLine?`:${L.startLine}${L.endLine?`-${L.endLine}`:""}`:"",ke=L.confidence!==null&&L.confidence!==void 0?` (${Math.round(Number(L.confidence)*100)}%)`:"";return`- ${L.type}: ${L.name} (${L.filePath}${vn})${ke}`}),dt=j.length>0?j:Ee.map(L=>({id:A(L,0,"id"),name:A(L,1,"name"),slug:A(L,2,"slug"),confidence:A(L,3,"confidence")})),Qe=C.length>0?C:de.map(L=>({id:A(L,0,"id"),name:A(L,1,"name"),slug:A(L,2,"slug"),confidence:A(L,3,"confidence")})),yt=dt.map(L=>`- ${I(L)}`),Ot=Qe.map(L=>`- ${I(L)}`),Dt=((M==null?void 0:M.processes)??E.map(L=>({id:A(L,0,"id"),label:A(L,1,"label"),heuristicLabel:void 0,processType:A(L,2,"processType"),stepCount:A(L,3,"stepCount")}))).map(L=>`- ${L.label||L.heuristicLabel||L.id||"Unknown process"} (${L.stepCount??"?"} steps)`),bn=Z!=null?Number(Z).toFixed(2):"n/a",yr=Array.isArray(ge)?ge.slice(0,8).join(", "):"";return[`FEATURE: ${O||U||x}`,`Kind: ${B||"feature"}`,`Members: ${Y??_e.length}`,`Confidence: ${bn}`,`Description: ${F||((R=M==null?void 0:M.cluster)==null?void 0:R.description)||"n/a"}`,yr?`Signals: ${yr}`:"","","TOP MEMBERS:",...xe.length>0?xe:["- None found"],"","DEPENDS ON:",...yt.length>0?yt:["- None found"],"","USED BY:",...Ot.length>0?Ot:["- None found"],"","PROCESSES TOUCHING THIS FEATURE:",...Dt.length>0?Dt:["- None found"]].filter((L,vn,ke)=>L!==""||ke[vn-1]!=="").join(`
|
|
799
|
+
`)}if(b==="cluster"){const x=A(S,0,"id"),O=A(S,1,"label"),U=A(S,2,"cohesion"),B=A(S,3,"symbolCount"),F=A(S,4,"description"),Y=`
|
|
800
|
+
MATCH (c:Community {id: '${x.replace(/'/g,"''")}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(m)
|
|
801
|
+
RETURN m.name AS name, m.filePath AS filePath, label(m) AS nodeType
|
|
802
|
+
LIMIT 50
|
|
803
|
+
`,Z=`
|
|
804
|
+
MATCH (c:Community {id: '${x.replace(/'/g,"''")}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(s)
|
|
805
|
+
MATCH (s)-[:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
806
|
+
RETURN DISTINCT p.id AS id, p.label AS label, p.stepCount AS stepCount
|
|
807
|
+
ORDER BY p.stepCount DESC
|
|
808
|
+
LIMIT 20
|
|
809
|
+
`,[ge,M]=await Promise.all([e(Y),e(Z)]),K=ge.map(oe=>{const X=A(oe,0,"name"),ie=A(oe,1,"filePath");return`- ${A(oe,2,"nodeType")}: ${X} (${ie||"n/a"})`}),se=M.map(oe=>{const X=A(oe,1,"label"),ie=A(oe,2,"stepCount");return`- ${X} (${ie} steps)`});return[`CLUSTER: ${O}`,`Symbols: ${B??ge.length}`,`Cohesion: ${U!=null?Number(U).toFixed(2):"n/a"}`,`Description: ${F||"n/a"}`,"","TOP MEMBERS:",...K.length>0?K:["- None found"],"","PROCESSES TOUCHING THIS CLUSTER:",...se.length>0?se:["- None found"]].join(`
|
|
810
|
+
`)}if(b==="symbol"){const x=A(T,0,"id"),O=A(T,1,"name"),U=A(T,2,"filePath"),B=A(T,3,"nodeType");if(!qY(B))return`Unknown node type "${B}" for symbol "${m}".`;const F=`
|
|
811
|
+
MATCH (n:${B} {id: '${String(x).replace(/'/g,"''")}'})
|
|
812
|
+
MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
813
|
+
RETURN c.label AS label, c.description AS description
|
|
814
|
+
LIMIT 1
|
|
815
|
+
`,Y=`
|
|
816
|
+
MATCH (n:${B} {id: '${String(x).replace(/'/g,"''")}'})
|
|
817
|
+
MATCH (n)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
|
|
818
|
+
RETURN f.name AS name, f.slug AS slug, f.featureKind AS kind
|
|
819
|
+
LIMIT 1
|
|
820
|
+
`,Z=`
|
|
821
|
+
MATCH (n:${B} {id: '${String(x).replace(/'/g,"''")}'})
|
|
822
|
+
MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
823
|
+
RETURN p.label AS label, r.step AS step, p.stepCount AS stepCount
|
|
824
|
+
ORDER BY r.step
|
|
825
|
+
`,ge=`
|
|
826
|
+
MATCH (n:${B} {id: '${String(x).replace(/'/g,"''")}'})
|
|
827
|
+
OPTIONAL MATCH (n)-[r1:CodeRelation]->(dst)
|
|
828
|
+
OPTIONAL MATCH (src)-[r2:CodeRelation]->(n)
|
|
829
|
+
RETURN
|
|
830
|
+
collect(DISTINCT {name: dst.name, type: r1.type, confidence: r1.confidence}) AS outgoing,
|
|
831
|
+
collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
|
|
832
|
+
LIMIT 1
|
|
833
|
+
`,[M,K,se,oe]=await Promise.all([e(F),e(Y),e(Z),e(ge)]),X=M.length>0?A(M[0],0,"label"):"Unclustered",ie=M.length>0?A(M[0],1,"description"):"",Ee=K.length>0?A(K[0],0,"name")||A(K[0],1,"slug"):"",de=K.length>0?A(K[0],2,"kind"):"",E=se.map(j=>{const C=A(j,0,"label"),_e=A(j,1,"step"),xe=A(j,2,"stepCount");return`- ${C} (step ${_e}/${xe??"?"})`});let v="None";if(oe.length>0){const j=oe[0],C=Array.isArray(j)?j[0]:j.outgoing||[],_e=Array.isArray(j)?j[1]:j.incoming||[],xe=(C||[]).filter(Ue=>Ue&&Ue.name).slice(0,5),dt=(_e||[]).filter(Ue=>Ue&&Ue.name).slice(0,5),Qe=(Ue,Dt)=>{const bn=Ue.confidence?Math.round(Ue.confidence*100):100;return Dt==="out"?`-[${Ue.type} ${bn}%]-> ${Ue.name}`:`<-[${Ue.type} ${bn}%]- ${Ue.name}`},yt=xe.map(Ue=>Qe(Ue,"out")),Ot=dt.map(Ue=>Qe(Ue,"in"));(yt.length||Ot.length)&&(v=[...yt,...Ot].join(", "))}return[`SYMBOL: ${B} ${O}`,`ID: ${x}`,`File: ${U||"n/a"}`,`Feature: ${Ee||"Unassigned"}${de?` (${de})`:""}`,`Cluster: ${X}${ie?` — ${ie}`:""}`,"","PROCESSES:",...E.length>0?E:["- None found"],"","CONNECTIONS:",v].join(`
|
|
834
|
+
`)}return`Unable to explore "${m}".`},{name:"explore",description:"Deep dive on a symbol, feature cluster, structural cluster, or process. Shows membership, participation, and connections.",schema:Yi({target:Ps().describe("Name or ID of a symbol, feature cluster, cluster, or process"),type:jT(["symbol","feature","cluster","process"]).optional().nullable().describe("Optional target type (auto-detected if omitted)")})}),h=li(async({target:m,direction:g,maxDepth:y,relationTypes:b,includeTests:_,minConfidence:w})=>{var Ce;const S=Math.min(y??3,10),T=_??!1,A=w??.7,I=Q=>{if(!Q)return!1;const Je=Q.toLowerCase();return Je.includes(".test.")||Je.includes(".spec.")||Je.includes("__tests__")||Je.includes("__mocks__")||Je.endsWith(".test.ts")||Je.endsWith(".test.tsx")||Je.endsWith(".spec.ts")||Je.endsWith(".spec.tsx")},k=["CALLS","IMPORTS","EXTENDS","IMPLEMENTS"],R=b&&b.length>0?b.filter(Q=>GY(Q)):k;if(R.length===0)return`No valid relation types provided. Valid types: ${JT.join(", ")}`;const x=R.map(Q=>`'${Q.replace(/'/g,"''")}'`).join(", "),O=g==="upstream"?"Files that DEPEND ON this (breakage risk)":"Dependencies this RELIES ON",U=m.includes("/"),B=m.replace(/'/g,"''"),F=U?`
|
|
835
|
+
MATCH (n)
|
|
836
|
+
WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${B}'
|
|
837
|
+
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
838
|
+
LIMIT 10
|
|
839
|
+
`:`
|
|
840
|
+
MATCH (n)
|
|
841
|
+
WHERE n.name = '${B}'
|
|
842
|
+
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
843
|
+
LIMIT 10
|
|
844
|
+
`;let Y;try{Y=await e(F)}catch(Q){return`Error finding target "${m}": ${Q}`}if(!Y||Y.length===0)return`Could not find "${m}" in the codebase. Try using the search tool first to find the exact name.`;const Z=Y.map(Q=>Array.isArray(Q)?Q[2]:Q.filePath).filter(Boolean);if(Y.length>1&&!m.includes("/"))return`⚠️ AMBIGUOUS TARGET: Multiple files named "${m}" found:
|
|
845
|
+
|
|
846
|
+
${Z.map((Q,Je)=>`${Je+1}. ${Q}`).join(`
|
|
847
|
+
`)}
|
|
848
|
+
|
|
849
|
+
Please specify which file you mean by using a more specific path, e.g.:
|
|
850
|
+
- impact("${Z[0].split("/").slice(-3).join("/")}")
|
|
851
|
+
- impact("${((Ce=Z[1])==null?void 0:Ce.split("/").slice(-3).join("/"))||Z[0]}")`;let ge=Y[0];if(m.includes("/")&&Y.length>1){const Q=Y.find(Je=>{const wt=Array.isArray(Je)?Je[2]:Je.filePath;return wt&&wt.toLowerCase().includes(m.toLowerCase())});if(Q)ge=Q;else return`⚠️ AMBIGUOUS TARGET: Could not uniquely match "${m}". Found:
|
|
852
|
+
|
|
853
|
+
${Z.map((Je,wt)=>`${wt+1}. ${Je}`).join(`
|
|
854
|
+
`)}
|
|
855
|
+
|
|
856
|
+
Please use a more specific path.`}const M=Array.isArray(ge)?ge[0]:ge.id,K=Array.isArray(ge)?ge[1]:ge.nodeType,se=Array.isArray(ge)?ge[2]:ge.filePath,oe="",X=K==="File",ie=[],Ee=g==="upstream"?X?`
|
|
857
|
+
MATCH (affected)-[r:CodeRelation]->(callee)
|
|
858
|
+
WHERE callee.filePath = '${(se||m).replace(/'/g,"''")}'
|
|
859
|
+
AND r.type IN [${x}]
|
|
860
|
+
AND affected.filePath <> callee.filePath
|
|
861
|
+
AND (r.confidence IS NULL OR r.confidence >= ${A})
|
|
862
|
+
RETURN DISTINCT
|
|
863
|
+
affected.id AS id,
|
|
864
|
+
affected.name AS name,
|
|
865
|
+
label(affected) AS nodeType,
|
|
866
|
+
affected.filePath AS filePath,
|
|
867
|
+
affected.startLine AS startLine,
|
|
868
|
+
1 AS depth,
|
|
869
|
+
r.type AS edgeType,
|
|
870
|
+
r.confidence AS confidence,
|
|
871
|
+
r.reason AS reason
|
|
872
|
+
LIMIT 300
|
|
873
|
+
`:`
|
|
874
|
+
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
875
|
+
MATCH (affected)-[r:CodeRelation]->(target)
|
|
876
|
+
WHERE r.type IN [${x}]
|
|
877
|
+
AND (r.confidence IS NULL OR r.confidence >= ${A})
|
|
878
|
+
RETURN DISTINCT
|
|
879
|
+
affected.id AS id,
|
|
880
|
+
affected.name AS name,
|
|
881
|
+
label(affected) AS nodeType,
|
|
882
|
+
affected.filePath AS filePath,
|
|
883
|
+
affected.startLine AS startLine,
|
|
884
|
+
1 AS depth,
|
|
885
|
+
r.type AS edgeType,
|
|
886
|
+
r.confidence AS confidence,
|
|
887
|
+
r.reason AS reason
|
|
888
|
+
LIMIT 300
|
|
889
|
+
`:X?`
|
|
890
|
+
MATCH (caller)-[r:CodeRelation]->(affected)
|
|
891
|
+
WHERE caller.filePath = '${(se||m).replace(/'/g,"''")}'
|
|
892
|
+
AND r.type IN [${x}]
|
|
893
|
+
AND caller.filePath <> affected.filePath
|
|
894
|
+
AND (r.confidence IS NULL OR r.confidence >= ${A})
|
|
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
|
+
1 AS depth,
|
|
902
|
+
r.type AS edgeType,
|
|
903
|
+
r.confidence AS confidence,
|
|
904
|
+
r.reason AS reason
|
|
905
|
+
LIMIT 300
|
|
906
|
+
`:`
|
|
907
|
+
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
908
|
+
MATCH (target)-[r:CodeRelation]->(affected)
|
|
909
|
+
WHERE r.type IN [${x}]
|
|
910
|
+
AND (r.confidence IS NULL OR r.confidence >= ${A})
|
|
911
|
+
RETURN DISTINCT
|
|
912
|
+
affected.id AS id,
|
|
913
|
+
affected.name AS name,
|
|
914
|
+
label(affected) AS nodeType,
|
|
915
|
+
affected.filePath AS filePath,
|
|
916
|
+
affected.startLine AS startLine,
|
|
917
|
+
1 AS depth,
|
|
918
|
+
r.type AS edgeType,
|
|
919
|
+
r.confidence AS confidence,
|
|
920
|
+
r.reason AS reason
|
|
921
|
+
LIMIT 300
|
|
922
|
+
`;if(ie.push(e(Ee).then(Q=>Q).catch(Q=>[])),S>=2){const Q=g==="upstream"?`
|
|
923
|
+
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
924
|
+
MATCH (a)-[r1:CodeRelation]->(target)
|
|
925
|
+
MATCH (affected)-[r2:CodeRelation]->(a)
|
|
926
|
+
WHERE r1.type IN [${x}] AND r2.type IN [${x}]
|
|
927
|
+
AND affected.id <> target.id
|
|
928
|
+
AND (r1.confidence IS NULL OR r1.confidence >= ${A})
|
|
929
|
+
AND (r2.confidence IS NULL OR r2.confidence >= ${A})
|
|
930
|
+
RETURN DISTINCT
|
|
931
|
+
affected.id AS id,
|
|
932
|
+
affected.name AS name,
|
|
933
|
+
label(affected) AS nodeType,
|
|
934
|
+
affected.filePath AS filePath,
|
|
935
|
+
affected.startLine AS startLine,
|
|
936
|
+
2 AS depth,
|
|
937
|
+
r2.type AS edgeType,
|
|
938
|
+
r2.confidence AS confidence,
|
|
939
|
+
r2.reason AS reason
|
|
940
|
+
LIMIT 200
|
|
941
|
+
`:`
|
|
942
|
+
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
943
|
+
MATCH (target)-[r1:CodeRelation]->(a)
|
|
944
|
+
MATCH (a)-[r2:CodeRelation]->(affected)
|
|
945
|
+
WHERE r1.type IN [${x}] AND r2.type IN [${x}]
|
|
946
|
+
AND affected.id <> target.id
|
|
947
|
+
AND (r1.confidence IS NULL OR r1.confidence >= ${A})
|
|
948
|
+
AND (r2.confidence IS NULL OR r2.confidence >= ${A})
|
|
949
|
+
RETURN DISTINCT
|
|
950
|
+
affected.id AS id,
|
|
951
|
+
affected.name AS name,
|
|
952
|
+
label(affected) AS nodeType,
|
|
953
|
+
affected.filePath AS filePath,
|
|
954
|
+
affected.startLine AS startLine,
|
|
955
|
+
2 AS depth,
|
|
956
|
+
r2.type AS edgeType,
|
|
957
|
+
r2.confidence AS confidence,
|
|
958
|
+
r2.reason AS reason
|
|
959
|
+
LIMIT 200
|
|
960
|
+
`;ie.push(e(Q).catch(Je=>[]))}if(S>=3){const Q=g==="upstream"?`
|
|
961
|
+
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
962
|
+
MATCH (a)-[r1:CodeRelation]->(target)
|
|
963
|
+
MATCH (b)-[r2:CodeRelation]->(a)
|
|
964
|
+
MATCH (affected)-[r3:CodeRelation]->(b)
|
|
965
|
+
WHERE r1.type IN [${x}] AND r2.type IN [${x}] AND r3.type IN [${x}]
|
|
966
|
+
AND affected.id <> target.id AND affected.id <> a.id
|
|
967
|
+
AND (r1.confidence IS NULL OR r1.confidence >= ${A})
|
|
968
|
+
AND (r2.confidence IS NULL OR r2.confidence >= ${A})
|
|
969
|
+
AND (r3.confidence IS NULL OR r3.confidence >= ${A})
|
|
970
|
+
RETURN DISTINCT
|
|
971
|
+
affected.id AS id,
|
|
972
|
+
affected.name AS name,
|
|
973
|
+
label(affected) AS nodeType,
|
|
974
|
+
affected.filePath AS filePath,
|
|
975
|
+
affected.startLine AS startLine,
|
|
976
|
+
3 AS depth,
|
|
977
|
+
r3.type AS edgeType,
|
|
978
|
+
r3.confidence AS confidence,
|
|
979
|
+
r3.reason AS reason
|
|
980
|
+
LIMIT 100
|
|
981
|
+
`:`
|
|
982
|
+
MATCH (target {id: '${M.replace(/'/g,"''")}'})
|
|
983
|
+
MATCH (target)-[r1:CodeRelation]->(a)
|
|
984
|
+
MATCH (a)-[r2:CodeRelation]->(b)
|
|
985
|
+
MATCH (b)-[r3:CodeRelation]->(affected)
|
|
986
|
+
WHERE r1.type IN [${x}] AND r2.type IN [${x}] AND r3.type IN [${x}]
|
|
987
|
+
AND affected.id <> target.id AND affected.id <> a.id
|
|
988
|
+
AND (r1.confidence IS NULL OR r1.confidence >= ${A})
|
|
989
|
+
AND (r2.confidence IS NULL OR r2.confidence >= ${A})
|
|
990
|
+
AND (r3.confidence IS NULL OR r3.confidence >= ${A})
|
|
991
|
+
RETURN DISTINCT
|
|
992
|
+
affected.id AS id,
|
|
993
|
+
affected.name AS name,
|
|
994
|
+
label(affected) AS nodeType,
|
|
995
|
+
affected.filePath AS filePath,
|
|
996
|
+
affected.startLine AS startLine,
|
|
997
|
+
3 AS depth,
|
|
998
|
+
r3.type AS edgeType,
|
|
999
|
+
r3.confidence AS confidence,
|
|
1000
|
+
r3.reason AS reason
|
|
1001
|
+
LIMIT 100
|
|
1002
|
+
`;ie.push(e(Q).catch(Je=>[]))}const de=await Promise.all(ie),E=new Map,v=[],j=new Set;de.forEach((Q,Je)=>{const wt=Je+1;Q.forEach(Ye=>{const en=Array.isArray(Ye)?Ye[0]:Ye.id,wr=Array.isArray(Ye)?Ye[3]:Ye.filePath;if(!(!T&&I(wr))&&en&&!j.has(en)){j.add(en),E.has(wt)||E.set(wt,[]);const Vi={id:en,name:Array.isArray(Ye)?Ye[1]:Ye.name,nodeType:Array.isArray(Ye)?Ye[2]:Ye.nodeType,filePath:wr,startLine:Array.isArray(Ye)?Ye[4]:Ye.startLine,edgeType:Array.isArray(Ye)?Ye[5]:Ye.edgeType||"CALLS",confidence:Array.isArray(Ye)?Ye[6]:Ye.confidence??1,reason:Array.isArray(Ye)?Ye[7]:Ye.reason||""};E.get(wt).push(Vi),v.push(en)}})});const C=v.length;if(C===0){if(X){const Q=Ye=>Ye.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),wt=((se||m).split("/").pop()||m).replace(/\.[^/.]+$/,"");try{const en=(await r(`\\b${Q(wt)}\\b`,15)).filter(wr=>wr.filePath!==se);if(en.length>0){const wr=en.map(Vi=>`${Vi.filePath}:${Vi.line}: ${Vi.text}`).join(`
|
|
1003
|
+
`);return`No ${g} dependencies found for "${m}" (types: ${R.join(", ")}), but textual references were detected (graph may be incomplete):
|
|
1004
|
+
|
|
1005
|
+
${wr}${oe}`}}catch{}}return`No ${g} dependencies found for "${m}" (types: ${R.join(", ")}). This code appears to be ${g==="upstream"?"unused (not called by anything)":"self-contained (no outgoing dependencies)"}.${oe}`}const _e=E.get(1)||[],xe=E.get(2)||[],dt=E.get(3)||[],Qe={high:0,medium:0,low:0};for(const Q of E.values())for(const Je of Q){const wt=Je.confidence??1;wt>=.9?Qe.high+=1:wt>=.8?Qe.medium+=1:Qe.low+=1}const Ot=v.slice(0,500),Ue=Ot.map(Q=>`'${Q.replace(/'/g,"''")}'`).join(", ");let Dt=[],bn=[],yr=[];if(Ot.length>0){const Q=`
|
|
1006
|
+
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
1007
|
+
WHERE s.id IN [${Ue}]
|
|
1008
|
+
RETURN p.label AS label, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep, p.stepCount AS stepCount
|
|
1009
|
+
ORDER BY hits DESC
|
|
1010
|
+
LIMIT 20
|
|
1011
|
+
`,Je=`
|
|
1012
|
+
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
1013
|
+
WHERE s.id IN [${Ue}]
|
|
1014
|
+
RETURN c.label AS label, COUNT(DISTINCT s.id) AS hits
|
|
1015
|
+
ORDER BY hits DESC
|
|
1016
|
+
LIMIT 20
|
|
1017
|
+
`,wt=`
|
|
1018
|
+
MATCH (s)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
|
|
1019
|
+
WHERE s.id IN [${Ue}]
|
|
1020
|
+
RETURN f.name AS label, f.featureKind AS kind, COUNT(DISTINCT s.id) AS hits
|
|
1021
|
+
ORDER BY hits DESC
|
|
1022
|
+
LIMIT 20
|
|
1023
|
+
`,Ye=_e.map(Ke=>`'${Ke.id.replace(/'/g,"''")}'`).join(", "),en=_e.length>0?`
|
|
1024
|
+
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
1025
|
+
WHERE s.id IN [${Ye}]
|
|
1026
|
+
RETURN DISTINCT c.label AS label
|
|
1027
|
+
`:"",wr=_e.length>0?`
|
|
1028
|
+
MATCH (s)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster)
|
|
1029
|
+
WHERE s.id IN [${Ye}]
|
|
1030
|
+
RETURN DISTINCT f.name AS label
|
|
1031
|
+
`:"",[Vi,vP,SP,AP,TP]=await Promise.all([e(Q),e(Je),en?e(en):Promise.resolve([]),e(wt),wr?e(wr):Promise.resolve([])]),Kb=new Set;SP.forEach(Ke=>{const Pr=Array.isArray(Ke)?Ke[0]:Ke.label;Pr&&Kb.add(Pr)});const Wb=new Set;TP.forEach(Ke=>{const Pr=Array.isArray(Ke)?Ke[0]:Ke.label;Pr&&Wb.add(Pr)}),Dt=Vi.map(Ke=>({label:Array.isArray(Ke)?Ke[0]:Ke.label,hits:Array.isArray(Ke)?Ke[1]:Ke.hits,minStep:Array.isArray(Ke)?Ke[2]:Ke.minStep,stepCount:Array.isArray(Ke)?Ke[3]:Ke.stepCount})),bn=vP.map(Ke=>{const Pr=Array.isArray(Ke)?Ke[0]:Ke.label,Dp=Array.isArray(Ke)?Ke[1]:Ke.hits,Up=Kb.has(Pr)?"direct":"indirect";return{label:Pr,hits:Dp,impact:Up}}),yr=AP.map(Ke=>{const Pr=Array.isArray(Ke)?Ke[0]:Ke.label,Dp=Array.isArray(Ke)?Ke[1]:Ke.kind,Up=Array.isArray(Ke)?Ke[2]:Ke.hits,EP=Wb.has(Pr)?"direct":"indirect";return{label:Pr,kind:Dp,hits:Up,impact:EP}})}const L=_e.length,vn=Dt.length,ke=bn.length,Te=yr.length;let Oe="LOW";L>=30||vn>=5||ke>=5||Te>=5||C>=200?Oe="CRITICAL":L>=15||vn>=3||ke>=3||Te>=3||C>=100?Oe="HIGH":(L>=5||C>=30)&&(Oe="MEDIUM");const ee=[`🔴 IMPACT: ${m} | ${g} | ${C} affected`,`Confidence: High ${Qe.high} | Medium ${Qe.medium} | Low ${Qe.low}`,"","AFFECTED PROCESSES:",...Dt.length>0?Dt.map(Q=>`- ${Q.label} - BROKEN at step ${Q.minStep??"?"} (${Q.hits} symbols, ${Q.stepCount??"?"} steps)`):["- None found"],"","AFFECTED FEATURE CLUSTERS:",...yr.length>0?yr.map(Q=>`- ${Q.label}${Q.kind?` (${Q.kind})`:""} - ${Q.impact}, ${Q.hits} symbols`):["- None found"],"","AFFECTED CLUSTERS:",...bn.length>0?bn.map(Q=>`- ${Q.label} (${Q.impact}, ${Q.hits} symbols)`):["- None found"],"",`RISK: ${Oe}`,`- Direct callers: ${L}`,`- Processes affected: ${vn}`,`- Feature clusters affected: ${Te}`,`- Clusters affected: ${ke}`,""],ne=Q=>{var wr;const Je=((wr=Q.filePath)==null?void 0:wr.split("/").pop())||"",wt=Q.startLine?`${Je}:${Q.startLine}`:Je,Ye=Math.round((Q.confidence??1)*100),en=Ye<80?"[fuzzy]":"";return` ${Q.nodeType}|${Q.name}|${wt}|${Q.edgeType}|${Ye}%${en}`},Re=async Q=>{if(!Q.filePath||!Q.startLine)return null;try{const wt=(await s(Q.filePath)).split(`
|
|
1032
|
+
`),Ye=Q.startLine-1;if(Ye<0||Ye>=wt.length)return null;let en=wt[Ye].trim();return en.length>80&&(en=en.slice(0,77)+"..."),en}catch{return null}};if(_e.length>0){const Q=g==="upstream"?`d=1 (Directly DEPEND ON ${m}):`:`d=1 (${m} USES these):`;ee.push(Q);for(const Je of _e.slice(0,15)){ee.push(ne(Je));const wt=await Re(Je);wt&&ee.push(` ↳ "${wt}"`)}_e.length>15&&ee.push(` ... +${_e.length-15} more`),ee.push("")}if(xe.length>0){const Q=g==="upstream"?`d=2 (Indirectly DEPEND ON ${m}):`:`d=2 (${m} USES these indirectly):`;ee.push(Q),xe.slice(0,15).forEach(Je=>ee.push(ne(Je))),xe.length>15&&ee.push(` ... +${xe.length-15} more`),ee.push("")}return dt.length>0&&(ee.push("d=3 (Deep impact/dependency):"),dt.slice(0,5).forEach(Q=>ee.push(ne(Q))),dt.length>5&&ee.push(` ... +${dt.length-5} more`),ee.push("")),ee.push("✅ GRAPH ANALYSIS COMPLETE (trusted)"),ee.push(`⚠️ Optional: grep("${m}") for dynamic patterns`),ee.push(""),ee.join(`
|
|
1033
|
+
`)},{name:"impact",description:`Analyze the impact of changing a function, class, or file.
|
|
1034
|
+
|
|
1035
|
+
Use when users ask:
|
|
1036
|
+
- "What would break if I changed X?"
|
|
1037
|
+
- "What depends on X?"
|
|
1038
|
+
- "Impact analysis for X"
|
|
1039
|
+
|
|
1040
|
+
Direction:
|
|
1041
|
+
- upstream: Find what CALLS/IMPORTS/EXTENDS this target (what would break)
|
|
1042
|
+
- downstream: Find what this target CALLS/IMPORTS/EXTENDS (dependencies)
|
|
1043
|
+
|
|
1044
|
+
Output format (compact tabular):
|
|
1045
|
+
Type|Name|File:Line|EdgeType|Confidence%
|
|
1046
|
+
|
|
1047
|
+
EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS
|
|
1048
|
+
Confidence: 100% = certain, <80% = fuzzy match (may be false positive)
|
|
1049
|
+
|
|
1050
|
+
relationTypes filter (optional):
|
|
1051
|
+
- Default: CALLS, IMPORTS, EXTENDS, IMPLEMENTS (usage-based)
|
|
1052
|
+
- Can add CONTAINS, DEFINES for structural analysis
|
|
1053
|
+
|
|
1054
|
+
Additional output sections:
|
|
1055
|
+
- Affected processes (with step impact)
|
|
1056
|
+
- Affected feature clusters (product/domain areas)
|
|
1057
|
+
- Affected clusters (direct/indirect)
|
|
1058
|
+
- Risk summary (based on direct callers, processes, feature clusters, clusters)`,schema:Yi({target:Ps().describe("Name of the function, class, or file to analyze"),direction:jT(["upstream","downstream"]).describe("upstream = what depends on this; downstream = what this depends on"),maxDepth:Yd().optional().nullable().describe("Max traversal depth (default: 3, max: 10)"),relationTypes:WY(Ps()).optional().nullable().describe("Filter by relation types: CALLS, IMPORTS, EXTENDS, IMPLEMENTS, CONTAINS, DEFINES (default: usage-based)"),includeTests:pg().optional().nullable().describe("Include test files in results (default: false, excludes .test.ts, .spec.ts, __tests__)"),minConfidence:Yd().optional().nullable().describe("Minimum edge confidence 0-1 (default: 0.7, excludes fuzzy/inferred matches)")})});return[o,c,u,l,d,f,h]},LT=`You are CodraGraph, a Code Analysis Agent with access to a Knowledge Graph. Your responses MUST be grounded.
|
|
1059
|
+
|
|
1060
|
+
## ⚠️ MANDATORY: GROUNDING
|
|
1061
|
+
Every factual claim MUST include a citation.
|
|
1062
|
+
- File refs: [[src/auth.ts:45-60]] (line range with hyphen)
|
|
1063
|
+
- NO citation = NO claim. Say "I didn't find evidence" instead of guessing.
|
|
1064
|
+
|
|
1065
|
+
## ⚠️ MANDATORY: VALIDATION
|
|
1066
|
+
Every output MUST be validated.
|
|
1067
|
+
- Use cypher to validate the results and confirm completeness of context before final output.
|
|
1068
|
+
- NO validation = NO claim. Say "I didn't find evidence" instead of guessing.
|
|
1069
|
+
- Do not blindly trust readme or single source of truth. Always validate and cross-reference. Never be lazy.
|
|
1070
|
+
|
|
1071
|
+
## 🧠 CORE PROTOCOL
|
|
1072
|
+
You are an investigator. For each question:
|
|
1073
|
+
1. **Search** → Use cypher, search or grep to find relevant code
|
|
1074
|
+
2. **Read** → Use read to see the actual source
|
|
1075
|
+
3. **Trace** → Use cypher to follow connections in the graph
|
|
1076
|
+
4. **Cite** → Ground every finding with [[file:line]] or [[Type:Name]]
|
|
1077
|
+
5. **Validate** → Use cypher to validate the results and confirm completeness of context before final output. ( MUST DO )
|
|
1078
|
+
|
|
1079
|
+
## 🛠️ TOOLS
|
|
1080
|
+
- **\`search\`** — Hybrid search. Results grouped by process with cluster context.
|
|
1081
|
+
- **\`cypher\`** — Cypher queries against the graph. Use \`{{QUERY_VECTOR}}\` for vector search.
|
|
1082
|
+
- **\`grep\`** — Regex search. Best for exact strings, TODOs, error codes.
|
|
1083
|
+
- **\`read\`** — Read file content. Always use after search/grep to see full code.
|
|
1084
|
+
- **\`explore\`** — Deep dive on a symbol, feature cluster, structural cluster, or process.
|
|
1085
|
+
- **\`overview\`** — Codebase map showing feature clusters, structural clusters, and processes.
|
|
1086
|
+
- **\`impact\`** — Impact analysis. Shows affected processes, feature clusters, clusters, and risk level.
|
|
1087
|
+
|
|
1088
|
+
## 📊 GRAPH SCHEMA
|
|
1089
|
+
Nodes: File, Folder, Function, Class, Interface, Method, Community, Process, FeatureCluster, Route, Tool, Section
|
|
1090
|
+
Relations: \`CodeRelation\` with \`type\` property: CONTAINS, DEFINES, IMPORTS, CALLS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, FEATURE_MEMBER_OF, FEATURE_DEPENDS_ON
|
|
1091
|
+
|
|
1092
|
+
## 📐 GRAPH SEMANTICS (Important!)
|
|
1093
|
+
**Edge Types:**
|
|
1094
|
+
- \`CALLS\`: Method invocation OR constructor injection. If A receives B as parameter and uses it, A→B is CALLS. This is intentional simplification.
|
|
1095
|
+
- \`IMPORTS\`: File-level import/include statement.
|
|
1096
|
+
- \`EXTENDS/IMPLEMENTS\`: Class inheritance.
|
|
1097
|
+
|
|
1098
|
+
**Process Nodes:**
|
|
1099
|
+
- Process labels use format: "EntryPoint → Terminal" (e.g., "onCreate → showToast")
|
|
1100
|
+
- These are heuristic names from tracing execution flow, NOT application-defined names
|
|
1101
|
+
- Entry points are detected via export status, naming patterns, and framework conventions
|
|
1102
|
+
|
|
1103
|
+
**FeatureCluster Nodes:**
|
|
1104
|
+
- Feature clusters are human/product areas like Settings, Auth, AI, Billing, Admin, or Docs.
|
|
1105
|
+
- Use \`overview\` first to find relevant feature areas, then \`explore\` with \`type: "feature"\` to load focused files, line ranges, dependencies, and flows.
|
|
1106
|
+
- Prefer feature context before broad exploration when the user asks to refactor or understand an application area.
|
|
1107
|
+
|
|
1108
|
+
Cypher examples:
|
|
1109
|
+
- \`MATCH (f:Function) RETURN f.name LIMIT 10\`
|
|
1110
|
+
- \`MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f.name, g.name\`
|
|
1111
|
+
- \`MATCH (m)-[:CodeRelation {type: 'FEATURE_MEMBER_OF'}]->(f:FeatureCluster {name: 'Settings'}) RETURN m.name, m.filePath, m.startLine\`
|
|
1112
|
+
|
|
1113
|
+
## 📝CRITICAL RULES
|
|
1114
|
+
- **impact output is trusted.** Do NOT re-validate with cypher. Optionally run the suggested grep commands for dynamic patterns.
|
|
1115
|
+
- **Cite or retract.** Never state something you can't ground.
|
|
1116
|
+
- **Read before concluding.** Don't guess from names alone.
|
|
1117
|
+
- **Retry on failure.** If a tool fails, fix the input and try again.
|
|
1118
|
+
- **Cyfer tool validation** prefer using cyfer tool in anything that requires graph connections.
|
|
1119
|
+
- **OUTPUT STYLE** Prefer using tables and mermaid diagrams instead of long explanations.
|
|
1120
|
+
- ALWAYS USE MERMAID FOR VISUALIZATION AND STRUCTURING THE OUTPUT.
|
|
1121
|
+
|
|
1122
|
+
## 🎯 OUTPUT STYLE
|
|
1123
|
+
Think like a senior architect. Be concise—no fluff, short, precise and to the point.
|
|
1124
|
+
- Use tables for comparisons/rankings
|
|
1125
|
+
- Use mermaid diagrams for flows/dependencies
|
|
1126
|
+
- Surface deep insights: patterns, coupling, design decisions
|
|
1127
|
+
- End with **TL;DR** (short summary of the response, summing up the response and the most critical parts)
|
|
1128
|
+
|
|
1129
|
+
## MERMAID RULES
|
|
1130
|
+
When generating diagrams:
|
|
1131
|
+
- NO special characters in node labels: quotes, (), /, &, <, >
|
|
1132
|
+
- Wrap labels with spaces in quotes: A["My Label"]
|
|
1133
|
+
- Use simple IDs: A, B, C or auth, db, api
|
|
1134
|
+
- Flowchart: graph TD or graph LR (not flowchart)
|
|
1135
|
+
- Always test mentally: would this parse?
|
|
1136
|
+
|
|
1137
|
+
BAD: A[User's Data] --> B(Process & Save)
|
|
1138
|
+
GOOD: A["User Data"] --> B["Process and Save"]
|
|
1139
|
+
`,YY=n=>{switch(n.provider){case"openai":{const e=n;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("OpenAI API key is required but was not provided");return new kh({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=n;return new Qq({azureOpenAIApiKey:e.apiKey,azureOpenAIApiInstanceName:XY(e.endpoint),azureOpenAIApiDeploymentName:e.deploymentName,azureOpenAIApiVersion:e.apiVersion??"2024-12-01-preview",streaming:!0})}case"gemini":{const e=n;return new aJ({apiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxOutputTokens:e.maxTokens,streaming:!0})}case"anthropic":{const e=n;return new yT({anthropicApiKey:e.apiKey,model:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens??8192,streaming:!0})}case"ollama":{const e=n;return new bY({baseUrl:e.baseUrl??OP,model:e.model,temperature:e.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case"openrouter":{const e=n;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("OpenRouter API key is required but was not provided");return new kh({openAIApiKey:e.apiKey,apiKey:e.apiKey,modelName:e.model,temperature:e.temperature??.1,maxTokens:e.maxTokens,configuration:{apiKey:e.apiKey,baseURL:e.baseUrl??xP},streaming:!0})}case"minimax":{const e=n;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("MiniMax API key is required but was not provided");return new yT({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=n;if(!e.apiKey||e.apiKey.trim()==="")throw new Error("GLM API key is required but was not provided");return new kh({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: ${n.provider}`)}},XY=n=>{try{const t=new URL(n).hostname,r=t.match(/^([^.]+)\.openai\.azure\.com/);return r?r[1]:t.split(".")[0]}catch{return n}},MQ=(n,e,t)=>{const r=YY(n),s=JY(e),i=t?CP(LT,t):LT;return fK({llm:r,tools:s,messageModifier:new hr(i)})};async function*jQ(n,e){var t,r,s,i,a,o;try{const c=e.map(g=>({role:g.role,content:g.content})),u=await n.stream({messages:c},{streamMode:["values","messages"],recursionLimit:50}),l=new Set,d=new Set;let f=c.length,h=0,m=!1;for await(const g of u){let y,b;if(Array.isArray(g)&&g.length===2&&typeof g[0]=="string"?[y,b]=g:Array.isArray(g)&&((t=g[0])!=null&&t._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 S=_.content,T=_.tool_calls||[];let A="";if(typeof S=="string"?A=S:Array.isArray(S)&&(A=S.filter(I=>I.type==="text"||typeof I=="string").map(I=>typeof I=="string"?I:I.text||"").join("")),A&&A.length>0){const I=!m||T.length>0||h>0;yield{type:I?"reasoning":"content",[I?"reasoning":"content"]:A}}if(T.length>0){m=!0,h+=T.length;for(const I of T){const k=I.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!l.has(k)){l.add(k);let R;try{R=(i=I.function)!=null&&i.arguments?JSON.parse(I.function.arguments):{}}catch{R={}}yield{type:"tool_call",toolCall:{id:k,name:I.name||((a=I.function)==null?void 0:a.name)||"unknown",args:I.args||R,status:"running"}}}}}}if(w==="tool"||w==="ToolMessage"){const S=_.tool_call_id||"";if(S&&!d.has(S)){d.add(S);const T=typeof _.content=="string"?_.content:JSON.stringify(_.content);yield{type:"tool_result",toolCall:{id:S,name:_.name||"tool",args:{},result:T,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 S=_[w],T=((o=S._getType)==null?void 0:o.call(S))||S.type||"unknown";if((T==="ai"||T==="AIMessage")&&!l.size){const A=S.tool_calls||[];for(const I of A){const k=I.id||`tool-${Date.now()}`;l.has(k)||(h++,l.add(k),yield{type:"tool_call",toolCall:{id:k,name:I.name||"unknown",args:I.args||{},status:"running"}})}}if(T==="tool"||T==="ToolMessage"){const A=S.tool_call_id||"";if(A&&!d.has(A)){d.add(A);const I=typeof S.content=="string"?S.content:JSON.stringify(S.content);yield{type:"tool_result",toolCall:{id:A,name:S.name||"tool",args:{},result:I,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 LQ=async(n,e)=>{var i;const t=e.map(a=>({role:a.role,content:a.content})),r=await n.invoke({messages:t}),s=r.messages[r.messages.length-1];return((i=s==null?void 0:s.content)==null?void 0:i.toString())??"No response generated."};export{LT as BASE_SYSTEM_PROMPT,YY as createChatModel,MQ as createGraphRAGAgent,LQ as invokeAgent,jQ as streamAgentResponse};
|