gitnexus 1.6.10-rc.2 → 1.6.10-rc.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -12
- package/dist/cli/analyze.js +166 -5
- package/dist/cli/clean.js +17 -3
- package/dist/cli/cli-message.d.ts +1 -1
- package/dist/cli/doctor.d.ts +18 -0
- package/dist/cli/doctor.js +76 -3
- package/dist/cli/embeddings.d.ts +12 -0
- package/dist/cli/embeddings.js +49 -0
- package/dist/cli/help-i18n.js +4 -0
- package/dist/cli/i18n/en.d.ts +10 -5
- package/dist/cli/i18n/en.js +10 -5
- package/dist/cli/i18n/resources.d.ts +15 -5
- package/dist/cli/i18n/zh-CN.d.ts +5 -0
- package/dist/cli/i18n/zh-CN.js +10 -5
- package/dist/cli/index.js +12 -1
- package/dist/core/augmentation/engine.js +4 -3
- package/dist/core/embeddings/embedder.js +16 -2
- package/dist/core/embeddings/embedding-pipeline.d.ts +20 -0
- package/dist/core/embeddings/embedding-pipeline.js +10 -2
- package/dist/core/embeddings/http-client.d.ts +28 -1
- package/dist/core/embeddings/http-client.js +107 -15
- package/dist/core/embeddings/node-module-compat.d.ts +23 -0
- package/dist/core/embeddings/node-module-compat.js +23 -0
- package/dist/core/embeddings/onnxruntime-common-resolver.js +6 -3
- package/dist/core/embeddings/onnxruntime-node-resolver.js +31 -5
- package/dist/core/embeddings/runtime-install.d.ts +119 -0
- package/dist/core/embeddings/runtime-install.js +372 -0
- package/dist/core/embeddings/runtime-support.d.ts +48 -17
- package/dist/core/embeddings/runtime-support.js +96 -0
- package/dist/core/group/extractors/http-patterns/python.js +246 -108
- package/dist/core/group/extractors/manifest-extractor.js +4 -0
- package/dist/core/incremental/escalation-gate.d.ts +38 -0
- package/dist/core/incremental/escalation-gate.js +48 -0
- package/dist/core/incremental/shadow-candidates.d.ts +3 -3
- package/dist/core/incremental/shadow-candidates.js +3 -3
- package/dist/core/incremental/subgraph-extract.d.ts +2 -2
- package/dist/core/incremental/subgraph-extract.js +2 -2
- package/dist/core/ingestion/cobol/jcl-processor.js +9 -8
- package/dist/core/ingestion/cobol-processor.js +27 -26
- package/dist/core/ingestion/community-processor.d.ts +51 -1
- package/dist/core/ingestion/community-processor.js +316 -63
- package/dist/core/ingestion/emit-references.js +3 -2
- package/dist/core/ingestion/languages/cpp/captures.js +157 -74
- package/dist/core/ingestion/markdown-processor.js +3 -2
- package/dist/core/ingestion/parsing-processor.d.ts +3 -1
- package/dist/core/ingestion/parsing-processor.js +4 -0
- package/dist/core/ingestion/pipeline-phases/parse-impl.js +42 -0
- package/dist/core/ingestion/route-extractors/constant-resolver.d.ts +83 -0
- package/dist/core/ingestion/route-extractors/constant-resolver.js +131 -0
- package/dist/core/ingestion/route-extractors/python-const-resolver.d.ts +75 -0
- package/dist/core/ingestion/route-extractors/python-const-resolver.js +299 -0
- package/dist/core/ingestion/tree-sitter-queries.d.ts +1 -1
- package/dist/core/ingestion/tree-sitter-queries.js +12 -1
- package/dist/core/ingestion/utils/line-base.d.ts +20 -0
- package/dist/core/ingestion/utils/line-base.js +20 -0
- package/dist/core/ingestion/utils/symbol-labels.d.ts +21 -0
- package/dist/core/ingestion/utils/symbol-labels.js +45 -0
- package/dist/core/ingestion/workers/parse-worker.d.ts +34 -0
- package/dist/core/ingestion/workers/parse-worker.js +40 -5
- package/dist/core/ingestion/workers/result-merge.js +4 -0
- package/dist/core/ingestion/workers/worker-pool.d.ts +14 -0
- package/dist/core/ingestion/workers/worker-pool.js +85 -5
- package/dist/core/lbug/csv-generator.js +8 -2
- package/dist/core/lbug/cypher-escape.d.ts +20 -0
- package/dist/core/lbug/cypher-escape.js +20 -0
- package/dist/core/lbug/extension-load-error.d.ts +67 -0
- package/dist/core/lbug/extension-load-error.js +320 -0
- package/dist/core/lbug/extension-loader.d.ts +17 -2
- package/dist/core/lbug/extension-loader.js +38 -13
- package/dist/core/lbug/lbug-adapter.d.ts +147 -1
- package/dist/core/lbug/lbug-adapter.js +390 -70
- package/dist/core/lbug/lbug-config.d.ts +28 -0
- package/dist/core/lbug/lbug-config.js +114 -4
- package/dist/core/lbug/native-check.d.ts +22 -0
- package/dist/core/lbug/native-check.js +66 -0
- package/dist/core/lbug/pool-adapter.js +10 -1
- package/dist/core/lbug/sidecar-recovery.d.ts +172 -0
- package/dist/core/lbug/sidecar-recovery.js +418 -16
- package/dist/core/platform/capabilities.js +27 -1
- package/dist/core/run-analyze.js +470 -108
- package/dist/core/search/fts-indexes.d.ts +7 -0
- package/dist/core/search/fts-indexes.js +37 -0
- package/dist/core/tree-sitter/safe-parse.d.ts +8 -3
- package/dist/core/tree-sitter/safe-parse.js +21 -7
- package/dist/core/wiki/graph-queries.js +6 -5
- package/dist/mcp/core/embedder.js +16 -2
- package/dist/mcp/local/line-display.d.ts +22 -0
- package/dist/mcp/local/line-display.js +3 -0
- package/dist/mcp/local/local-backend.d.ts +14 -0
- package/dist/mcp/local/local-backend.js +63 -19
- package/dist/mcp/local/pdg-impact.d.ts +5 -3
- package/dist/mcp/local/pdg-impact.js +5 -2
- package/dist/mcp/resources.js +1 -0
- package/dist/mcp/tools.js +1 -1
- package/dist/server/analyze-launch.d.ts +6 -0
- package/dist/server/analyze-launch.js +82 -6
- package/dist/server/api.d.ts +30 -0
- package/dist/server/api.js +63 -21
- package/dist/storage/parse-cache.js +1 -1
- package/dist/storage/repo-manager.d.ts +65 -1
- package/dist/storage/repo-manager.js +18 -1
- package/hooks/antigravity/gitnexus-antigravity-hook.cjs +50 -3
- package/hooks/claude/gitnexus-hook.cjs +59 -9
- package/package.json +5 -3
- package/scripts/cross-platform-tests.ts +43 -0
- package/scripts/ensure-fts.ts +32 -0
- package/scripts/install-duckdb-extension.mjs +85 -24
- package/scripts/run-cross-platform.ts +46 -6
- package/scripts/shard-arg.ts +30 -0
- package/web/assets/ProcessFlowModal-Dna7GkwO.js +22 -0
- package/web/assets/{agent-Dli_x7bU.js → agent-DNYDy-KA.js} +49 -49
- package/web/assets/architecture-7EHR7CIX-6QZW5X65-BVWFvYz2.js +1 -0
- package/web/assets/architectureDiagram-UL44E2DR-BU5ZRITg.js +36 -0
- package/web/assets/{blockDiagram-7IZFK4PR-BkWhpzWB.js → blockDiagram-7IZFK4PR-Dut1BpTV.js} +2 -2
- package/web/assets/{c4Diagram-Y2BXMSZH-DtBvpzWD.js → c4Diagram-Y2BXMSZH-DOXVs7-C.js} +2 -2
- package/web/assets/chunk-2T2R6R2M-pkw2oXHH.js +4 -0
- package/web/assets/chunk-2UTLFMKG-CXlhF3Pt.js +1 -0
- package/web/assets/chunk-3SSMPTDK-rPsRM1x0.js +321 -0
- package/web/assets/chunk-4R4BOZG6-Be_F0JoX.js +159 -0
- package/web/assets/{chunk-6764PJDD-DpIS7hxD.js → chunk-6764PJDD-C7xxk063.js} +1 -1
- package/web/assets/{chunk-67TQ5CYL-4sNPJU1q.js → chunk-67TQ5CYL-zxhDWgyF.js} +3 -3
- package/web/assets/chunk-7FYTHRHK-CsmYIswB.js +32 -0
- package/web/assets/chunk-7J6CGLKN-AmkN8jJN.js +10 -0
- package/web/assets/chunk-7W6UQGC5-pyKGssV3.js +1 -0
- package/web/assets/chunk-C62D2QBJ-3gdL8EKc.js +1 -0
- package/web/assets/chunk-CEXFNPSA-CjwtMDkc.js +1 -0
- package/web/assets/{chunk-INKRHTLW-Nu4ri9P-.js → chunk-INKRHTLW-D9BM9HWZ.js} +1 -1
- package/web/assets/chunk-J5EP6P6S-L19oz55R.js +1 -0
- package/web/assets/{chunk-KGFNY3KK-JGMJvKCK.js → chunk-KGFNY3KK-tD2F6wxK.js} +1 -1
- package/web/assets/chunk-KGYTTC2M-zm6n242I.js +1 -0
- package/web/assets/{chunk-KRXBNO2N-BW5o0KUN.js → chunk-KRXBNO2N-C-UNuKKf.js} +1 -1
- package/web/assets/{chunk-LCXTWHL2-CfLLCywY.js → chunk-LCXTWHL2-Ba9JK-6F.js} +2 -2
- package/web/assets/{chunk-LII3EMHJ-D-jm-dLa.js → chunk-LII3EMHJ-EGx-eBIu.js} +1 -1
- package/web/assets/chunk-LRIF4GLE-C3_PqUBq.js +1 -0
- package/web/assets/{chunk-QA3QBVWF-BgRW3SXd.js → chunk-QA3QBVWF-D4cSJBf6.js} +1 -1
- package/web/assets/chunk-RERM46MO-B5dAdWpP.js +1 -0
- package/web/assets/{chunk-RG4AUYOV-CqWzWsV3.js → chunk-RG4AUYOV-OqBBMwuQ.js} +4 -4
- package/web/assets/chunk-RKZBBQEN-MyIQbGgD.js +1 -0
- package/web/assets/chunk-RLI5ZMPA-CkXZ0y0U.js +1 -0
- package/web/assets/{chunk-T2UQINTJ-DSBqkzH7.js → chunk-T2UQINTJ-BJusEiGe.js} +1 -1
- package/web/assets/chunk-UP6H54XL-BG-n7qDp.js +1 -0
- package/web/assets/chunk-UXSXWOXI-CW1_r5cS.js +1 -0
- package/web/assets/{chunk-UY5QBCOK-DyF0vyGd.js → chunk-UY5QBCOK-BCpUlARQ.js} +1 -1
- package/web/assets/chunk-VU6ZFW4Y-BeXVk45_.js +2 -0
- package/web/assets/{chunk-W44A43WB-JqMLIpR0.js → chunk-W44A43WB-BN8EQc_u.js} +1 -1
- package/web/assets/{chunk-ZXARS5L4-CxN8oiwI.js → chunk-ZXARS5L4-BI_qR2Nm.js} +1 -1
- package/web/assets/classDiagram-KGZ6W3CR-D9zSIg0x.js +1 -0
- package/web/assets/classDiagram-v2-72OJOZXJ-D9zSIg0x.js +1 -0
- package/web/assets/cose-bilkent-UX7MHV2Q-BmnZ7Mvj.js +1 -0
- package/web/assets/dagre-ND4H6XIP-CpcV5kbl.js +4 -0
- package/web/assets/diagram-3NCE3AQN-6SMxBRpj.js +43 -0
- package/web/assets/diagram-GF46GFSD-BZEdNcRZ.js +24 -0
- package/web/assets/{diagram-HNR7UZ2L-DFCfd5LI.js → diagram-HNR7UZ2L-DxKW2a2Y.js} +2 -2
- package/web/assets/diagram-QXG6HAR7-HfTHcXX_.js +24 -0
- package/web/assets/diagram-WEQXMOUZ-CyijUS8r.js +10 -0
- package/web/assets/{erDiagram-L5TCEMPS-8X1y6R4Y.js → erDiagram-L5TCEMPS-D0fvpWEX.js} +3 -3
- package/web/assets/eventmodeling-FCH6USID-MREXMVOE-CgFBM7e-.js +1 -0
- package/web/assets/flowDiagram-H6V6AXG4-Bvr9bbhk.js +162 -0
- package/web/assets/{ganttDiagram-JCBTUEKG-D3iL2Aet.js → ganttDiagram-JCBTUEKG-TzODrLzv.js} +2 -2
- package/web/assets/gitGraph-WXDBUCRP-R675I2BI-DCJv7SII.js +1 -0
- package/web/assets/gitGraphDiagram-S2ZK5IYY-ONQSwJIY.js +106 -0
- package/web/assets/index-B4eB4dNZ.js +575 -0
- package/web/assets/index-CX_fADmQ.css +2 -0
- package/web/assets/info-J43DQDTF-KCYPFFUO-BfNy-9Nd.js +1 -0
- package/web/assets/infoDiagram-3YFTVSEB-DIPVUIQ6.js +2 -0
- package/web/assets/{ishikawaDiagram-BNXS4ZKH-DfYpxnE5.js → ishikawaDiagram-BNXS4ZKH-BLjivjXL.js} +3 -3
- package/web/assets/{journeyDiagram-M6C3CM3L-CvArszLo.js → journeyDiagram-M6C3CM3L-Cetgs3NH.js} +3 -3
- package/web/assets/{kanban-definition-75IXJCU3-CpfVLLf9.js → kanban-definition-75IXJCU3-DMlCaIpf.js} +5 -5
- package/web/assets/{katex-K3KEBU37-CTc5BslQ.js → katex-K3KEBU37-qRQBy-EZ.js} +2 -2
- package/web/assets/{mindmap-definition-2TDM6QVE-DypvbOMQ.js → mindmap-definition-2TDM6QVE-B4GbXQBc.js} +3 -3
- package/web/assets/packet-YPE3B663-LP52Z2RK-D4qkeG9k.js +1 -0
- package/web/assets/pie-LRSECV5Y-TCRJHUBD-B_yMKyQa.js +1 -0
- package/web/assets/{pieDiagram-CU6KROY3-s27EFWgP.js → pieDiagram-CU6KROY3-D3YC_xyg.js} +2 -2
- package/web/assets/{quadrantDiagram-VICAPDV7-yXSZ2lLz.js → quadrantDiagram-VICAPDV7-B1TQnlm0.js} +2 -2
- package/web/assets/radar-GUYGQ44K-RDLRG3WG-DeD6yN_0.js +1 -0
- package/web/assets/{requirementDiagram-JXO7QTGE-CWhqInuf.js → requirementDiagram-JXO7QTGE-f8wczLQf.js} +3 -3
- package/web/assets/rolldown-runtime-QTnfLwEv.js +1 -0
- package/web/assets/{sankeyDiagram-URQDO5SZ-1qEjlFIB.js → sankeyDiagram-URQDO5SZ-BTxzG5j0.js} +2 -2
- package/web/assets/{sequenceDiagram-VS2MUI6T-RyTlZ5cR.js → sequenceDiagram-VS2MUI6T-DuamM-IR.js} +5 -5
- package/web/assets/src-BNCXICdA.js +1 -0
- package/web/assets/stateDiagram-7D4R322I-Ch2pEUcw.js +1 -0
- package/web/assets/stateDiagram-v2-36443NZ5-7ANuoZLL.js +1 -0
- package/web/assets/{timeline-definition-O6YCAMPW-DrrqLYAf.js → timeline-definition-O6YCAMPW-07BR8R8G.js} +3 -3
- package/web/assets/treeView-BLDUP644-QA4HXRO3-CDuSYnd4.js +1 -0
- package/web/assets/treemap-LRROVOQU-LLAWBHMP-imazucyJ.js +1 -0
- package/web/assets/{vennDiagram-MWXL3ELB-B0RkWAim.js → vennDiagram-MWXL3ELB-BQX2ossk.js} +4 -4
- package/web/assets/wardley-L42UT6IY-5TKZOOLJ-DqrT9tB8.js +1 -0
- package/web/assets/{wardleyDiagram-CUQ6CDDI-boUxiQ5F.js → wardleyDiagram-CUQ6CDDI-CGIJBBiK.js} +3 -3
- package/web/assets/{xychartDiagram-N2JHSOCM-BOLm0eNm.js → xychartDiagram-N2JHSOCM-B3HNMuWp.js} +4 -4
- package/web/index.html +17 -10
- package/web/assets/architecture-7EHR7CIX-6QZW5X65-DxJw65fT.js +0 -1
- package/web/assets/architectureDiagram-UL44E2DR-dEkqUZN9.js +0 -36
- package/web/assets/chunk-3SSMPTDK-B4_etUhr.js +0 -321
- package/web/assets/chunk-7W6UQGC5-KyEG0HQg.js +0 -1
- package/web/assets/chunk-KGYTTC2M-CWC_c3H9.js +0 -161
- package/web/assets/classDiagram-KGZ6W3CR-CMne4tG9.js +0 -1
- package/web/assets/classDiagram-v2-72OJOZXJ-CMne4tG9.js +0 -1
- package/web/assets/cose-bilkent-UX7MHV2Q-D71wNYRJ.js +0 -1
- package/web/assets/dagre-ND4H6XIP-Co5rRx9X.js +0 -4
- package/web/assets/diagram-3NCE3AQN-DBp4O00j.js +0 -43
- package/web/assets/diagram-GF46GFSD-6N_8yS0i.js +0 -24
- package/web/assets/diagram-QXG6HAR7-Di093rFg.js +0 -24
- package/web/assets/diagram-WEQXMOUZ-DZWi4SUN.js +0 -10
- package/web/assets/eventmodeling-FCH6USID-MREXMVOE-BQm9QzEa.js +0 -1
- package/web/assets/flowDiagram-H6V6AXG4-CMpY8Ufn.js +0 -162
- package/web/assets/gitGraph-WXDBUCRP-R675I2BI-Cr_Bm2Nb.js +0 -1
- package/web/assets/gitGraphDiagram-S2ZK5IYY-CPIDgxGm.js +0 -106
- package/web/assets/index-KctnI3Vq.js +0 -635
- package/web/assets/index-_lgn7hs5.css +0 -2
- package/web/assets/info-J43DQDTF-KCYPFFUO-Cs4p2oyk.js +0 -1
- package/web/assets/infoDiagram-3YFTVSEB-BaLMZkUg.js +0 -2
- package/web/assets/packet-YPE3B663-LP52Z2RK-CKCrztD2.js +0 -1
- package/web/assets/pie-LRSECV5Y-TCRJHUBD-BB7pHqoD.js +0 -1
- package/web/assets/radar-GUYGQ44K-RDLRG3WG-DhoTOcuK.js +0 -1
- package/web/assets/stateDiagram-7D4R322I-DTjVfX4A.js +0 -1
- package/web/assets/stateDiagram-v2-36443NZ5-xY9_k9_Q.js +0 -1
- package/web/assets/treeView-BLDUP644-QA4HXRO3-ODehyGKL.js +0 -1
- package/web/assets/treemap-LRROVOQU-LLAWBHMP-BfpgC-7o.js +0 -1
- package/web/assets/wardley-L42UT6IY-5TKZOOLJ-CNeL6VHE.js +0 -1
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as e,t}from"./rolldown-runtime-QTnfLwEv.js";import"./src-BNCXICdA.js";import{CHAT_ONLY_PROMPT_NOTE as n,buildDynamicSystemPrompt as r}from"./context-builder-BHiFUA8O.js";var i=`File.Folder.Function.Class.Interface.Method.CodeElement.Community.Process.Section.Struct.Enum.Macro.Typedef.Union.Namespace.Trait.Impl.TypeAlias.Const.Static.Variable.Property.Record.Delegate.Annotation.Constructor.Template.Module.Route.Tool.BasicBlock`.split(`.`),a=`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.INJECTS.CFG.REACHING_DEF.TAINTED.SANITIZES.TAINT_PATH.CDG.POST_DOMINATE`.split(`.`),o=Object.defineProperty,s=(e,t)=>{let n={};for(var r in e)o(n,r,{get:e[r],enumerable:!0});return t||o(n,Symbol.toStringTag,{value:`Module`}),n};function c(e){let t=Symbol.for(e);return{brand(n,r){let i=r?Symbol.for(`${e}.${r}`):t;class a extends n{[i]=!0;constructor(...e){super(...e)}static isInstance(e){return typeof e==`object`&&!!e&&i in e&&e[i]===!0}}return Object.defineProperty(a,"name",{value:n.name}),a},sub(t){return c(`${e}.${t}`)},isInstance(e){return typeof e==`object`&&!!e&&t in e&&e[t]===!0}}}var l=c(`langchain`),u=s({ContextOverflowError:()=>h,LangChainError:()=>p,ModelAbortError:()=>m,addLangChainErrorFields:()=>d,ns:()=>f});function d(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}var f=l.sub(`error`),p=class extends f.brand(Error){name=`LangChainError`;constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},m=class extends f.brand(p,`model-abort`){name=`ModelAbortError`;partialOutput;constructor(e,t){super(e),this.partialOutput=t}},h=class e extends f.brand(p,`context-overflow`){name=`ContextOverflowError`;cause;constructor(e){super(e??`Input exceeded the model's context window.`)}static fromError(t){let n=new e(t.message);return n.cause=t,n}};function g(e){return!!(e&&typeof e==`object`&&`type`in e&&e.type===`tool_call`)}function _(e){return!!(e&&typeof e==`object`&&`toolCall`in e&&e.toolCall!=null&&typeof e.toolCall==`object`&&`id`in e.toolCall&&typeof e.toolCall.id==`string`)}var v=class extends Error{output;constructor(e,t){super(e),this.output=t}};function y(e,t=x){e=e.trim();let n=e.indexOf("```");if(n===-1)return t(e);let r=e.substring(n+3);r.startsWith(`json
|
|
2
2
|
`)?r=r.substring(5):r.startsWith(`json`)?r=r.substring(4):r.startsWith(`
|
|
3
3
|
`)&&(r=r.substring(1));let i=r.indexOf("```"),a=r;return i!==-1&&(a=r.substring(0,i)),t(a.trim())}function b(e){try{return JSON.parse(e)}catch{}let t=e.trim();if(t.length===0)throw Error(`Unexpected end of JSON input`);let n=0;function r(){for(;n<t.length&&/\s/.test(t[n]);)n+=1}function i(){if(t[n]!==`"`)throw Error(`Expected '"' at position ${n}, got '${t[n]}'`);n+=1;let e=``,r=!1;for(;n<t.length;){let i=t[n];if(r){if(i===`n`)e+=`
|
|
4
4
|
`;else if(i===`t`)e+=` `;else if(i===`r`)e+=`\r`;else if(i===`\\`)e+=`\\`;else if(i===`"`)e+=`"`;else if(i===`b`)e+=`\b`;else if(i===`f`)e+=`\f`;else if(i===`/`)e+=`/`;else if(i===`u`){let r=t.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(r))r.length===4?e+=String.fromCharCode(Number.parseInt(r,16)):e+=`u${r}`,n+=r.length;else throw Error(`Invalid unicode escape sequence '\\u${r}' at position ${n}`)}else throw Error(`Invalid escape sequence '\\${i}' at position ${n}`);r=!1}else if(i===`\\`)r=!0;else if(i===`"`)return n+=1,e;else e+=i;n+=1}return r&&(e+=`\\`),e}function a(){let e=n,r=``;if(t[n]===`-`&&(r+=`-`,n+=1),n<t.length&&t[n]===`0`&&(r+=`0`,n+=1,t[n]>=`0`&&t[n]<=`9`))throw Error(`Invalid number at position ${e}`);if(n<t.length&&t[n]>=`1`&&t[n]<=`9`)for(;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&t[n]===`.`)for(r+=`.`,n+=1;n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(n<t.length&&(t[n]===`e`||t[n]===`E`))for(r+=t[n],n+=1,n<t.length&&(t[n]===`+`||t[n]===`-`)&&(r+=t[n],n+=1);n<t.length&&t[n]>=`0`&&t[n]<=`9`;)r+=t[n],n+=1;if(r===`-`)return-0;let i=Number.parseFloat(r);if(Number.isNaN(i))throw n=e,Error(`Invalid number '${r}' at position ${e}`);return i}function o(){if(r(),n>=t.length)throw Error(`Unexpected end of input at position ${n}`);let e=t[n];if(e===`{`)return c();if(e===`[`)return s();if(e===`"`)return i();if(`null`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),null;if(`true`.startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),!0;if(`false`.startsWith(t.substring(n,n+5)))return n+=Math.min(5,t.length-n),!1;if(e===`-`||e>=`0`&&e<=`9`)return a();throw Error(`Unexpected character '${e}' at position ${n}`)}function s(){if(t[n]!==`[`)throw Error(`Expected '[' at position ${n}, got '${t[n]}'`);let e=[];if(n+=1,r(),n>=t.length)return e;if(t[n]===`]`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length||(e.push(o()),r(),n>=t.length))return e;if(t[n]===`]`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or ']' at position ${n}, got '${t[n]}'`)}return e}function c(){if(t[n]!==`{`)throw Error(`Expected '{' at position ${n}, got '${t[n]}'`);let e={};if(n+=1,r(),n>=t.length)return e;if(t[n]===`}`)return n+=1,e;for(;n<t.length;){if(r(),n>=t.length)return e;let a=i();if(r(),n>=t.length)return e;if(t[n]!==`:`)throw Error(`Expected ':' at position ${n}, got '${t[n]}'`);if(n+=1,r(),n>=t.length||(e[a]=o(),r(),n>=t.length))return e;if(t[n]===`}`)return n+=1,e;if(t[n]===`,`){n+=1;continue}throw Error(`Expected ',' or '}' at position ${n}, got '${t[n]}'`)}return e}let l=o();if(r(),n<t.length)throw Error(`Unexpected character '${t[n]}' at position ${n}`);return l}function x(e){try{return e===void 0?null:b(e)}catch{return null}}var ee=/([A-Z]+)([A-Z][a-z0-9]+)/g,te=/([a-z0-9])([A-Z])/g,S=/[-_\s]+/g;function ne(e){return e.replace(ee,`$1_$2`).replace(te,`$1_$2`).replace(S,`_`).toLowerCase()}function re(e){let t=e.trim();return/[-_\s]/.test(t)?t.replace(S,`_`).toLowerCase().replace(/_+([a-z0-9])/g,(e,t)=>t.toUpperCase()):t}function ie(e,t){return t?.[e]||ne(e)}function ae(e,t){return t?.[e]||re(e)}function oe(e,t,n){let r={};for(let i in e)Object.hasOwn(e,i)&&(r[t(i,n)]=e[i]);return r}var se=`__lc_escaped__`;function ce(e){return`lc`in e||Object.keys(e).length===1&&`__lc_escaped__`in e}function C(e){return{[se]:e}}function le(e){return Object.keys(e).length===1&&`__lc_escaped__`in e}function ue(e){return typeof e==`object`&&!!e&&`lc_serializable`in e&&typeof e.toJSON==`function`}function de(e){let t;return t=typeof e==`object`&&e?`lc_id`in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??`Object`]:[typeof e],{lc:1,type:`not_implemented`,id:t}}function fe(e,t=new WeakSet){if(typeof e==`object`&&e&&!Array.isArray(e)){if(t.has(e))return de(e);if(ue(e))return e;t.add(e);let n=e;if(ce(n))return t.delete(e),C(n);let r={};for(let[e,i]of Object.entries(n))r[e]=fe(i,t);return t.delete(e),r}return Array.isArray(e)?e.map(e=>fe(e,t)):e}function pe(e){if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(le(t))return t[se];let n={};for(let[e,r]of Object.entries(t))n[e]=pe(r);return n}return Array.isArray(e)?e.map(e=>pe(e)):e}var me=s({Serializable:()=>ve,get_lc_unique_name:()=>_e});function he(e){return Array.isArray(e)?[...e]:{...e}}function ge(e,t){let n=he(e);for(let[e,r]of Object.entries(t)){let[t,...i]=e.split(`.`).reverse(),a=n;for(let e of i.reverse()){if(a[e]===void 0)break;a[e]=he(a[e]),a=a[e]}a[t]!==void 0&&(a[t]={lc:1,type:`secret`,id:[r]})}return n}function _e(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name==`function`&&(typeof t.lc_name!=`function`||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var ve=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,_e(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){this.lc_serializable_keys===void 0?this.lc_kwargs=e??{}:this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e)))}toJSON(){if(!this.lc_serializable||this.lc_kwargs instanceof e||typeof this.lc_kwargs!=`object`||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},n={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,`lc_aliases`,this)),Object.assign(n,Reflect.get(e,`lc_secrets`,this)),Object.assign(r,Reflect.get(e,`lc_attributes`,this));Object.keys(n).forEach(e=>{let t=this,n=r,[i,...a]=e.split(`.`).reverse();for(let e of a.reverse()){if(!(e in t)||t[e]===void 0)return;(!(e in n)||n[e]===void 0)&&(typeof t[e]==`object`&&t[e]!=null?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}i in t&&t[i]!==void 0&&(n[i]=n[i]||t[i])});let i={},a=new WeakSet;a.add(this);for(let[e,t]of Object.entries(r))i[e]=fe(t,a);let o=oe(Object.keys(n).length?ge(i,n):i,ie,t);return{lc:1,type:`constructor`,id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:`not_implemented`,id:this.lc_id}}};function ye(e){return typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&`source_type`in e&&(e.source_type===`url`||e.source_type===`base64`||e.source_type===`text`||e.source_type===`id`)}function be(e){return ye(e)&&e.source_type===`url`&&`url`in e&&typeof e.url==`string`}function xe(e){return ye(e)&&e.source_type===`base64`&&`data`in e&&typeof e.data==`string`}function Se(e){return ye(e)&&e.source_type===`text`&&`text`in e&&typeof e.text==`string`}function Ce(e){return ye(e)&&e.source_type===`id`&&`id`in e&&typeof e.id==`string`}function we(e){if(ye(e)){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url}};if(e.source_type===`base64`){if(!e.mime_type)throw Error(`mime_type key is required for base64 data.`);return{type:`image_url`,image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw Error(`Unsupported source type. Only 'url' and 'base64' are supported.`)}function Te(e){let t=e.split(`;`)[0].split(`/`);if(t.length!==2)throw Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);let n=t[0].trim(),r=t[1].trim();if(n===``||r===``)throw Error(`Invalid mime type: "${e}" - type or subtype is empty.`);let i={};for(let t of e.split(`;`).slice(1)){let n=t.split(`=`);if(n.length!==2)throw Error(`Invalid parameter syntax in mime type: "${e}".`);let r=n[0].trim(),a=n[1].trim();if(r===``)throw Error(`Invalid parameter syntax in mime type: "${e}".`);i[r]=a}return{type:n,subtype:r,parameters:i}}function Ee({dataUrl:e,asTypedArray:t=!1}){let n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let e=t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2];return{mime_type:r,data:e}}}function De(e,t){if(e.type===`text`){if(!t.fromStandardTextBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type===`image`){if(!t.fromStandardImageBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type===`audio`){if(!t.fromStandardAudioBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type===`file`){if(!t.fromStandardFileBlock)throw Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function w(e,t){return T(e)&&e.type===t}function T(e){return typeof e==`object`&&!!e}function Oe(e){return Array.isArray(e)}function E(e){return typeof e==`string`}function D(e){return typeof e==`number`}function ke(e){return e instanceof Uint8Array}function Ae(e){try{return JSON.parse(e)}catch{return}}var je=e=>e();function Me(e){if(e.type===`char_location`&&E(e.document_title)&&D(e.start_char_index)&&D(e.end_char_index)&&E(e.cited_text)){let{document_title:t,start_char_index:n,end_char_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`char`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`page_location`&&E(e.document_title)&&D(e.start_page_number)&&D(e.end_page_number)&&E(e.cited_text)){let{document_title:t,start_page_number:n,end_page_number:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`page`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`content_block_location`&&E(e.document_title)&&D(e.start_block_index)&&D(e.end_block_index)&&E(e.cited_text)){let{document_title:t,start_block_index:n,end_block_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`block`,title:t??void 0,startIndex:n,endIndex:r,citedText:i}}if(e.type===`web_search_result_location`&&E(e.url)&&E(e.title)&&E(e.encrypted_index)&&E(e.cited_text)){let{url:t,title:n,encrypted_index:r,cited_text:i,...a}=e;return{...a,type:`citation`,source:`url`,url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:i}}if(e.type===`search_result_location`&&E(e.source)&&E(e.title)&&D(e.start_block_index)&&D(e.end_block_index)&&E(e.cited_text)){let{source:t,title:n,start_block_index:r,end_block_index:i,cited_text:a,...o}=e;return{...o,type:`citation`,source:`search`,url:t,title:n??void 0,startIndex:r,endIndex:i,citedText:a}}}function Ne(e){if(w(e,`document`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`file`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`file`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`file`,fileId:e.source.file_id};if(e.source.type===`text`&&E(e.source.data))return{type:`file`,mimeType:String(e.source.media_type??`text/plain`),data:e.source.data}}else if(w(e,`image`)&&T(e.source)&&`type`in e.source){if(e.source.type===`base64`&&E(e.source.media_type)&&E(e.source.data))return{type:`image`,mimeType:e.source.media_type,data:e.source.data};if(e.source.type===`url`&&E(e.source.url))return{type:`image`,url:e.source.url};if(e.source.type===`file`&&E(e.source.file_id))return{type:`image`,fileId:e.source.file_id}}}function Pe(e){function*t(){for(let t of e){let e=Ne(t);e?yield e:yield t}}return Array.from(t())}function Fe(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`text`)&&E(n.text)){let{text:e,citations:t,...r}=n;if(Oe(t)&&t.length){let n=t.reduce((e,t)=>{let n=Me(t);return n?[...e,n]:e},[]);yield{...r,type:`text`,text:e,annotations:n};continue}else{yield{...r,type:`text`,text:e};continue}}else if(w(n,`thinking`)&&E(n.thinking)){let{thinking:e,signature:t,...r}=n;yield{...r,type:`reasoning`,reasoning:e,signature:t};continue}else if(w(n,`redacted_thinking`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`tool_use`)&&E(n.name)&&E(n.id)){yield{type:`tool_call`,id:n.id,name:n.name,args:n.input};continue}else if(w(n,`input_json_delta`)){if(Le(e)&&e.tool_call_chunks?.length){let t=e.tool_call_chunks[0];yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if(w(n,`server_tool_use`)&&E(n.name)&&E(n.id)){let{name:e,id:t}=n;if(e===`web_search`){yield{id:t,type:`server_tool_call`,name:`web_search`,args:{query:je(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.query))return n.input.query;if(E(n.partial_json)){let e=Ae(n.partial_json);if(e?.query)return e.query}return``})}};continue}else if(n.name===`code_execution`){yield{id:t,type:`server_tool_call`,name:`code_execution`,args:{code:je(()=>{if(typeof n.input==`string`)return n.input;if(T(n.input)&&E(n.input.code))return n.input.code;if(E(n.partial_json)){let e=Ae(n.partial_json);if(e?.code)return e.code}return``})}};continue}}else if(w(n,`web_search_tool_result`)&&E(n.tool_use_id)&&Oe(n.content)){let{content:e,tool_use_id:t}=n;yield{type:`server_tool_call_result`,name:`web_search`,toolCallId:t,status:`success`,output:{urls:e.reduce((e,t)=>w(t,`web_search_result`)?[...e,t.url]:e,[])}};continue}else if(w(n,`code_execution_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`code_execution`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`mcp_tool_use`)){yield{id:n.id,type:`server_tool_call`,name:`mcp_tool_use`,args:n.input};continue}else if(w(n,`mcp_tool_result`)&&E(n.tool_use_id)&&T(n.content)){yield{type:`server_tool_call_result`,name:`mcp_tool_use`,toolCallId:n.tool_use_id,status:`success`,output:n.content};continue}else if(w(n,`container_upload`)){yield{type:`server_tool_call`,name:`container_upload`,args:n.input};continue}else if(w(n,`search_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else if(w(n,`tool_result`)){yield{id:n.id,type:`non_standard`,value:n};continue}else{let e=Ne(n);if(e){yield e;continue}}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Ie={translateContent:Fe,translateContentChunk:Fe};function Le(e){return typeof e?._getType==`function`&&typeof e.concat==`function`&&e._getType()===`ai`}function Re(e){return be(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:xe(e)?{type:e.type,mimeType:e.mime_type??`application/octet-stream`,data:e.data,metadata:e.metadata}:Ce(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function ze(e){return e.map(Re)}function Be(e){return!!(w(e,`image_url`)&&T(e.image_url)||w(e,`input_audio`)&&T(e.input_audio)||w(e,`file`)&&T(e.file))}function Ve(e){if(w(e,`image_url`)&&T(e.image_url)&&E(e.image_url.url)){let t=Ee({dataUrl:e.image_url.url});return t?{type:`image`,mimeType:t.mime_type,data:t.data}:{type:`image`,url:e.image_url.url}}else if(w(e,`input_audio`)&&T(e.input_audio)&&E(e.input_audio.data)&&E(e.input_audio.format))return{type:`audio`,data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};else if(w(e,`file`)&&T(e.file)&&E(e.file.data)){let t=Ee({dataUrl:e.file.data});if(t)return{type:`file`,data:t.data,mimeType:t.mime_type};if(E(e.file.file_id))return{type:`file`,fileId:e.file.file_id}}return e}function He(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...We(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function Ue(e){let t=[];typeof e.content==`string`?e.content.length>0&&t.push({type:`text`,text:e.content}):t.push(...We(e.content));for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}function We(e){let t=[];for(let n of e)Be(n)?t.push(Ve(n)):t.push(n);return t}function Ge(e){if(e.type===`url_citation`){let{url:t,title:n,start_index:r,end_index:i}=e;return{type:`citation`,url:t,title:n,startIndex:r,endIndex:i}}if(e.type===`file_citation`){let{file_id:t,filename:n,index:r}=e;return{type:`citation`,title:n,startIndex:r,endIndex:r,fileId:t}}return e}function Ke(e){function*t(){T(e.additional_kwargs?.reasoning)&&Oe(e.additional_kwargs.reasoning.summary)&&(yield{type:`reasoning`,reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>T(t)&&E(t.text)?`${e}${t.text}`:e,``)});let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t)if(w(e,`text`)){let{text:t,annotations:n,phase:r,extras:i,...a}=e,o=T(i)?{...i}:{};E(r)&&(o.phase=r);let s=Object.keys(o).length>0?{extras:o}:{};Array.isArray(n)?yield{...a,...s,type:`text`,text:String(t),annotations:n.map(Ge)}:yield{...a,...s,type:`text`,text:String(t)}}for(let t of e.tool_calls??[])yield{type:`tool_call`,id:t.id,name:t.name,args:t.args};if(T(e.additional_kwargs)&&Oe(e.additional_kwargs.tool_outputs))for(let t of e.additional_kwargs.tool_outputs){if(w(t,`web_search_call`)){let e={};if(T(t.action)&&E(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:`server_tool_call`,name:`web_search`,args:e},t.status===`completed`||t.status===`failed`){let e={};T(t.action)&&(e.action=t.action),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:e}}continue}else if(w(t,`file_search_call`)){yield{id:t.id,type:`server_tool_call`,name:`file_search`,args:{queries:Oe(t.queries)?t.queries:[]}},(t.status===`completed`||t.status===`failed`)&&(yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:`error`,output:Oe(t.results)?{results:t.results}:{}});continue}else if(w(t,`computer_call`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`code_interpreter_call`)){if(E(t.code)&&(yield{id:t.id,type:`server_tool_call`,name:`code_interpreter`,args:{code:t.code}}),Oe(t.outputs)){let e=je(()=>{if(t.status!==`in_progress`){if(t.status===`completed`)return 0;if(t.status===`incomplete`)return 127;if(t.status!==`interpreting`&&t.status===`failed`)return 1}});for(let n of t.outputs)if(w(n,`logs`)){yield{type:`server_tool_call_result`,toolCallId:t.id??``,status:`success`,output:{type:`code_interpreter_output`,returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(n.logs),stdout:[0,void 0].includes(e)?String(n.logs):void 0}};continue}}continue}else if(w(t,`mcp_call`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_call`,args:t.input};continue}else if(w(t,`mcp_list_tools`)){yield{id:t.id,type:`server_tool_call`,name:`mcp_list_tools`,args:t.input};continue}else if(w(t,`mcp_approval_request`)){yield{type:`non_standard`,value:t};continue}else if(w(t,`tool_search_call`)){let e={};T(t.arguments)&&Object.assign(e,t.arguments);let n={};E(t.execution)&&(n.execution=t.execution),E(t.status)&&(n.status=t.status),E(t.call_id)&&(n.call_id=t.call_id),yield{id:E(t.id)?t.id:``,type:`server_tool_call`,name:`tool_search`,args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}else if(w(t,`tool_search_output`)){let e={name:`tool_search`};E(t.execution)&&(e.execution=t.execution),yield{type:`server_tool_call_result`,toolCallId:E(t.id)?t.id:``,status:t.status===`completed`?`success`:t.status===`failed`?`error`:`success`,output:{tools:Oe(t.tools)?t.tools:[]},extras:e};continue}else if(w(t,`image_generation_call`)){E(t.result)&&(yield{type:`image`,mimeType:`image/png`,data:t.result,id:E(t.id)?t.id:void 0,metadata:{status:E(t.status)?t.status:void 0}}),yield{type:`non_standard`,value:t};continue}T(t)&&(yield{type:`non_standard`,value:t})}}return Array.from(t())}function qe(e){function*t(){yield*Ke(e);for(let t of e.tool_call_chunks??[])yield{type:`tool_call_chunk`,id:t.id,name:t.name,args:t.args}}return Array.from(t())}var Je={translateContent:e=>typeof e.content==`string`?He(e):Ke(e),translateContentChunk:e=>typeof e.content==`string`?Ue(e):qe(e)};function Ye(e){return typeof e==`object`&&!!e&&`type`in e&&`content`in e&&(typeof e.content==`string`||Array.isArray(e.content))}function Xe(e,t=`pretty`){return t===`pretty`?Ze(e):JSON.stringify(e)}function Ze(e){let t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),i=`=`.repeat(r),a=n.length%2==0?i:`${i}=`;if(t.push(`${i}${n}${a}`),e.type===`ai`){let n=e;if(n.tool_calls&&n.tool_calls.length>0){t.push(`Tool Calls:`);for(let e of n.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(` Args:`);for(let[n,r]of Object.entries(e.args))t.push(` ${n}: ${typeof r==`object`?JSON.stringify(r):r}`)}}}if(e.type===`tool`){let n=e;n.name&&t.push(`Name: ${n.name}`)}return typeof e.content==`string`&&e.content.trim()&&(t.length>1&&t.push(``),t.push(e.content)),t.join(`
|
|
5
5
|
`)}var Qe=Symbol.for(`langchain.message`);function $e(e){return Array.isArray(e)?e:typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:e==null?[]:[e]}function et(e,t){if(typeof e==`string`)return e===``?t:typeof t==`string`?e+t:Array.isArray(t)&&t.length===0?e:Array.isArray(t)&&t.some(e=>ye(e))?[{type:`text`,source_type:`text`,text:e},...t]:[{type:`text`,text:e},...t];if(Array.isArray(t)){let n=$e(e);return pt(n,t)??[...n,...t]}else if(t===``)return e;else if(Array.isArray(e)&&e.some(e=>ye(e)))return[...e,{type:`file`,source_type:`text`,text:t}];else return[...$e(e),{type:`text`,text:t}]}function tt(e,t){return e===`error`||t===`error`?`error`:`success`}function nt(e,t){function n(e,r){if(typeof e!=`object`||!e||e===void 0)return e;if(r>=t)return Array.isArray(e)?`[Array]`:`[Object]`;if(Array.isArray(e))return e.map(e=>n(e,r+1));let i={};for(let t of Object.keys(e))i[t]=n(e[t],r+1);return i}return JSON.stringify(n(e,0),null,2)}var rt=class extends ve{lc_namespace=[`langchain_core`,`messages`];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:`additional_kwargs`,response_metadata:`response_metadata`}}[Qe]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){let t=typeof e==`string`||Array.isArray(e)?{content:e}:e;t.additional_kwargs||={},t.response_metadata||={},super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:`v1`,...t.response_metadata}):t.content===void 0?(this.content=[],this.response_metadata=t.response_metadata):(this.content=t.content??[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content==`string`?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:``).join(``):``}get contentBlocks(){let e=typeof this.content==`string`?[{type:`text`,text:this.content}]:this.content;return[ze,We,Pe].reduce((e,t)=>t(e),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return`BaseMessage`}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e==`object`&&!!e&&Qe in e&&e[Qe]===!0&&Ye(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for(`nodejs.util.inspect.custom`)](e){if(e===null)return this;let t=nt(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e=`pretty`){return Xe(this,e)}};function it(e){return Array.isArray(e)&&e.every(e=>typeof e.index==`number`)}var at=[`index`,`created`,`timestamp`];function ot(e,t,n){let r=n?.ignoreKeys??at;if(e==null&&t==null)return;if(e==null||t==null)return e??t;let i={...e};for(let[e,a]of Object.entries(t))if(i[e]==null)i[e]=a;else if(a==null)continue;else if(typeof i[e]!=typeof a||Array.isArray(i[e])!==Array.isArray(a))throw Error(`field[${e}] already exists in the message chunk, but with a different type.`);else if(typeof i[e]==`string`){if(e===`type`)continue;if([`id`,`name`,`output_version`,`model_provider`].includes(e))a&&(i[e]=a);else if(r.includes(e))continue;else i[e]+=a}else if(typeof i[e]==`number`){if(r.includes(e))continue;i[e]=i[e]+a}else if(typeof i[e]==`object`&&!Array.isArray(i[e]))i[e]=ot(i[e],a,n);else if(Array.isArray(i[e]))i[e]=pt(i[e],a,n);else if(i[e]===a)continue;else console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`);return i}function st(e){return typeof e==`number`||typeof e==`string`}function ct(e){return typeof e!=`object`||!e||!(`index`in e)?!1:st(e.index)}function lt(e){if(typeof e!=`object`||!e||!(`id`in e))return!1;let t=e.id;return t!=null&&t!==``}function ut(e){return e.endsWith(`_delta`)?e.slice(0,-6):e}function dt(e,t){return typeof e!=`object`||!e||typeof t!=`object`||!t||!(`type`in e)||!(`type`in t)?!1:typeof e.type==`string`&&typeof t.type==`string`&&ut(e.type)!==ut(t.type)}function ft(e,t){let n=ct(t),r=lt(t);return!n&&!r?-1:e.findIndex(e=>{let i=ct(e),a=lt(e);return n&&i?e.index!==t.index||dt(e,t)?!1:a&&r?e.id===t.id:!0:!n&&!i&&r&&a?e.id===t.id:!1})}function pt(e,t,n){if(!(e==null&&t==null)){if(e==null||t==null)return e||t;{let r=[...e];for(let e of t){let t=ft(r,e);if(t!==-1)r[t]=ot(r[t],e,n);else if(typeof e==`object`&&e&&`text`in e&&e.text===``)continue;else r.push(e)}return r}}}function mt(e,t,n){if(!(e==null&&t==null)){if(e==null||t==null)return e??t;if(typeof e!=typeof t)throw Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if(typeof e==`string`&&typeof t==`string`)return e+t;if(Array.isArray(e)&&Array.isArray(t))return pt(e,t,n);if(typeof e==`object`&&typeof t==`object`)return ot(e,t,n);if(e===t)return e;throw Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}}var ht=class e extends rt{static isInstance(t){if(!super.isInstance(t))return!1;let n=Object.getPrototypeOf(t);for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function gt(e){return typeof e.role==`string`}function _t(e){return typeof e?._getType==`function`}function vt(e){return ht.isInstance(e)}var yt=s({ToolMessage:()=>xt,ToolMessageChunk:()=>St,defaultToolCallParser:()=>Ct,isDirectToolOutput:()=>bt,isToolMessage:()=>wt,isToolMessageChunk:()=>Tt});function bt(e){return typeof e==`object`&&!!e&&`lc_direct_tool_output`in e&&e.lc_direct_tool_output===!0}var xt=class extends rt{static lc_name(){return`ToolMessage`}get lc_aliases(){return{tool_call_id:`tool_call_id`}}lc_direct_tool_output=!0;type=`tool`;status;tool_call_id;metadata;artifact;constructor(e,t,n){let r=typeof e==`string`||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(r),this.tool_call_id=r.tool_call_id,this.artifact=r.artifact,this.status=r.status,this.metadata=r.metadata}static isInstance(e){return super.isInstance(e)&&e.type===`tool`}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},St=class extends ht{type=`tool`;tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return`ToolMessageChunk`}concat(e){let t=this.constructor;return new t({content:et(this.content,e.content),additional_kwargs:ot(this.additional_kwargs,e.additional_kwargs),response_metadata:ot(this.response_metadata,e.response_metadata),artifact:mt(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:tt(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function Ct(e){let t=[],n=[];for(let r of e)if(r.function){let e=r.function.name;try{let n=JSON.parse(r.function.arguments);t.push({name:e||``,args:n||{},id:r.id})}catch{n.push({name:e,args:r.function.arguments,id:r.id,error:`Malformed args.`})}}else continue;return[t,n]}function wt(e){return typeof e==`object`&&!!e&&`getType`in e&&typeof e.getType==`function`&&e.getType()===`tool`}function Tt(e){return e._getType()===`tool`}function Et(e){switch(e){case`csv`:return`text/csv`;case`doc`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`docx`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`html`:return`text/html`;case`md`:return`text/markdown`;case`pdf`:return`application/pdf`;case`txt`:return`text/plain`;case`xls`:return`application/vnd.ms-excel`;case`xlsx`:return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;case`gif`:return`image/gif`;case`jpeg`:return`image/jpeg`;case`jpg`:return`image/jpeg`;case`png`:return`image/png`;case`webp`:return`image/webp`;case`flv`:return`video/flv`;case`mkv`:return`video/mkv`;case`mov`:return`video/mov`;case`mp4`:return`video/mp4`;case`mpeg`:return`video/mpeg`;case`mpg`:return`video/mpg`;case`three_gp`:return`video/three_gp`;case`webm`:return`video/webm`;case`wmv`:return`video/wmv`;default:return`application/octet-stream`}}function Dt(e){if(T(e.document)&&T(e.document.source)){let t=Et(T(e.document)&&E(e.document.format)?e.document.format:``);if(T(e.document.source)){if(T(e.document.source.s3Location)&&E(e.document.source.s3Location.uri))return{type:`file`,mimeType:t,fileId:e.document.source.s3Location.uri};if(ke(e.document.source.bytes))return{type:`file`,mimeType:t,data:e.document.source.bytes};if(E(e.document.source.text))return{type:`file`,mimeType:t,data:Buffer.from(e.document.source.text).toString(`base64`)};if(Oe(e.document.source.content))return{type:`file`,mimeType:t,data:e.document.source.content.reduce((e,t)=>T(t)&&E(t.text)?e+t.text:e,``)}}}return{type:`non_standard`,value:e}}function Ot(e){if(w(e,`image`)&&T(e.image)){let t=Et(T(e.image)&&E(e.image.format)?e.image.format:``);if(T(e.image.source)){if(T(e.image.source.s3Location)&&E(e.image.source.s3Location.uri))return{type:`image`,mimeType:t,fileId:e.image.source.s3Location.uri};if(ke(e.image.source.bytes))return{type:`image`,mimeType:t,data:e.image.source.bytes}}}return{type:`non_standard`,value:e}}function kt(e){if(w(e,`video`)&&T(e.video)){let t=Et(T(e.video)&&E(e.video.format)?e.video.format:``);if(T(e.video.source)){if(T(e.video.source.s3Location)&&E(e.video.source.s3Location.uri))return{type:`video`,mimeType:t,fileId:e.video.source.s3Location.uri};if(ke(e.video.source.bytes))return{type:`video`,mimeType:t,data:e.video.source.bytes}}}return{type:`non_standard`,value:e}}function At(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let e of t){if(w(e,`cache_point`)){yield{type:`non_standard`,value:e};continue}else if(w(e,`citations_content`)&&T(e.citationsContent)){yield{type:`text`,text:Oe(e.citationsContent.content)?e.citationsContent.content.reduce((e,t)=>T(t)&&E(t.text)?e+t.text:e,``):``,annotations:Oe(e.citationsContent.citations)?e.citationsContent.citations.reduce((e,t)=>{if(T(t)){let n=Oe(t.sourceContent)?t.sourceContent.reduce((e,t)=>T(t)&&E(t.text)?e+t.text:e,``):``,r=je(()=>{if(T(t.location)){let e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if(T(e))return{source:D(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:D(e.start)?e.start:void 0,endIndex:D(e.end)?e.end:void 0}}return{}});e.push({type:`citation`,citedText:n,...r})}return e},[]):[]};continue}else if(w(e,`document`)&&T(e.document)){yield Dt(e);continue}else if(w(e,`guard_content`)){yield{type:`non_standard`,value:e};continue}else if(w(e,`image`)&&T(e.image)){yield Ot(e);continue}else if(w(e,`reasoning_content`)&&E(e.reasoningText)){yield{type:`reasoning`,reasoning:e.reasoningText};continue}else if(w(e,`text`)&&E(e.text)){yield{type:`text`,text:e.text};continue}else if(w(e,`tool_result`)){yield{type:`non_standard`,value:e};continue}else if(w(e,`tool_call`))continue;else if(w(e,`video`)&&T(e.video)){yield kt(e);continue}yield{type:`non_standard`,value:e}}}return Array.from(t())}var jt={translateContent:At,translateContentChunk:At};function Mt(e){let t=[],n=e.additional_kwargs?.reasoning_content;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Nt={translateContent:Mt,translateContentChunk:Mt};function Pt(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`text`)&&E(n.text)){yield{type:`text`,text:n.text};continue}else if(w(n,`thinking`)&&E(n.thinking)){yield{type:`reasoning`,reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(w(n,`inlineData`)&&T(n.inlineData)&&E(n.inlineData.mimeType)&&E(n.inlineData.data)){yield{type:`file`,mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(w(n,`functionCall`)&&T(n.functionCall)&&E(n.functionCall.name)&&T(n.functionCall.args)){yield{type:`tool_call`,id:e.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(w(n,`functionResponse`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`fileData`)&&T(n.fileData)&&E(n.fileData.mimeType)&&E(n.fileData.fileUri)){yield{type:`file`,mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(w(n,`executableCode`)){yield{type:`non_standard`,value:n};continue}else if(w(n,`codeExecutionResult`)){yield{type:`non_standard`,value:n};continue}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Ft={translateContent:Pt,translateContentChunk:Pt};function It(e){function*t(){let t=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content;for(let n of t){if(w(n,`reasoning`)&&E(n.reasoning)){let r=je(()=>{let r=t.indexOf(n);if(Oe(e.additional_kwargs?.signatures)&&r>=0)return e.additional_kwargs.signatures.at(r)});E(r)?yield{type:`reasoning`,reasoning:n.reasoning,signature:r}:yield{type:`reasoning`,reasoning:n.reasoning};continue}else if(w(n,`thinking`)&&E(n.thinking)){yield{type:`reasoning`,reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(w(n,`text`)&&E(n.text)){yield{type:`text`,text:n.text};continue}else if(w(n,`image_url`)){if(E(n.image_url))if(n.image_url.startsWith(`data:`)){let e=n.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:`image`,data:e[2],mimeType:e[1]}:yield{type:`image`,url:n.image_url}}else yield{type:`image`,url:n.image_url};continue}else if(w(n,`media`)&&E(n.mimeType)&&E(n.data)){yield{type:`file`,mimeType:n.mimeType,data:n.data};continue}yield{type:`non_standard`,value:n}}}return Array.from(t())}var Lt={translateContent:It,translateContentChunk:It};function Rt(e){let t=[],n=e.additional_kwargs?.reasoning;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`){let n=e.content,r=n.match(/<think>([\s\S]*?)<\/think>/);if(r){let e=r[1].trim();e.length>0&&t.push({type:`reasoning`,reasoning:e}),n=n.replace(/<think>[\s\S]*?<\/think>/,``).trim()}n.length>0&&t.push({type:`text`,text:n})}else for(let n of e.content)if(typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)){let e=n.text,r=e.match(/<think>([\s\S]*?)<\/think>/);if(r){let n=r[1].trim();n.length>0&&t.push({type:`reasoning`,reasoning:n}),e=e.replace(/<think>[\s\S]*?<\/think>/,``).trim()}e.length>0&&t.push({type:`text`,text:e})}for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var zt={translateContent:Rt,translateContentChunk:Rt};function Bt(e){let t=[],n=e.additional_kwargs?.reasoning_content;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Vt={translateContent:Bt,translateContentChunk:Bt};function Ht(e){let t=[],n=e.additional_kwargs?.reasoning_details,r=!1;if(Array.isArray(n)&&n.length>0)for(let e of n){if(typeof e!=`object`||!e)continue;let n=e.type;if(n===`reasoning.summary`){let n=e.summary;E(n)&&n.length>0&&(t.push({type:`reasoning`,reasoning:n}),r=!0)}else if(n===`reasoning.text`){let n=e.text;E(n)&&n.length>0&&(t.push({type:`reasoning`,reasoning:n}),r=!0)}}if(!r){let n=e.additional_kwargs?.reasoning_content;E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n})}if(typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Ut={translateContent:Ht,translateContentChunk:Ht};function Wt(e){let t=[];if(T(e.additional_kwargs?.reasoning)){let n=e.additional_kwargs.reasoning;if(Oe(n.summary)){let e=n.summary.reduce((e,t)=>T(t)&&E(t.text)?`${e}${t.text}`:e,``);e.length>0&&t.push({type:`reasoning`,reasoning:e})}}let n=e.additional_kwargs?.reasoning_content;if(E(n)&&n.length>0&&t.push({type:`reasoning`,reasoning:n}),typeof e.content==`string`)e.content.length>0&&t.push({type:`text`,text:e.content});else for(let n of e.content)typeof n==`object`&&`type`in n&&n.type===`text`&&`text`in n&&E(n.text)&&t.push({type:`text`,text:n.text});for(let n of e.tool_calls??[])t.push({type:`tool_call`,id:n.id,name:n.name,args:n.args});return t}var Gt={translateContent:Wt,translateContentChunk:Wt};function Kt(e){function*t(){let t=je(()=>{if(typeof e.content==`string`)return e.additional_kwargs.originalTextContentBlock?[{...e.additional_kwargs.originalTextContentBlock,type:`text`}]:[{type:`text`,text:e.content}];{let t=e.additional_kwargs?.originalTextContentBlock;if(t?.thoughtSignature&&!e.content.some(e=>`thoughtSignature`in e)){let n=[...e.content];for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.type===`text`&&!r.thought)return r.thoughtSignature=t.thoughtSignature,n}}return e.content}});for(let n of t){let t=je(()=>w(n,`text`)&&E(n.text)?{type:`text`,text:n.text}:w(n,`inlineData`)&&T(n.inlineData)&&E(n.inlineData.mimeType)&&E(n.inlineData.data)?{type:`file`,mimeType:n.inlineData.mimeType,data:n.inlineData.data}:w(n,`functionCall`)&&T(n.functionCall)&&E(n.functionCall.name)&&T(n.functionCall.args)?{type:`tool_call`,id:e.id,name:n.functionCall.name,args:n.functionCall.args}:w(n,`functionResponse`)?{type:`non_standard`,value:n}:w(n,`fileData`)&&T(n.fileData)&&E(n.fileData.mimeType)&&E(n.fileData.fileUri)?{type:`file`,mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:(w(n,`executableCode`)||w(n,`codeExecutionResult`),{type:`non_standard`,value:n})),r=je(()=>`thought`in n&&n.thought?{type:`reasoning`,reasoning:t.type===`text`?t.text:``,reasoningContentBlock:t}:t),i={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...r};for(let e in i)i[e]===void 0&&delete i[e];yield i}}return Array.from(t())}globalThis.lc_block_translators_registry??=new Map([[`anthropic`,Ie],[`bedrock-converse`,jt],[`deepseek`,Nt],[`google`,{translateContent:Kt,translateContentChunk:Kt}],[`google-genai`,Ft],[`google-vertexai`,Lt],[`groq`,zt],[`ollama`,Vt],[`openai`,Je],[`openrouter`,Ut],[`xai`,Gt]]);function qt(e){return globalThis.lc_block_translators_registry.get(e)}function Jt(e,t){return ot(e,t)??{}}function Yt(e,t){let n={};return(e?.audio!==void 0||t?.audio!==void 0)&&(n.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(n.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(n.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(n.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(n.text=(e?.text??0)+(t?.text??0)),n}function Xt(e,t){let n={...Yt(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function Zt(e,t){let n={...Yt(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function Qt(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:Xt(e?.input_token_details,t?.input_token_details),output_token_details:Zt(e?.output_token_details,t?.output_token_details)}}var $t=class extends rt{type=`ai`;tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:`tool_calls`,invalid_tool_calls:`invalid_tool_calls`,usage_metadata:`usage_metadata`}}constructor(e){let t;if(typeof e==`string`||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;let n=t.additional_kwargs?.tool_calls,r=t.tool_calls;n!=null&&n.length>0&&(r===void 0||r.length===0)&&console.warn([`New LangChain packages are available that more efficiently handle`,`tool calling.
|
|
6
6
|
|
|
7
7
|
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(` `));try{if(n!=null&&r===void 0){let[e,r]=Ct(n);t.tool_calls=e??[],t.invalid_tool_calls=r??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&`output_version`in t.response_metadata&&t.response_metadata.output_version===`v1`&&t.content!==void 0&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){if(t.tool_calls){let e=t.tool_calls.filter(e=>!t.contentBlocks?.some(t=>t.type===`tool_call`&&t.id===e.id&&t.name===e.name));t.contentBlocks.push(...e.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args})))}let e=t.contentBlocks.filter(e=>e.type===`tool_call`).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=[...t.tool_calls??[],...e.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args}))])}}super(t),typeof t!=`string`&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return`AIMessage`}get contentBlocks(){if(this.response_metadata&&`output_version`in this.response_metadata&&this.response_metadata.output_version===`v1`)return this.content;if(this.response_metadata&&`model_provider`in this.response_metadata&&typeof this.response_metadata.model_provider==`string`){let e=qt(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({type:`tool_call`,id:e.id,name:e.name,args:e.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type===`ai`}};function en(e){return e._getType()===`ai`}function tn(e){return e._getType()===`ai`}var nn=class extends ht{type=`ai`;tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e==`string`||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata===void 0?void 0:e.usage_metadata};else{let n=Pn(e.tool_call_chunks??[]);t={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:e.usage_metadata===void 0?void 0:e.usage_metadata}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:`tool_calls`,invalid_tool_calls:`invalid_tool_calls`,tool_call_chunks:`tool_call_chunks`,usage_metadata:`usage_metadata`}}static lc_name(){return`AIMessageChunk`}get contentBlocks(){if(this.response_metadata&&`output_version`in this.response_metadata&&this.response_metadata.output_version===`v1`)return this.content;if(this.response_metadata&&`model_provider`in this.response_metadata&&typeof this.response_metadata.model_provider==`string`){let e=qt(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!=`string`){let t=this.content.filter(e=>e.type===`tool_call`).map(e=>e.id);for(let n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:`tool_call`,id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let t={content:et(this.content,e.content),additional_kwargs:ot(this.additional_kwargs,e.additional_kwargs),response_metadata:Jt(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=pt(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(t.tool_call_chunks=n)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){let n=pt(this.tool_calls,e.tool_calls);n!==void 0&&n.length>0&&(t.tool_calls=n)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Qt(this.usage_metadata,e.usage_metadata));let n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type===`ai`}},rn=class e extends rt{static lc_name(){return`ChatMessage`}type=`generic`;role;static _chatMessageClass(){return e}constructor(e,t){(typeof e==`string`||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type===`generic`}get _printableFields(){return{...super._printableFields,role:this.role}}},an=class extends ht{static lc_name(){return`ChatMessageChunk`}type=`generic`;role;constructor(e,t){(typeof e==`string`||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){let t=this.constructor;return new t({content:et(this.content,e.content),additional_kwargs:ot(this.additional_kwargs,e.additional_kwargs),response_metadata:ot(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 on(e){return e._getType()===`generic`}function sn(e){return e._getType()===`generic`}var cn=class extends rt{static lc_name(){return`FunctionMessage`}type=`function`;name;constructor(e){super(e),this.name=e.name}},ln=class extends ht{static lc_name(){return`FunctionMessageChunk`}type=`function`;concat(e){let t=this.constructor;return new t({content:et(this.content,e.content),additional_kwargs:ot(this.additional_kwargs,e.additional_kwargs),response_metadata:ot(this.response_metadata,e.response_metadata),name:this.name??``,id:this.id??e.id})}};function un(e){return e._getType()===`function`}function dn(e){return e._getType()===`function`}var fn=class extends rt{static lc_name(){return`HumanMessage`}type=`human`;constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type===`human`}},pn=class extends ht{static lc_name(){return`HumanMessageChunk`}type=`human`;constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:et(this.content,e.content),additional_kwargs:ot(this.additional_kwargs,e.additional_kwargs),response_metadata:ot(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`human`}};function mn(e){return e.getType()===`human`}function hn(e){return e.getType()===`human`}var gn=class extends rt{type=`remove`;id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type===`remove`}},_n=class e extends rt{static lc_name(){return`SystemMessage`}type=`system`;constructor(e){super(e)}concat(t){if(typeof t==`string`)return new e({content:et(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(e.isInstance(t))return new e({content:et(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw Error(`Unexpected chunk type for system message`)}static isInstance(e){return super.isInstance(e)&&e.type===`system`}},vn=class extends ht{static lc_name(){return`SystemMessageChunk`}type=`system`;constructor(e){super(e)}concat(e){let t=this.constructor;return new t({content:et(this.content,e.content),additional_kwargs:ot(this.additional_kwargs,e.additional_kwargs),response_metadata:ot(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type===`system`}};function yn(e){return e._getType()===`system`}function bn(e){return e._getType()===`system`}function xn(e){return e.isCustomTool===!0}var Sn=e=>e();function Cn(e){return g(e)?e:typeof e.id==`string`&&e.type===`function`&&typeof e.function==`object`&&e.function!==null&&`arguments`in e.function&&typeof e.function.arguments==`string`&&`name`in e.function&&typeof e.function.name==`string`?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:`tool_call`}:e}function wn(e){return typeof e==`object`&&!!e&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs==`object`}function Tn(e){let t,n;if(wn(e)){let r=e.id.at(-1);t=r===`HumanMessage`||r===`HumanMessageChunk`?`user`:r===`AIMessage`||r===`AIMessageChunk`?`assistant`:r===`SystemMessage`||r===`SystemMessageChunk`?`system`:r===`FunctionMessage`||r===`FunctionMessageChunk`?`function`:r===`ToolMessage`||r===`ToolMessageChunk`?`tool`:`unknown`,n=e.kwargs}else{let{type:r,...i}=e;t=r,n=i}if(t===`human`||t===`user`)return new fn(n);if(t===`ai`||t===`assistant`){let{tool_calls:e,...t}=n;if(!Array.isArray(e))return new $t(n);let r=e.map(Cn);return new $t({...t,tool_calls:r})}else if(t===`system`)return new _n(n);else if(t===`developer`)return new _n({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:`developer`}});else if(t===`tool`&&`tool_call_id`in n)return new xt({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});else if(t===`remove`&&`id`in n&&typeof n.id==`string`)return new gn({...n,id:n.id});else throw d(Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),`MESSAGE_COERCION_FAILURE`)}function En(e){if(typeof e==`string`)return new fn(e);if(_t(e))return e;if(Array.isArray(e)){let[t,n]=e;return Tn({type:t,content:n})}else if(gt(e)){let{role:t,...n}=e;return Tn({...n,type:t})}else return Tn(e)}function Dn(e){if(typeof e==`string`)return e;switch(e.type){case`text`:return e.text??``;case`text-plain`:return e.text??`[text-plain file]`;case`image`:case`image_url`:return`[image]`;case`audio`:case`input_audio`:return`[audio]`;case`video`:return`[video]`;case`file`:return`[file]`;case`reasoning`:case`tool_call`:case`tool_call_chunk`:case`invalid_tool_call`:case`server_tool_call`:case`server_tool_call_chunk`:case`server_tool_call_result`:case`non_standard`:return``;default:return e.type?`[${e.type}]`:``}}function On(e,t=`Human`,n=`AI`){let r=[];for(let i of e){let e;if(i.type===`human`)e=t;else if(i.type===`ai`)e=n;else if(i.type===`system`)e=`System`;else if(i.type===`tool`)e=`Tool`;else if(i.type===`generic`)e=i.role;else throw Error(`Got unsupported message type: ${i.type}`);let a=i.name?`${i.name}, `:``,o=typeof i.content==`string`?i.content:Array.isArray(i.content)?i.content.map(Dn).filter(Boolean).join(``):``,s=`${e}: ${a}${o}`;if(i.type===`ai`){let e=i;e.tool_calls&&e.tool_calls.length>0?s+=JSON.stringify(e.tool_calls):e.additional_kwargs&&`function_call`in e.additional_kwargs&&(s+=JSON.stringify(e.additional_kwargs.function_call))}r.push(s)}return r.join(`
|
|
8
|
-
`)}function kn(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function An(e){let t=kn(e);switch(t.type){case`human`:return new fn(t.data);case`ai`:return new $t(t.data);case`system`:return new _n(t.data);case`function`:if(t.data.name===void 0)throw Error(`Name must be defined for function messages`);return new cn(t.data);case`tool`:if(t.data.tool_call_id===void 0)throw Error(`Tool call ID must be defined for tool messages`);return new xt(t.data);case`generic`:if(t.data.role===void 0)throw Error(`Role must be defined for chat messages`);return new rn(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function jn(e){return e.map(An)}function Mn(e){return e.map(e=>e.toDict())}function Nn(e){let t=e._getType();if(t===`human`)return new pn({...e});if(t===`ai`){let t={...e};return`tool_calls`in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:`tool_call_chunk`,index:void 0,args:JSON.stringify(e.args)}))}),new nn({...t})}else if(t===`system`)return new vn({...e});else if(t===`function`)return new ln({...e});else if(rn.isInstance(e))return new an({...e});else throw Error(`Unknown message type.`)}function Pn(e){let t=e.reduce((e,t)=>{let n=e.findIndex(([e])=>`id`in t&&t.id&&`index`in t&&t.index!==void 0?t.id===e.id&&t.index===e.index:`id`in t&&t.id?t.id===e.id:`index`in t&&t.index!==void 0?t.index===e.index:!1);return n===-1?e.push([t]):e[n].push(t),e},[]),n=[],r=[];for(let e of t){let t=null,i=e.some(xn),a=e[0]?.name??``,o=e.map(e=>e.args||``).join(``),s=i?o:o.trim(),c=s.length?s:`{}`,l=e.find(e=>e.id)?.id??e[0]?.id;if(i&&l){n.push({name:a,args:{input:s},id:l,type:`tool_call`});continue}try{if(t=x(c),!l||typeof t!=`object`||!t||Array.isArray(t))throw Error(`Malformed tool call chunk args.`);n.push({name:a,args:t,id:l,type:`tool_call`})}catch{r.push({name:a,args:c,id:l,error:`Malformed args.`,type:`invalid_tool_call`})}}return{tool_call_chunks:e,tool_calls:n,invalid_tool_calls:r}}var Fn=`ffffffff-ffff-ffff-ffff-ffffffffffff`,In=`00000000-0000-0000-0000-000000000000`,Ln=/^(?:[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 Rn(e){return typeof e==`string`&&Ln.test(e)}function zn(e){if(!Rn(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Bn=[];for(let e=0;e<256;++e)Bn.push((e+256).toString(16).slice(1));function Vn(e,t=0){return(Bn[e[t+0]]+Bn[e[t+1]]+Bn[e[t+2]]+Bn[e[t+3]]+`-`+Bn[e[t+4]]+Bn[e[t+5]]+`-`+Bn[e[t+6]]+Bn[e[t+7]]+`-`+Bn[e[t+8]]+Bn[e[t+9]]+`-`+Bn[e[t+10]]+Bn[e[t+11]]+Bn[e[t+12]]+Bn[e[t+13]]+Bn[e[t+14]]+Bn[e[t+15]]).toLowerCase()}function Hn(e,t=0){let n=Vn(e,t);if(!Rn(n))throw TypeError(`Stringified UUID is invalid`);return n}var Un=new Uint8Array(16);function Wn(){return crypto.getRandomValues(Un)}var Gn={};function Kn(e,t,n){let r,i=e?._v6??!1;if(e){let t=Object.keys(e);t.length===1&&t[0]===`_v6`&&(e=void 0)}if(e)r=Jn(e.random??e.rng?.()??Wn(),e.msecs,e.nsecs,e.clockseq,e.node,t,n);else{let e=Date.now(),a=Wn();qn(Gn,e,a),r=Jn(a,Gn.msecs,Gn.nsecs,i?void 0:Gn.clockseq,i?void 0:Gn.node,t,n)}return t??Vn(r)}function qn(e,t,n){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=n.slice(10,16),e.node[0]|=1,e.clockseq=(n[8]<<8|n[9])&16383),e.msecs=t,e}function Jn(e,t,n,r,i,a,o=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),n??=0,r??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=0xb1d069b5400;let s=((t&268435455)*1e4+n)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let c=t/4294967296*1e4&268435455;a[o++]=c>>>8&255,a[o++]=c&255,a[o++]=c>>>24&15|16,a[o++]=c>>>16&255,a[o++]=r>>>8|128,a[o++]=r&255;for(let e=0;e<6;++e)a[o++]=i[e];return a}function Yn(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Xn(e,t,n)}function Xn(e,t,n){e||={};let r=e.random??e.rng?.()??Wn();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Vn(r)}function Zn(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Qn(e,t){return e<<t|e>>>32-t}function $n(e){let t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(e.length+1);r.set(e),r[e.length]=128,e=r;let i=e.length/4+2,a=Math.ceil(i/16),o=Array(a);for(let t=0;t<a;++t){let n=new Uint32Array(16);for(let r=0;r<16;++r)n[r]=e[t*64+r*4]<<24|e[t*64+r*4+1]<<16|e[t*64+r*4+2]<<8|e[t*64+r*4+3];o[t]=n}o[a-1][14]=(e.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(e.length-1)*8&4294967295;for(let e=0;e<a;++e){let r=new Uint32Array(80);for(let t=0;t<16;++t)r[t]=o[e][t];for(let e=16;e<80;++e)r[e]=Qn(r[e-3]^r[e-8]^r[e-14]^r[e-16],1);let i=n[0],a=n[1],s=n[2],c=n[3],l=n[4];for(let e=0;e<80;++e){let n=Math.floor(e/20),o=Qn(i,5)+Zn(n,a,s,c)+l+t[n]+r[e]>>>0;l=c,c=s,s=Qn(a,30)>>>0,a=i,i=o}n[0]=n[0]+i>>>0,n[1]=n[1]+a>>>0,n[2]=n[2]+s>>>0,n[3]=n[3]+c>>>0,n[4]=n[4]+l>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function er(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}var tr=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,nr=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function rr(e,t,n,r,i,a){let o=typeof n==`string`?er(n):n,s=typeof r==`string`?zn(r):r;if(typeof r==`string`&&(r=zn(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Vn(c)}function ir(e,t,n,r){return rr(80,$n,e,t,n,r)}ir.DNS=tr,ir.URL=nr;function ar(e){let t=or(typeof e==`string`?zn(e):e);return typeof e==`string`?Vn(t):t}function or(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function sr(e,t,n){e??={},n??=0;let r=Kn({...e,_v6:!0},new Uint8Array(16));if(r=ar(r),t){if(n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;e++)t[n+e]=r[e];return t}return Vn(r)}var cr={};function lr(e,t,n){let r;if(e)r=dr(e.random??e.rng?.()??Wn(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Wn();ur(cr,e,i),r=dr(i,cr.msecs,cr.seq,t,n)}return t??Vn(r)}function ur(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function dr(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}function fr(e){if(!Rn(e))throw TypeError(`Invalid UUID`);return parseInt(e.slice(14,15),16)}var pr=s({MAX:()=>mr,NIL:()=>hr,parse:()=>gr,stringify:()=>_r,v1:()=>vr,v4:()=>yr,v5:()=>br,v6:()=>xr,v7:()=>Sr,validate:()=>Cr,version:()=>wr}),mr=Fn,hr=In,gr=zn,_r=Hn,vr=Kn,yr=Yn,br=ir,xr=sr,Sr=lr,Cr=Rn,wr=fr,Tr=s({getEnv:()=>jr,getEnvironmentVariable:()=>Pr,getRuntimeEnvironment:()=>Nr,isBrowser:()=>Er,isDeno:()=>kr,isJsDom:()=>Or,isNode:()=>Ar,isWebWorker:()=>Dr}),Er=()=>typeof window<`u`&&window.document!==void 0,Dr=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,Or=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),kr=()=>typeof Deno<`u`,Ar=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!kr(),jr=()=>{let e;return e=Er()?`browser`:Ar()?`node`:Dr()?`webworker`:Or()?`jsdom`:kr()?`deno`:`other`,e},Mr;function Nr(){return Mr===void 0&&(Mr={library:`langchain-js`,runtime:jr()}),Mr}function Pr(e){try{return typeof process<`u`?{}[e]:kr()?Deno?.env.get(e):void 0}catch{return}}var Fr=s({BaseCallbackHandler:()=>zr,callbackHandlerPrefersChatModelStreamEvents:()=>Rr,callbackHandlerPrefersStreaming:()=>Lr,isBaseCallbackHandler:()=>Br}),Ir=class{};function Lr(e){return`lc_prefer_streaming`in e&&e.lc_prefer_streaming}function Rr(e){return`lc_prefer_chat_model_stream_events`in e&&e.lc_prefer_chat_model_stream_events}var zr=class extends Ir{lc_serializable=!1;get lc_namespace(){return[`langchain_core`,`callbacks`,this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,_e(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Pr(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`;constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return ve.prototype.toJSON.call(this)}toJSONNotImplemented(){return ve.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends zr{name=Sr();constructor(){super(),Object.assign(this,e)}}return new t}},Br=e=>{let t=e;return t!==void 0&&typeof t.copy==`function`&&typeof t.name==`string`&&typeof t.awaitHandlers==`boolean`},Vr=/^(?:[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 Hr(e){return typeof e==`string`&&Vr.test(e)}function Ur(e){if(!Hr(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Wr=[];for(let e=0;e<256;++e)Wr.push((e+256).toString(16).slice(1));function Gr(e,t=0){return(Wr[e[t+0]]+Wr[e[t+1]]+Wr[e[t+2]]+Wr[e[t+3]]+`-`+Wr[e[t+4]]+Wr[e[t+5]]+`-`+Wr[e[t+6]]+Wr[e[t+7]]+`-`+Wr[e[t+8]]+Wr[e[t+9]]+`-`+Wr[e[t+10]]+Wr[e[t+11]]+Wr[e[t+12]]+Wr[e[t+13]]+Wr[e[t+14]]+Wr[e[t+15]]).toLowerCase()}var Kr=new Uint8Array(16);function qr(){return crypto.getRandomValues(Kr)}function Jr(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Yr(e,t,n)}function Yr(e,t,n){e||={};let r=e.random??e.rng?.()??qr();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Gr(r)}function Xr(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Zr(e,t){return e<<t|e>>>32-t}function Qr(e){let t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(e.length+1);r.set(e),r[e.length]=128,e=r;let i=e.length/4+2,a=Math.ceil(i/16),o=Array(a);for(let t=0;t<a;++t){let n=new Uint32Array(16);for(let r=0;r<16;++r)n[r]=e[t*64+r*4]<<24|e[t*64+r*4+1]<<16|e[t*64+r*4+2]<<8|e[t*64+r*4+3];o[t]=n}o[a-1][14]=(e.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(e.length-1)*8&4294967295;for(let e=0;e<a;++e){let r=new Uint32Array(80);for(let t=0;t<16;++t)r[t]=o[e][t];for(let e=16;e<80;++e)r[e]=Zr(r[e-3]^r[e-8]^r[e-14]^r[e-16],1);let i=n[0],a=n[1],s=n[2],c=n[3],l=n[4];for(let e=0;e<80;++e){let n=Math.floor(e/20),o=Zr(i,5)+Xr(n,a,s,c)+l+t[n]+r[e]>>>0;l=c,c=s,s=Zr(a,30)>>>0,a=i,i=o}n[0]=n[0]+i>>>0,n[1]=n[1]+a>>>0,n[2]=n[2]+s>>>0,n[3]=n[3]+c>>>0,n[4]=n[4]+l>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function $r(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}var ei=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,ti=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function ni(e,t,n,r,i,a){let o=typeof n==`string`?$r(n):n,s=typeof r==`string`?Ur(r):r;if(typeof r==`string`&&(r=Ur(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Gr(c)}function ri(e,t,n,r){return ni(80,Qr,e,t,n,r)}ri.DNS=ei,ri.URL=ti;var ii={};function ai(e,t,n){let r;if(e)r=si(e.random??e.rng?.()??qr(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=qr();oi(ii,e,i),r=si(i,ii.msecs,ii.seq,t,n)}return t??Gr(r)}function oi(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function si(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}var ci=`gen_ai.operation.name`,li=`gen_ai.system`,ui=`gen_ai.request.model`,di=`gen_ai.response.model`,fi=`gen_ai.usage.input_tokens`,pi=`gen_ai.usage.output_tokens`,mi=`gen_ai.usage.total_tokens`,hi=`gen_ai.request.max_tokens`,gi=`gen_ai.request.temperature`,_i=`gen_ai.request.top_p`,vi=`gen_ai.request.frequency_penalty`,yi=`gen_ai.request.presence_penalty`,bi=`gen_ai.response.finish_reasons`,xi=`gen_ai.prompt`,Si=`gen_ai.completion`,Ci=`gen_ai.request.extra_query`,wi=`gen_ai.request.extra_body`,Ti=`gen_ai.serialized.name`,Ei=`gen_ai.serialized.signature`,Di=`gen_ai.serialized.doc`,Oi=`gen_ai.response.id`,ki=`gen_ai.response.service_tier`,Ai=`gen_ai.response.system_fingerprint`,ji=`gen_ai.usage.input_token_details`,Mi=`gen_ai.usage.output_token_details`,Ni=`langsmith.trace.session_id`,Pi=`langsmith.trace.session_name`,Fi=`langsmith.span.kind`,Ii=`langsmith.trace.name`,Li=`langsmith.metadata`,Ri=`langsmith.span.tags`,zi=`langsmith.request.streaming`,Bi=`langsmith.request.headers`,Vi=`langsmith.usage_metadata`,Hi=(...e)=>fetch(...e),Ui=void 0,Wi=Symbol.for(`ls:fetch_implementation`),Gi=()=>globalThis[Wi]===void 0?!0:Ui??!1,Ki=e=>async(...t)=>{if(e||wo(`DEBUG`)===`true`){let[e,n]=t;console.log(`→ ${n?.method||`GET`} ${e}`)}let n=await(globalThis[Wi]??Hi)(...t);return(e||wo(`DEBUG`)===`true`)&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},qi=()=>wo(`PROJECT`)??Co(`LANGCHAIN_SESSION`)??`default`,Ji={};function Yi(e){Ji[e]||(console.warn(e),Ji[e]=!0)}var O=e=>BigInt(e),Xi=O(`0x9E3779B1`),Zi=O(`0x85EBCA77`),Qi=O(`0xC2B2AE3D`),$i=O(`0x9E3779B185EBCA87`),ea=O(`0xC2B2AE3D27D4EB4F`),ta=O(`0x165667B19E3779F9`),na=O(`0x85EBCA77C2B2AE63`),ra=O(`0x27D4EB2F165667C5`),ia=O(`0x165667919E3779F9`),aa=O(`0x9FB21C651E98DF25`);function oa(e){let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}var sa=oa(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),ca=(O(1)<<O(128))-O(1),la=(O(1)<<O(64))-O(1),ua=(O(1)<<O(32))-O(1),da=64,fa=da/8,pa=8,ma=4;function ha(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function ga(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function _a(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function va(e,t=0){return e[t]}var ya=e=>(e&O(255))<<O(56)|(e&O(65280))<<O(40)|(e&O(16711680))<<O(24)|(e&O(4278190080))<<O(8)|(e&O(0xff00000000))>>O(8)|(e&O(0xff0000000000))>>O(24)|(e&O(0xff000000000000))>>O(40)|(e&O(0xff00000000000000))>>O(56),ba=e=>(e=(e&O(65535))<<O(16)|(e&O(4294901760))>>O(16),e=(e&O(16711935))<<O(8)|(e&O(4278255360))>>O(8),e),xa=(e,t)=>(e&ua)*(t&ua)&la,Sa=e=>{if(!e)throw Error(`Assert failed`)};function Ca(e,t){return(e<<t|e>>O(32)-t)&ua}function wa(e,t,n){for(let r=0;r<fa;r++){let i=ga(t,r*8),a=i^ga(n,r*8);e[r^1]+=i,e[r]+=xa(a,a>>O(32))}return e}function Ta(e,t,n,r){for(let i=0;i<r;i++)wa(e,ha(t,i*da),ha(n,i*8));return e}function Ea(e,t){for(let n=0;n<fa;n++){let r=ga(t,n*8),i=e[n];i=La(i,O(47)),i^=r,i*=Xi,e[n]=i&la}return e}function Da(e,t){return ja(e[0]^ga(t,0),e[1]^ga(t,pa))}function Oa(e,t,n){let r=n;return r+=Da(e.slice(0),ha(t,0*ma)),r+=Da(e.slice(2),ha(t,4*ma)),r+=Da(e.slice(4),ha(t,8*ma)),r+=Da(e.slice(6),ha(t,12*ma)),Pa(r&la)}function ka(e,t,n,r,i){let a=Math.floor((n.byteLength-da)/8),o=da*a,s=Math.floor((t.byteLength-1)/o);for(let r=0;r<s;r++)e=Ta(e,ha(t,r*o),n,a),e=i(e,ha(n,n.byteLength-da));{let i=Math.floor((t.byteLength-1-o*s)/da);e=Ta(e,ha(t,s*o),n,i),e=r(e,ha(t,t.byteLength-da),ha(n,n.byteLength-da-7))}return e}function Aa(e,t,n){let r=new BigUint64Array([Qi,$i,ea,ta,na,Zi,ra,Xi]);Sa(e.length>128),r=ka(r,e,t,wa,Ea),Sa(r.length*8==64);{let n=Oa(r,ha(t,11),O(e.byteLength)*$i&la);return Oa(r,ha(t,t.byteLength-da-11),~(O(e.byteLength)*ea)&la)<<O(64)|n}}function ja(e,t){let n=e*t&ca;return n&la^n>>O(64)}function Ma(e,t,n){return ja((ga(e,0)^ga(t,0)+n)&la,(ga(e,8)^ga(t,8)-n)&la)}function Na(e,t,n,r,i){let a=e&la,o=e>>O(64)&la;return a+=Ma(t,r,i),a^=ga(n,0)+ga(n,8),a&=la,o+=Ma(n,ha(r,16),i),o^=ga(t,0)+ga(t,8),o&=la,o<<O(64)|a}function Pa(e){return e^=e>>O(37),e*=ia,e&=la,e^=e>>O(32),e}function Fa(e){return e^=e>>O(33),e*=ea,e&=la,e^=e>>O(29),e*=ta,e&=la,e^=e>>O(32),e}function Ia(e,t,n){let r=e.byteLength;Sa(r>0&&r<=3);let i=O(va(e,r-1))|O(r<<8)|O(va(e,0)<<16)|O(va(e,r>>1)<<24),a=(i^(O(_a(t,0))^O(_a(t,4)))+n)&la,o=(O(_a(t,8))^O(_a(t,12)))-n;return(Fa((Ca(ba(i),O(13))^o)&la)&la)<<O(64)|Fa(a)}function La(e,t){return e^e>>t}function Ra(e,t,n){let r=e.byteLength;Sa(r>=4&&r<=8);{let i=_a(e,0),a=_a(e,r-4),o=((O(i)|O(a)<<O(32))^(ga(t,16)^ga(t,24))+n&la)*($i+(O(r)<<O(2)))&ca;return o+=(o&la)<<O(65),o&=ca,o^=o>>O(67),La(La(o&la,O(35))*aa&la,O(28))|Pa(o>>O(64))<<O(64)}}function za(e,t,n){let r=e.byteLength;Sa(r>=9&&r<=16);{let i=(ga(t,32)^ga(t,40))+n&la,a=(ga(t,48)^ga(t,56))-n&la,o=ga(e),s=ga(e,r-8),c=(o^s^i)*$i,l=(c&la)+(O(r-1)<<O(54));c=c&(ca^la)|l,s^=a,c+=s+(s&ua)*(Zi-O(1))<<O(64),c&=ca,c^=ya(c>>O(64));let u=(c&la)*ea;return u+=(c>>O(64))*ea<<O(64),u&=ca,Pa(u&la)|Pa(u>>O(64))<<O(64)}}function Ba(e,t){let n=e.byteLength;return Sa(n<=16),n>8?za(e,sa,t):n>=4?Ra(e,sa,t):n>0?Ia(e,sa,t):Fa(t^ga(sa,64)^ga(sa,72))|Fa(t^ga(sa,80)^ga(sa,88))<<O(64)}function Va(e){return~e+O(1)&la}function Ha(e,t,n){let r=O(e.byteLength)*$i&la,i=O(e.byteLength-1)/O(32);for(;i>=0;){let a=Number(i);r=Na(r,ha(e,16*a),ha(e,e.byteLength-16*(a+1)),ha(t,32*a),n),i--}let a=r+(r>>O(64))&la;a=Pa(a);let o=(r&la)*$i+(r>>O(64))*na+(O(e.byteLength)-n&la)*ea;return o&=la,o=Va(Pa(o)),a|o<<O(64)}function Ua(e,t,n){let r=O(e.byteLength)*$i&la;for(let i=32;i<160;i+=32)r=Na(r,ha(e,i-32),ha(e,i-16),ha(t,i-32),n);r=Pa(r&la)|Pa(r>>O(64))<<O(64);for(let i=160;i<=e.byteLength;i+=32)r=Na(r,ha(e,i-32),ha(e,i-16),ha(t,3+i-160),n);r=Na(r,ha(e,e.byteLength-16),ha(e,e.byteLength-32),ha(t,103),Va(n));let i=r+(r>>O(64))&la;i=Pa(i);let a=(r&la)*$i+(r>>O(64))*na+(O(e.byteLength)-n&la)*ea;return a&=la,a=Va(Pa(a)),i|a<<O(64)}function Wa(e,t=O(0)){let n=e.byteLength;return n<=16?Ba(e,t):n<=128?Ha(e,sa,t):n<=240?Ua(e,sa,t):Aa(e,sa,t)}function Ga(e){let t=new Uint8Array(16),n=new DataView(t.buffer),r=e&la,i=e>>O(64);return n.setBigUint64(0,i,!1),n.setBigUint64(8,r,!1),t}var Ka=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function qa(e,t){if(!Ka.test(e)){let n=t===void 0?`Invalid UUID: ${e}`:`Invalid UUID for ${t}: ${e}`;throw Error(n)}return e}function Ja(e){return ai({msecs:typeof e==`string`?Date.parse(e):e,seq:0})}function Ya(e){if(!Ka.test(e))return null;let t=e[14];return parseInt(t,16)}function Xa(e){let t=e.replace(/-/g,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function Za(e){let t=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Qa=new TextEncoder;function $a(e){return Ga(Wa(Qa.encode(e)))}function eo(e,t){let n=$a(`${e}:${t}`),r=new Uint8Array(16);if(Ya(e)===7){let t=Xa(e);r.set(t.slice(0,6),0)}else{let e=Date.now();r[0]=e/1099511627776&255,r[1]=e/4294967296&255,r[2]=e/16777216&255,r[3]=e/65536&255,r[4]=e/256&255,r[5]=e&255}return r[6]=112|n[0]&15,r[7]=n[1],r[8]=128|n[2]&63,r.set(n.slice(3,10),9),Za(r)}var to={join:(...e)=>e.join(`/`),dirname:e=>e.split(`/`).slice(0,-1).join(`/`)};async function no(e){}async function ro(e,t){}async function io(e){return[]}async function ao(e){return{size:0}}function oo(e){return!1}function so(e){return``}function co(e,t){return t===null?!1:Date.now()-e.createdAt>t*1e3}var lo=new class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:t}),this._metrics.hits+=1,n.value}set(e,t,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r={value:t,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,r)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&=(clearInterval(this.refreshTimer),void 0)}dump(e){let t={};for(let[e,n]of this.cache.entries())t[e]=n.value;to.dirname(e),`${e}`;try{JSON.stringify({entries:t},null,2)}catch(e){throw e}}load(e){if(!oo(e))return 0;let t;try{let n=so(e);t=JSON.parse(n).entries??null}catch{return 0}if(!t)return 0;let n=0,r=Date.now();for(let[e,i]of Object.entries(t)){if(this.cache.size>=this.maxSize)break;let t={value:i,createdAt:r};this.cache.set(e,t),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn(`Unexpected error in cache refresh loop:`,e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[t,n]of this.cache.entries())co(n,this.ttlSeconds)&&e.push([t,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[t,n]of e)if(n.refreshFunc!==void 0)try{let e=await n.refreshFunc();this.set(t,e,n.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},uo=`0.6.3`,fo,po=()=>typeof window<`u`&&window.document!==void 0,mo=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,ho=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),go=()=>typeof Deno<`u`,_o=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!go(),vo=()=>fo||(fo=typeof Bun<`u`?`bun`:po()?`browser`:_o()?`node`:mo()?`webworker`:ho()?`jsdom`:go()?`deno`:`other`,fo),yo;function bo(){return yo===void 0&&(yo={library:`langsmith`,runtime:vo(),sdk:`langsmith-js`,sdk_version:uo,...Eo()}),yo}function xo(){let e=So(),t={},n=[`LANGCHAIN_API_KEY`,`LANGCHAIN_ENDPOINT`,`LANGCHAIN_TRACING_V2`,`LANGCHAIN_PROJECT`,`LANGCHAIN_SESSION`,`LANGSMITH_API_KEY`,`LANGSMITH_ENDPOINT`,`LANGSMITH_TRACING_V2`,`LANGSMITH_CONFIG_FILE`,`LANGSMITH_PROJECT`,`LANGSMITH_SESSION`];for(let[r,i]of Object.entries(e))typeof i==`string`&&!n.includes(r)&&!r.toLowerCase().includes(`key`)&&!r.toLowerCase().includes(`secret`)&&!r.toLowerCase().includes(`token`)&&(r===`LANGCHAIN_REVISION_ID`?t.revision_id=i:t[r]=i);return t}function So(){let e={};try{if(typeof process<`u`)for(let[t,n]of Object.entries({}))(t.startsWith(`LANGCHAIN_`)||t.startsWith(`LANGSMITH_`))&&n!=null&&((t.toLowerCase().includes(`key`)||t.toLowerCase().includes(`secret`)||t.toLowerCase().includes(`token`))&&typeof n==`string`?e[t]=n.slice(0,2)+`*`.repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function Co(e){try{return typeof process<`u`?{}[e]:void 0}catch{return}}function wo(e){return Co(`LANGSMITH_${e}`)||Co(`LANGCHAIN_${e}`)}var To;function Eo(){if(To!==void 0)return To;let e=[`VERCEL_GIT_COMMIT_SHA`,`NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA`,`COMMIT_REF`,`RENDER_GIT_COMMIT`,`CI_COMMIT_SHA`,`CIRCLE_SHA1`,`CF_PAGES_COMMIT_SHA`,`REACT_APP_GIT_SHA`,`SOURCE_VERSION`,`GITHUB_SHA`,`TRAVIS_COMMIT`,`GIT_COMMIT`,`BUILD_VCS_NUMBER`,`bamboo_planRepository_revision`,`Build.SourceVersion`,`BITBUCKET_COMMIT`,`DRONE_COMMIT_SHA`,`SEMAPHORE_GIT_SHA`,`BUILDKITE_COMMIT`],t={};for(let n of e){let e=Co(n);e!==void 0&&(t[n]=e)}return To=t,t}function Do(){return Co(`OTEL_ENABLED`)===`true`||wo(`OTEL_ENABLED`)===`true`}var Oo=new Set([`langsmith`,`otel`]);function ko(e){if(e!==void 0)return e;let t=wo(`TRACING_MODE`);if(t!==void 0&&t!==``){let e=t.toLowerCase();if(!Oo.has(e))throw Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(t)}. Must be one of: ${[...Oo].sort().join(`, `)}`);return Do()&&console.warn(`Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence.`),e}return Do()?`otel`:`langsmith`}var Ao=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&ko()===`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 n;if(t.length===1&&typeof t[0]==`function`?n=t[0]:t.length===2&&typeof t[1]==`function`?n=t[1]:t.length===3&&typeof t[2]==`function`&&(n=t[2]),typeof n==`function`)return n()}},jo=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Ao})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},Mo=class{active(){return{}}with(e,t){return t()}},No=Symbol.for(`ls:otel_trace`),Po=Symbol.for(`ls:otel_context`),Fo=Symbol.for(`ls:otel_get_default_otlp_tracer_provider`),Io=new jo,Lo=new Mo,Ro=new class{getTraceInstance(){return globalThis[No]??Io}getContextInstance(){return globalThis[Po]??Lo}initializeGlobalInstances(e){globalThis[No]===void 0&&(globalThis[No]=e.trace),globalThis[Po]===void 0&&(globalThis[Po]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Fo]=e}getDefaultOTLPTracerComponents(){return globalThis[Fo]??void 0}};function zo(){return Ro.getTraceInstance()}function Bo(){return Ro.getContextInstance()}function Vo(){return Ro.getDefaultOTLPTracerComponents()}var Ho={llm:`chat`,tool:`execute_tool`,retriever:`embeddings`,embedding:`embeddings`,prompt:`chat`};function Uo(e){return Ho[e]||e}function Wo(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`}var Go=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let n of e)try{if(!n.run)continue;if(n.operation===`post`){let e=this.createSpanForRun(n,n.run,t.get(n.id));e&&!n.run.end_time&&this.spans.set(n.id,e)}else this.updateSpanForRun(n,n.run)}catch(e){console.error(`Error processing operation ${n.id}:`,e)}}createSpanForRun(e,t,n){let r=n&&zo().getSpan(n);if(r)try{return this.finishSpanSetup(r,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(Error(t.error))):n.setStatus({code:1});let r=t.end_time;r&&(n.end(new Date(r)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,n){if(`run_type`in t&&t.run_type){e.setAttribute(Fi,t.run_type);let n=Uo(t.run_type||`chain`);e.setAttribute(ci,n)}`name`in t&&t.name&&e.setAttribute(Ii,t.name),`session_id`in t&&t.session_id&&e.setAttribute(Ni,t.session_id),`session_name`in t&&t.session_name&&e.setAttribute(Pi,t.session_name),this.setGenAiSystem(e,t);let r=this.extractModelName(t);r&&e.setAttribute(ui,r),t.extra?.metadata?.usage_metadata&&typeof t.extra.metadata.usage_metadata==`object`&&e.setAttribute(Vi,JSON.stringify(t.extra.metadata.usage_metadata)),`prompt_tokens`in t&&typeof t.prompt_tokens==`number`&&e.setAttribute(fi,t.prompt_tokens),`completion_tokens`in t&&typeof t.completion_tokens==`number`&&e.setAttribute(pi,t.completion_tokens),`total_tokens`in t&&typeof t.total_tokens==`number`&&e.setAttribute(mi,t.total_tokens),this.setInvocationParameters(e,t);let i=t.extra?.metadata||{};for(let[t,n]of Object.entries(i))n!=null&&e.setAttribute(`${Li}.${t}`,Wo(n)?String(n):JSON.stringify(n));let a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(Ri,a.join(`, `)):a&&e.setAttribute(Ri,String(a)),`serialized`in t&&typeof t.serialized==`object`){let n=t.serialized;n.name&&e.setAttribute(Ti,String(n.name)),n.signature&&e.setAttribute(Ei,String(n.signature)),n.doc&&e.setAttribute(Di,String(n.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n=`langchain`,r=this.extractModelName(t);if(r){let e=r.toLowerCase();e.includes(`anthropic`)||e.startsWith(`claude`)?n=`anthropic`:e.includes(`bedrock`)?n=`aws.bedrock`:e.includes(`azure`)&&e.includes(`openai`)?n=`az.ai.openai`:e.includes(`azure`)&&e.includes(`inference`)?n=`az.ai.inference`:e.includes(`cohere`)?n=`cohere`:e.includes(`deepseek`)?n=`deepseek`:e.includes(`gemini`)?n=`gemini`:e.includes(`groq`)?n=`groq`:e.includes(`watson`)||e.includes(`ibm`)?n=`ibm.watsonx.ai`:e.includes(`mistral`)?n=`mistral_ai`:e.includes(`gpt`)||e.includes(`openai`)?n=`openai`:e.includes(`perplexity`)||e.includes(`sonar`)?n=`perplexity`:e.includes(`vertex`)?n=`vertex_ai`:(e.includes(`xai`)||e.includes(`grok`))&&(n=`xai`)}e.setAttribute(li,n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(hi,n.max_tokens),n.temperature!==void 0&&e.setAttribute(gi,n.temperature),n.top_p!==void 0&&e.setAttribute(_i,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(vi,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(yi,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let n=t.run.inputs;typeof n==`object`&&n&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(ui,n.model),n.stream!==void 0&&e.setAttribute(zi,n.stream),n.extra_headers&&e.setAttribute(Bi,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Ci,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(wi,JSON.stringify(n.extra_body))),e.setAttribute(xi,JSON.stringify(n))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let n=t.run.outputs,r=this.getUnifiedRunTokens(n);if(r&&(e.setAttribute(fi,r[0]),e.setAttribute(pi,r[1]),e.setAttribute(mi,r[0]+r[1])),n&&typeof n==`object`){if(n.model&&e.setAttribute(di,String(n.model)),n.id&&e.setAttribute(Oi,n.id),n.choices&&Array.isArray(n.choices)){let t=n.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute(bi,t.join(`, `))}if(n.service_tier&&e.setAttribute(ki,n.service_tier),n.system_fingerprint&&e.setAttribute(Ai,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata==`object`){let t=n.usage_metadata;e.setAttribute(Vi,JSON.stringify(t)),t.input_token_details&&e.setAttribute(ji,JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute(Mi,JSON.stringify(t.output_token_details))}}e.setAttribute(Si,JSON.stringify(n))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;let n=Object.keys(e);for(let r of n){let n=e[r];if(!(!n||typeof n!=`object`)&&(t=this.extractUnifiedRunTokens(n.usage_metadata),t||n.lc===1&&n.kwargs&&typeof n.kwargs==`object`&&(t=this.extractUnifiedRunTokens(n.kwargs.usage_metadata),t)))return t}let r=e.generations||[];if(!Array.isArray(r))return null;let i=Array.isArray(r[0])?r.flat():r;for(let e of i)if(typeof e==`object`&&e.message&&typeof e.message==`object`&&e.message.kwargs&&typeof e.message.kwargs==`object`&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!=`object`||typeof e.input_tokens!=`number`||typeof e.output_tokens!=`number`?null:[e.input_tokens,e.output_tokens]}},Ko=Object.prototype.toString,qo=e=>Ko.call(e)===`[object Error]`,Jo=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 Yo(e){if(!(e&&qo(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:Jo.has(t)}function Xo(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Zo(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var Qo=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function $o(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function es(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function ts({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Qo)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),es(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=es(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!Yo(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=$o(n,i),f=Math.min(d,u);return f>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},f);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function ns(e,t={}){if(t={...t},Xo(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Zo(`factor`,t.factor,{min:0,allowInfinity:!1}),Zo(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Zo(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Zo(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await ts({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var rs=r(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),is=r(((e,t)=>{t.exports=(e,t)=>(t||=(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))})),as=r(((e,t)=>{var n=is(),r=class extends Error{constructor(e){super(e),this.name=`TimeoutError`}},i=(e,t,i)=>new Promise((a,o)=>{if(typeof t!=`number`||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){a(e);return}let s=setTimeout(()=>{if(typeof i==`function`){try{a(i())}catch(e){o(e)}return}let n=typeof i==`string`?i:`Promise timed out after ${t} milliseconds`,s=i instanceof Error?i:new r(n);typeof e.cancel==`function`&&e.cancel(),o(s)},t);n(e.then(a,o),()=>{clearTimeout(s)})});t.exports=i,t.exports.default=i,t.exports.TimeoutError=r})),os=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e,t,n){let r=0,i=e.length;for(;i>0;){let a=i/2|0,o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}e.default=t})),ss=r((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=os();e.default=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let i=t.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){return this._queue.shift()?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}})),cs=n(r((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=rs(),n=as(),r=ss(),i=()=>{},a=new n.TimeoutError;e.default=class extends t{constructor(e){if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=i,this._resolveIdle=i,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},e),!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit(`next`)}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=i,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=i,this.emit(`idle`))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit(`active`),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,i)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{r(await(this._timeout===void 0&&t.timeout===void 0?e():n.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&i(a)})))}catch(e){i(e)}this._next()},t),this._tryToStartAnother(),this.emit(`add`)})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}}))(),1),ls=`default`in cs.default?cs.default.default:cs.default,us=[408,425,429,500,502,503,504],ds=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 ls({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...n){let r=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&r>0&&this.queueSizeBytes+r>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${r} bytes.`));r>0&&(this.queueSizeBytes+=r);let i=this.onFailedResponseHook,a=this.queue.add(()=>ns(()=>t(...n).catch(e=>{throw e instanceof Error?e:Error(e)}),{async onFailedAttempt({error:e}){if(typeof e!=`object`||!e)throw e;let t=`message`in e&&typeof e.message==`string`?e.message:void 0;if(t?.startsWith(`Cancel`)||t?.startsWith(`TimeoutError`)||t?.startsWith(`AbortError`)||`name`in e&&e.name===`TimeoutError`||`code`in e&&e.code===`ECONNABORTED`)throw e;let n=`response`in e?e.response:void 0;if(i&&await i(n))return;let r=n?.status??(`status`in e?e.status:void 0);if(r!=null&&(typeof r==`number`||typeof r==`string`)&&!us.includes(+r))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return r>0&&(a=a.finally(()=>{this.queueSizeBytes-=r})),e.signal?Promise.race([a,new Promise((t,n)=>{e.signal?.addEventListener(`abort`,()=>{n(Error(`AbortError`))})})]):a}};function fs(e){return typeof e?._getType==`function`}function ps(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}function ms(e){return`Invalid prompt identifier format: "${e}". Expected one of:\n - "prompt-name" (for private prompts)\n - "owner/prompt-name" (for prompts with explicit owner)\n - "prompt-name:commit-hash" (with commit reference)\n - "owner/prompt-name:commit-hash" (with owner and commit)`}var hs=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=`LangSmithConflictError`,this.status=409}},gs=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=`LangSmithNotFoundError`,this.status=404}};function _s(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithNotFoundError`}function vs(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithConflictError`}async function k(e,t,n){let r;if(e.ok){n&&(r=await e.text());return}if(e.status===403)try{(await e.json())?.error===`org_scoped_key_requires_workspace`&&(r=`This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.`)}catch{let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(r===void 0)try{r=await e.text()}catch{r=``}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(e.status===404)throw new gs(i);if(e.status===409)throw new hs(i);let a=Error(i);throw a.status=e.status,a}var ys=`ERR_CONFLICTING_ENDPOINTS`,bs=class extends Error{constructor(){super(`You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.`),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:ys}),this.name=`ConflictingEndpointsError`}};function xs(e){return typeof e==`object`&&!!e&&e.code===ys}function Ss(e){if(!e||e.split(`/`).length>2||e.startsWith(`/`)||e.endsWith(`/`)||e.split(`:`).length>2)throw Error(ms(e));let[t,n]=e.split(`:`),r=n||`latest`;if(t.includes(`/`)){let[n,i]=t.split(`/`,2);if(!n||!i)throw Error(ms(e));return[n,i,r]}else{if(!t)throw Error(ms(e));return[`-`,t,r]}}var Cs=`langsmith-cli`,ws=6e4,Ts=1e4;function Es(){let e=vo();return e===`browser`||e===`webworker`}function Ds(){let e=Co(`LANGSMITH_CONFIG_FILE`);if(e)return e;let t=Co(`HOME`)??Co(`USERPROFILE`);if(t)return to.join(t,`.langsmith`,`config.json`)}function Os(e){let t=Co(`LANGSMITH_PROFILE`);if(t)return t;if(e.current_profile)return e.current_profile;if(e.profiles?.default)return`default`}function ks(){if(Es())return;let e=Ds();if(!(!e||!oo(e)))try{let t=JSON.parse(so(e)),n=Os(t),r=n?t.profiles?.[n]:void 0;return!n||!r?void 0:{configPath:e,config:t,profileName:n,profile:r}}catch{return}}function As(e){return e!=null&&e.trim()!==``}function js(e){return e?.trim().replace(/^["']|["']$/g,``)}function Ms(e){let t=e.oauth;if(!t?.refresh_token)return!1;if(!t.access_token)return!0;if(!t.expires_at)return!1;let n=Date.parse(t.expires_at);return Number.isNaN(n)?!1:n<=Date.now()+ws}function Ns(e){let t=e;for(;t.endsWith(`/`);)t=t.slice(0,-1);return t.endsWith(`/api/v1`)?t.slice(0,-7):t}function Ps(e,t){e.oauth??={},t.access_token&&(e.oauth.access_token=t.access_token),t.refresh_token&&(e.oauth.refresh_token=t.refresh_token),typeof t.expires_in==`number`&&t.expires_in>0&&(e.oauth.expires_at=new Date(Date.now()+t.expires_in*1e3).toISOString())}function Fs(e){return e.reason??Error(`The operation was aborted.`)}async function Is(e,t){if(!t)return e;if(t.aborted)throw Fs(t);let n,r=new Promise((e,r)=>{let i=()=>{r(Fs(t))};t.addEventListener(`abort`,i,{once:!0}),n=()=>{t.removeEventListener(`abort`,i)}});try{return await Promise.race([e,r])}finally{n?.()}}function Ls(){let e=ks(),t=e?.profile;if(!e||!t)return{};let n=js(t.api_key),r=js(t.oauth?.access_token),i=js(t.oauth?.refresh_token);return{apiUrl:t.api_url,apiKey:n,workspaceId:t.workspace_id,oauthAccessToken:r,oauthRefreshToken:i,profileAuth:n||r||i?new Rs(e):void 0}}var Rs=class{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(){let e=zs(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,t){Ms(this.state.profile)&&(this.refreshPromise||=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0}),await Is(this.refreshPromise,t));let n=Bs(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}async refreshOAuthToken(e){let t=this.state.profile.oauth?.refresh_token;if(!t)return;let n=js(this.state.profile.api_url)??`https://api.smith.langchain.com`;try{let r=new URLSearchParams({grant_type:`refresh_token`,client_id:Cs,refresh_token:t}),i=await e(`${Ns(n)}/oauth/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:r.toString(),signal:AbortSignal.timeout(Ts)});if(!i.ok)return;let a=await i.json();if(!a.access_token)return;Ps(this.state.profile,a),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await ro(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}\n`)}catch{return}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name===`Authorization`?e.value:void 0}};function zs(e){let t=js(e.oauth?.access_token);if(t)return{name:`Authorization`,value:`Bearer ${t}`};if(!js(e.oauth?.refresh_token))return Bs(e)}function Bs(e){let t=js(e.oauth?.access_token);if(t)return{name:`Authorization`,value:`Bearer ${t}`};let n=js(e.api_key);if(n)return{name:`x-api-key`,value:n}}var Vs=`[...]`,Hs={result:`[Circular]`},Us=[],Ws=[],Gs=new TextEncoder;function Ks(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function qs(e){return Gs.encode(e)}function Js(e){if(e&&typeof e==`object`&&e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e==`bigint`)return e.toString();return e}function Ys(e){return function(t,n){if(e){let r=e.call(this,t,n);if(r!==void 0)return r}return Js(n)}}function Xs(e){try{let t=new Set,n=0,r=typeof Buffer<`u`&&typeof Buffer.byteLength==`function`?e=>Buffer.byteLength(e,`utf8`):e=>e.length;function i(e){let t=r(e);return t>n&&(n=t),t+2}function a(e){return e===0?2:2+e*4}function o(e){return e===void 0||typeof e==`function`||typeof e==`symbol`}function s(e){return e===void 0||typeof e==`function`||typeof e==`symbol`?4:c(e)}function c(e){if(e===null)return 4;if(e===void 0)return 0;let n=typeof e;if(n===`boolean`)return 5;if(n===`number`)return Number.isFinite(e)?e.toString().length:4;if(n===`bigint`)return e.toString().length+2;if(n===`string`)return i(e);if(n===`function`||n===`symbol`)return 0;let l=e;if(l instanceof Date)return 26;if(l instanceof RegExp)return r(l.toString())+2;if(l instanceof Error){let e=l.name??``,t=l.message??``;return 22+r(e)+r(t)}if(typeof Buffer<`u`&&l instanceof Buffer)return 28+a(l.byteLength);if(ArrayBuffer.isView(l))return l instanceof DataView?2:2+(l.length??0)*(l instanceof Float32Array||l instanceof Float64Array?30:12);if(l instanceof ArrayBuffer)return 2;if(t.has(l))return 24;if(typeof l.toJSON==`function`){let e;try{e=l.toJSON(``)}catch{return 16}t.add(l);let n=c(e);return t.delete(l),n}t.add(l);let u;if(Array.isArray(l)){u=2;let e=l.length;for(let t=0;t<e;t++)u+=s(l[t]),t<e-1&&(u+=1)}else if(l instanceof Map){u=2;let e=0;for(let[t,n]of l)o(n)||(e>0&&(u+=1),u+=r(typeof t==`string`?t:String(t))+3,u+=c(n),e++)}else if(l instanceof Set){u=2;let e=0;for(let t of l)e>0&&(u+=1),u+=s(t),e++}else{u=2;let e=0,t=Object.keys(l);for(let n=0;n<t.length;n++){let i=t[n],a=l[i];o(a)||(e>0&&(u+=1),u+=r(i)+3,u+=c(a),e++)}}return t.delete(l),u}return{size:c(e),maxStringLen:n}}catch{return{size:Zs(e).length,maxStringLen:0}}}function Zs(e,t,n,r,i){try{return qs(JSON.stringify(e,Ys(n),r))}catch(a){if(!a.message?.includes(`Converting circular structure to JSON`))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`\nContext: ${t}`:``}`),qs(`[Unserializable]`);wo(`SUPPRESS_CIRCULAR_JSON_WARNINGS`)!==`true`&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`\nContext: ${t}`:``}`),i===void 0&&(i=Ks()),$s(e,``,0,[],void 0,0,i);let o;try{o=Ws.length===0?JSON.stringify(e,n,r):JSON.stringify(e,ec(n),r)}catch{return qs(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;Us.length!==0;){let e=Us.pop();e.length===4?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return qs(o)}}function Qs(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,Us.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),Us.push([r,n,t,i])):Ws.push([t,n,e])}function $s(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){Qs(Hs,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){Qs(Vs,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){Qs(Vs,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)$s(e[s],s,s,r,e,a,o);else{e=Js(e);var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];$s(e[l],l,s,r,e,a,o)}}r.pop()}}function ec(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(Ws.length>0)for(var r=0;r<Ws.length;r++){var i=Ws[r];if(i[1]===t&&i[0]===n){n=i[2],Ws.splice(r,1);break}}return e.call(this,t,n)}}var tc=class{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;let t=this.nextId++;return new Promise((n,r)=>{this.pending.set(t,{resolve:n,reject:r});try{this.worker.postMessage({id:t,op:`serialize`,payload:e})}catch(e){this.pending.delete(t),r(e)}})}async terminate(){this.worker&&=(await this.worker.terminate(),null);for(let[,e]of this.pending)e.reject(Error(`worker terminated`));this.pending.clear()}},nc=null;function rc(){return nc===null&&(nc=new tc),nc}var ic=64*1024,ac=2048;function oc(e,t=ic,n=ac){if(typeof e!=`object`||!e)return typeof e==`string`&&e.length>=t;let r=[e],i=new Set,a=0;for(;r.length>0;){if(a++>=n)return!1;let e=r.pop();if(e==null)continue;let o=typeof e;if(o===`string`){if(e.length>=t)return!0;continue}if(o!==`object`)continue;let s=e;if(i.has(s)||(i.add(s),s instanceof Date||s instanceof RegExp||s instanceof Error||s instanceof ArrayBuffer||ArrayBuffer.isView(s)))continue;if(Array.isArray(s)){for(let e=s.length-1;e>=0;e--)r.push(s[e]);continue}if(s instanceof Map){for(let[,e]of s)r.push(e);continue}if(s instanceof Set){for(let e of s)r.push(e);continue}let c=Object.keys(s);for(let e=c.length-1;e>=0;e--)r.push(s[c[e]])}return!1}function sc(e,t){let[n]=Ss(e);if(n!==`-`&&!t)throw 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 cc(e){return typeof e==`string`&&e.length>0&&!e.includes(`Z`)&&!e.includes(`+`)&&!e.includes(`-`,10)?e+`Z`:e}function lc(e){return{...e,start_time:cc(e.start_time),end_time:cc(e.end_time)}}function uc(e,t,n){if(n)return e;let r=bo(),i=t??xo(),a=e.extra??{},o=a.metadata;return e.extra={...a,runtime:{...r,...a?.runtime},metadata:{...i,...i.revision_id||`revision_id`in e&&e.revision_id?{revision_id:(`revision_id`in e?e.revision_id:void 0)??i.revision_id}:{},...o}},e}var dc=e=>{let t=e?.toString()??wo(`TRACING_SAMPLING_RATE`);if(t===void 0)return;let n=parseFloat(t);if(n<0||n>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},fc=e=>{let t=e.replace(`http://`,``).replace(`https://`,``).split(`/`)[0].split(`:`)[0];return t===`localhost`||t===`127.0.0.1`||t===`::1`};async function pc(e){let t=[];for await(let n of e)t.push(n);return t}function mc(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,`$1`).replace(/^'(.*)'$/,`$1`)}var hc=async e=>{if(e?.status===429){let t=parseInt(e.headers.get(`retry-after`)??`10`,10)*1e3;if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function gc(e){return typeof e==`number`?Number(e.toFixed(4)):e}var _c=1e4,vc=100,yc=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??1073741824}peek(){return this.items[0]}push(e){let t,n=new Promise(e=>{t=e}),r=Xs(e.item).size;return this.sizeBytes+r>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${r} bytes.`),t(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:r}),this.sizeBytes+=r,n)}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error(`Number of bytes to pop off may not be less than 1.`);let n=[],r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<t;){let e=this.items.shift();e&&(n.push(e),r+=e.size,this.sizeBytes-=e.size)}if(n.length===0&&this.items.length>0){let e=this.items.shift();n.push(e),r+=e.size,this.sizeBytes-=e.size}return[n.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>n.forEach(e=>e.itemPromiseResolve())]}},bc=class e{get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||Ki(this.debug);return(async(t,n)=>{let r,i=this.getProfileManagedAuthorizationHeader(n);return this.apiKey===void 0?this.hasExplicitAuthHeader(n,i)||(r=await this.profileAuth?.getAuthHeader(e,n?.signal)):r={name:`x-api-key`,value:`${this.apiKey}`},e(t,this.applyCurrentAuthHeaders(n,r,i))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let t=new Headers(e.headers).get(`Authorization`);if(As(t))return this.profileAuth.isProfileAuthorizationHeader(t??``)?t??void 0:void 0}isProfileManagedAuthorizationHeader(e,t){return e===t||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,t){if(!e?.headers)return!1;let n=new Headers(e.headers);if(As(n.get(`x-api-key`)))return!0;let r=n.get(`Authorization`);return As(r)?!this.isProfileManagedAuthorizationHeader(r??``,t):!1}applyCurrentAuthHeaders(e,t,n){if(!t)return e;let r=e=>{if(this.apiKey!==void 0&&t.name===`x-api-key`)return e.delete(`Authorization`),e.has(`x-api-key`)||e.set(`x-api-key`,t.value),e;if(t.name===`Authorization`){if(As(e.get(`x-api-key`)))return e;let r=e.get(`Authorization`);return As(r)&&!this.isProfileManagedAuthorizationHeader(r??``,n)||e.set(`Authorization`,t.value),e}let r=e.get(`Authorization`);return As(r)&&!this.isProfileManagedAuthorizationHeader(r??``,n)?e:(As(r)&&e.delete(`Authorization`),e.has(`x-api-key`)||e.set(`x-api-key`,t.value),e)};if(!e)return{headers:{[t.name]:t.value}};if(e.headers instanceof Headers||Array.isArray(e.headers))return{...e,headers:r(new Headers(e.headers))};let i={...e.headers??{}},a=e=>Object.keys(i).find(t=>t.toLowerCase()===e),o=e=>{let t=a(e);return t?i[t]:void 0},s=As(o(`x-api-key`)),c=o(`authorization`),l=As(c)&&!this.isProfileManagedAuthorizationHeader(c??``,n);if(this.apiKey!==void 0&&t.name===`x-api-key`){let n=a(`authorization`);return n&&delete i[n],s||(i[`x-api-key`]=t.value),{...e,headers:i}}if(t.name===`Authorization`){if(!s&&!l){let e=a(`authorization`);e&&e!==`Authorization`&&delete i[e],i.Authorization=t.value}return{...e,headers:i}}if(!l){let e=a(`authorization`);e&&delete i[e],s||(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||!oc(e)||(this._serializeWorker===void 0&&(this._serializeWorker=rc()),this._serializeWorker===null))return Zs(e,t);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,Zs(e,t)):n}catch{return Zs(e,t)}}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Co(`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:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:wo(`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:Co(`LANGSMITH_DEBUG`)===`true`});let n=e.getDefaultClientConfig();this.tracingSampleRate=dc(t.tracingSamplingRate),this.apiUrl=mc(t.apiUrl??n.apiUrl)??``,this.apiUrl.endsWith(`/`)&&(this.apiUrl=this.apiUrl.slice(0,-1));let r=mc(t.apiKey??n.apiKey);if(this.apiKey=As(r)?r:void 0,this.profileAuth=this.apiKey===void 0?n.profileAuth:void 0,this.webUrl=mc(t.webUrl??n.webUrl),this.webUrl?.endsWith(`/`)&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=mc(t.workspaceId??n.workspaceId),this.timeout_ms=t.timeout_ms??9e4,this.caller=new ds({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error(`Trace batch concurrency must be positive.`);this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.failedTracesDir=wo(`FAILED_TRACES_DIR`)||void 0;let i=wo(`FAILED_TRACES_MAX_MB`);if(i){let e=parseInt(i,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=e*1024*1024)}let a=t.maxIngestMemoryBytes??1073741824;this.batchIngestCaller=new ds({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...t.callerOptions??{},onFailedResponseHook:hc,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.hideMetadata=t.hideMetadata??n.hideMetadata,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new yc(a),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,this._tracingMode=ko(t.tracingMode),this._tracingMode===`otel`&&(this.langSmithToOTELTranslator=new Go),this.cachedLSEnvVarsForMetadata=xo(),t.cache!==void 0&&t.disablePromptCache&&Yi(`Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value.`),t.cache===void 0?t.disablePromptCache||(this._promptCache=lo):(Yi(`The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client.`),t.cache===!1?this._promptCache=void 0:t.cache===!0?this._promptCache=lo:this._promptCache=t.cache),this._customHeaders=t.headers??{}}static getDefaultClientConfig(){let e=Ls(),t=wo(`API_KEY`),n=wo(`ENDPOINT`),r=wo(`WORKSPACE_ID`),i=As(t),a=n??e.apiUrl??`https://api.smith.langchain.com`,o=r??e.workspaceId;return{apiUrl:a,apiKey:t,webUrl:void 0,hideInputs:wo(`HIDE_INPUTS`)===`true`,hideOutputs:wo(`HIDE_OUTPUTS`)===`true`,hideMetadata:wo(`HIDE_METADATA`)===`true`,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:fc(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(){let e={"User-Agent":`langsmith-js/${uo}`,...this._customHeaders};if(this.apiKey!==void 0)e[`x-api-key`]=`${this.apiKey}`;else{let t=this.profileAuth?.currentAuthHeader();t&&(e[t.name]=t.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(e=>{if(e.name===`new_token`){let{kwargs:t,...n}=e;return n}return e})}async prepareRunCreateOrUpdateInputs(e){let t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t.extra!=null&&`metadata`in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events!==void 0&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){let n=t?.toString()??``,r=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let t=await this._fetch(r,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let r=Number(t.get(`offset`))||0,i=Number(t.get(`limit`))||100;for(;;){t.set(`offset`,String(r)),t.set(`limit`,String(i));let a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{let t=await this._fetch(a,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`fetch ${e}`),t}),s=n?n(await o.json()):await o.json();if(s.length===0||(yield s,s.length<i))break;r+=s.length}}async*_getCursorPaginatedList(e,t=null,n=`POST`,r=`runs`){let i=t?{...t}:{};for(;;){let t=JSON.stringify(i),a=await(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await k(r,`fetch ${e}`),r})).json();if(!a||!a[r])break;yield a[r];let o=a.cursors;if(!o||!o.next)break;i.cursor=o.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){let t=[];for(let n of e)this.filteredPostUuids.has(n.trace_id)?n.id===n.trace_id&&this.filteredPostUuids.delete(n.trace_id):t.push(n);return t}else{let t=[];for(let n of e){let e=n.trace_id??n.id;this.filteredPostUuids.has(e)||(n.id===e?this._shouldSample()?t.push(n):this.filteredPostUuids.add(e):t.push(n))}return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??25165824}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??vc}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[r,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!r.length){i();break}let a=r.reduce((e,t)=>{let n=t.apiUrl??this.apiUrl,r=t.apiKey??this.apiKey,i=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?`default`:`${n}|${r}`;return e[i]||(e[i]=[]),e[i].push(t),e},{}),o=[];for(let[e,t]of Object.entries(a)){let n=this._processBatch(t,{apiUrl:e==="default"?void 0:e.split(`|`)[0],apiKey:e==="default"?void 0:e.split(`|`)[1]});o.push(n)}let s=Promise.all(o).finally(i);n.push(s)}return Promise.all(n)}static async _writeTraceToFallbackDir(t,n,r,i,a){try{let o=typeof n==`string`?Buffer.from(n,`utf8`):Buffer.from(n),s=JSON.stringify({version:1,endpoint:i,headers:r,body_base64:o.toString(`base64`)}),c=`trace_${Date.now()}_${Jr().slice(0,8)}.json`,l=to.join(t,c);if(e._fallbackDirsCreated.has(t)||(await no(t),e._fallbackDirsCreated.add(t)),a!==void 0&&a>0)try{let e=(await io(t)).filter(e=>e.startsWith(`trace_`)&&e.endsWith(`.json`)),n=0;for(let r of e){let{size:e}=await ao(to.join(t,r));n+=e}if(n>=a){console.warn(`Could not write trace to fallback dir ${t} as it's already over size limit (${n} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await ro(l,s),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(e){console.error(`LangSmith tracing error: could not write trace to fallback dir ${t}:`,e)}}async _processBatch(e,t){if(!e.length)return;let n=e.reduce((e,t)=>e+(t.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let r={runCreates:e.filter(e=>e.action===`create`).map(e=>e.item),runUpdates:e.filter(e=>e.action===`update`).map(e=>e.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let e=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(r,{...t,useGzip:e,sizeBytes:n})}catch(e){if(_s(e))this._multipartDisabled=!0,await this.batchIngestRuns(r,{...t,sizeBytes:n});else throw e}}else await this.batchIngestRuns(r,{...t,sizeBytes:n})}}catch(e){console.error(`Error exporting batch:`,e)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let t=new Map,n=[];for(let r of e)r.item.id&&r.otelContext&&(t.set(r.item.id,r.otelContext),r.action===`create`?n.push({operation:`post`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):n.push({operation:`patch`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=uc(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let n=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>r)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r}))},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:`GET`,headers:{...this._mergedHeaders,Accept:`application/json`},signal:AbortSignal.timeout(_c),...this.fetchOptions});return await k(e,`get server info`),e})).json();return this.debug&&console.log(`
|
|
8
|
+
`)}function kn(e){if(e.data!==void 0)return e;{let t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function An(e){let t=kn(e);switch(t.type){case`human`:return new fn(t.data);case`ai`:return new $t(t.data);case`system`:return new _n(t.data);case`function`:if(t.data.name===void 0)throw Error(`Name must be defined for function messages`);return new cn(t.data);case`tool`:if(t.data.tool_call_id===void 0)throw Error(`Tool call ID must be defined for tool messages`);return new xt(t.data);case`generic`:if(t.data.role===void 0)throw Error(`Role must be defined for chat messages`);return new rn(t.data);default:throw Error(`Got unexpected type: ${t.type}`)}}function jn(e){return e.map(An)}function Mn(e){return e.map(e=>e.toDict())}function Nn(e){let t=e._getType();if(t===`human`)return new pn({...e});if(t===`ai`){let t={...e};return`tool_calls`in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:`tool_call_chunk`,index:void 0,args:JSON.stringify(e.args)}))}),new nn({...t})}else if(t===`system`)return new vn({...e});else if(t===`function`)return new ln({...e});else if(rn.isInstance(e))return new an({...e});else throw Error(`Unknown message type.`)}function Pn(e){let t=e.reduce((e,t)=>{let n=e.findIndex(([e])=>`id`in t&&t.id&&`index`in t&&t.index!==void 0?t.id===e.id&&t.index===e.index:`id`in t&&t.id?t.id===e.id:`index`in t&&t.index!==void 0&&t.index===e.index);return n===-1?e.push([t]):e[n].push(t),e},[]),n=[],r=[];for(let e of t){let t=null,i=e.some(xn),a=e[0]?.name??``,o=e.map(e=>e.args||``).join(``),s=i?o:o.trim(),c=s.length?s:`{}`,l=e.find(e=>e.id)?.id??e[0]?.id;if(i&&l){n.push({name:a,args:{input:s},id:l,type:`tool_call`});continue}try{if(t=x(c),!l||typeof t!=`object`||!t||Array.isArray(t))throw Error(`Malformed tool call chunk args.`);n.push({name:a,args:t,id:l,type:`tool_call`})}catch{r.push({name:a,args:c,id:l,error:`Malformed args.`,type:`invalid_tool_call`})}}return{tool_call_chunks:e,tool_calls:n,invalid_tool_calls:r}}var Fn=`ffffffff-ffff-ffff-ffff-ffffffffffff`,In=`00000000-0000-0000-0000-000000000000`,Ln=/^(?:[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 Rn(e){return typeof e==`string`&&Ln.test(e)}function zn(e){if(!Rn(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Bn=[];for(let e=0;e<256;++e)Bn.push((e+256).toString(16).slice(1));function Vn(e,t=0){return(Bn[e[t+0]]+Bn[e[t+1]]+Bn[e[t+2]]+Bn[e[t+3]]+`-`+Bn[e[t+4]]+Bn[e[t+5]]+`-`+Bn[e[t+6]]+Bn[e[t+7]]+`-`+Bn[e[t+8]]+Bn[e[t+9]]+`-`+Bn[e[t+10]]+Bn[e[t+11]]+Bn[e[t+12]]+Bn[e[t+13]]+Bn[e[t+14]]+Bn[e[t+15]]).toLowerCase()}function Hn(e,t=0){let n=Vn(e,t);if(!Rn(n))throw TypeError(`Stringified UUID is invalid`);return n}var Un=new Uint8Array(16);function Wn(){return crypto.getRandomValues(Un)}var Gn={};function Kn(e,t,n){let r,i=e?._v6??!1;if(e){let t=Object.keys(e);t.length===1&&t[0]===`_v6`&&(e=void 0)}if(e)r=Jn(e.random??e.rng?.()??Wn(),e.msecs,e.nsecs,e.clockseq,e.node,t,n);else{let e=Date.now(),a=Wn();qn(Gn,e,a),r=Jn(a,Gn.msecs,Gn.nsecs,i?void 0:Gn.clockseq,i?void 0:Gn.node,t,n)}return t??Vn(r)}function qn(e,t,n){return e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0),e.node||(e.node=n.slice(10,16),e.node[0]|=1,e.clockseq=(n[8]<<8|n[9])&16383),e.msecs=t,e}function Jn(e,t,n,r,i,a,o=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!a)a=new Uint8Array(16),o=0;else if(o<0||o+16>a.length)throw RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);t??=Date.now(),n??=0,r??=(e[8]<<8|e[9])&16383,i??=e.slice(10,16),t+=0xb1d069b5400;let s=((t&268435455)*1e4+n)%4294967296;a[o++]=s>>>24&255,a[o++]=s>>>16&255,a[o++]=s>>>8&255,a[o++]=s&255;let c=t/4294967296*1e4&268435455;a[o++]=c>>>8&255,a[o++]=c&255,a[o++]=c>>>24&15|16,a[o++]=c>>>16&255,a[o++]=r>>>8|128,a[o++]=r&255;for(let e=0;e<6;++e)a[o++]=i[e];return a}function Yn(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Xn(e,t,n)}function Xn(e,t,n){e||={};let r=e.random??e.rng?.()??Wn();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Vn(r)}function Zn(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Qn(e,t){return e<<t|e>>>32-t}function $n(e){let t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(e.length+1);r.set(e),r[e.length]=128,e=r;let i=e.length/4+2,a=Math.ceil(i/16),o=Array(a);for(let t=0;t<a;++t){let n=new Uint32Array(16);for(let r=0;r<16;++r)n[r]=e[t*64+r*4]<<24|e[t*64+r*4+1]<<16|e[t*64+r*4+2]<<8|e[t*64+r*4+3];o[t]=n}o[a-1][14]=(e.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(e.length-1)*8&4294967295;for(let e=0;e<a;++e){let r=new Uint32Array(80);for(let t=0;t<16;++t)r[t]=o[e][t];for(let e=16;e<80;++e)r[e]=Qn(r[e-3]^r[e-8]^r[e-14]^r[e-16],1);let i=n[0],a=n[1],s=n[2],c=n[3],l=n[4];for(let e=0;e<80;++e){let n=Math.floor(e/20),o=Qn(i,5)+Zn(n,a,s,c)+l+t[n]+r[e]>>>0;l=c,c=s,s=Qn(a,30)>>>0,a=i,i=o}n[0]=n[0]+i>>>0,n[1]=n[1]+a>>>0,n[2]=n[2]+s>>>0,n[3]=n[3]+c>>>0,n[4]=n[4]+l>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function er(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}var tr=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,nr=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function rr(e,t,n,r,i,a){let o=typeof n==`string`?er(n):n,s=typeof r==`string`?zn(r):r;if(typeof r==`string`&&(r=zn(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Vn(c)}function ir(e,t,n,r){return rr(80,$n,e,t,n,r)}ir.DNS=tr,ir.URL=nr;function ar(e){let t=or(typeof e==`string`?zn(e):e);return typeof e==`string`?Vn(t):t}function or(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function sr(e,t,n){e??={},n??=0;let r=Kn({...e,_v6:!0},new Uint8Array(16));if(r=ar(r),t){if(n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;e++)t[n+e]=r[e];return t}return Vn(r)}var cr={};function lr(e,t,n){let r;if(e)r=dr(e.random??e.rng?.()??Wn(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=Wn();ur(cr,e,i),r=dr(i,cr.msecs,cr.seq,t,n)}return t??Vn(r)}function ur(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function dr(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}function fr(e){if(!Rn(e))throw TypeError(`Invalid UUID`);return parseInt(e.slice(14,15),16)}var pr=s({MAX:()=>mr,NIL:()=>hr,parse:()=>gr,stringify:()=>_r,v1:()=>vr,v4:()=>yr,v5:()=>br,v6:()=>xr,v7:()=>Sr,validate:()=>Cr,version:()=>wr}),mr=Fn,hr=In,gr=zn,_r=Hn,vr=Kn,yr=Yn,br=ir,xr=sr,Sr=lr,Cr=Rn,wr=fr,Tr=s({getEnv:()=>jr,getEnvironmentVariable:()=>Pr,getRuntimeEnvironment:()=>Nr,isBrowser:()=>Er,isDeno:()=>kr,isJsDom:()=>Or,isNode:()=>Ar,isWebWorker:()=>Dr}),Er=()=>typeof window<`u`&&window.document!==void 0,Dr=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,Or=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),kr=()=>typeof Deno<`u`,Ar=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!kr(),jr=()=>{let e;return e=Er()?`browser`:Ar()?`node`:Dr()?`webworker`:Or()?`jsdom`:kr()?`deno`:`other`,e},Mr;function Nr(){return Mr===void 0&&(Mr={library:`langchain-js`,runtime:jr()}),Mr}function Pr(e){try{return typeof process<`u`?{}[e]:kr()?Deno?.env.get(e):void 0}catch{return}}var Fr=s({BaseCallbackHandler:()=>zr,callbackHandlerPrefersChatModelStreamEvents:()=>Rr,callbackHandlerPrefersStreaming:()=>Lr,isBaseCallbackHandler:()=>Br}),Ir=class{};function Lr(e){return`lc_prefer_streaming`in e&&e.lc_prefer_streaming}function Rr(e){return`lc_prefer_chat_model_stream_events`in e&&e.lc_prefer_chat_model_stream_events}var zr=class extends Ir{lc_serializable=!1;get lc_namespace(){return[`langchain_core`,`callbacks`,this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,_e(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Pr(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`;constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return ve.prototype.toJSON.call(this)}toJSONNotImplemented(){return ve.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends zr{name=Sr();constructor(){super(),Object.assign(this,e)}}return new t}},Br=e=>{let t=e;return t!==void 0&&typeof t.copy==`function`&&typeof t.name==`string`&&typeof t.awaitHandlers==`boolean`},Vr=/^(?:[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 Hr(e){return typeof e==`string`&&Vr.test(e)}function Ur(e){if(!Hr(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Wr=[];for(let e=0;e<256;++e)Wr.push((e+256).toString(16).slice(1));function Gr(e,t=0){return(Wr[e[t+0]]+Wr[e[t+1]]+Wr[e[t+2]]+Wr[e[t+3]]+`-`+Wr[e[t+4]]+Wr[e[t+5]]+`-`+Wr[e[t+6]]+Wr[e[t+7]]+`-`+Wr[e[t+8]]+Wr[e[t+9]]+`-`+Wr[e[t+10]]+Wr[e[t+11]]+Wr[e[t+12]]+Wr[e[t+13]]+Wr[e[t+14]]+Wr[e[t+15]]).toLowerCase()}var Kr=new Uint8Array(16);function qr(){return crypto.getRandomValues(Kr)}function Jr(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Yr(e,t,n)}function Yr(e,t,n){e||={};let r=e.random??e.rng?.()??qr();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Gr(r)}function Xr(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:return t^n^r;case 2:return t&n^t&r^n&r;case 3:return t^n^r}}function Zr(e,t){return e<<t|e>>>32-t}function Qr(e){let t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(e.length+1);r.set(e),r[e.length]=128,e=r;let i=e.length/4+2,a=Math.ceil(i/16),o=Array(a);for(let t=0;t<a;++t){let n=new Uint32Array(16);for(let r=0;r<16;++r)n[r]=e[t*64+r*4]<<24|e[t*64+r*4+1]<<16|e[t*64+r*4+2]<<8|e[t*64+r*4+3];o[t]=n}o[a-1][14]=(e.length-1)*8/2**32,o[a-1][14]=Math.floor(o[a-1][14]),o[a-1][15]=(e.length-1)*8&4294967295;for(let e=0;e<a;++e){let r=new Uint32Array(80);for(let t=0;t<16;++t)r[t]=o[e][t];for(let e=16;e<80;++e)r[e]=Zr(r[e-3]^r[e-8]^r[e-14]^r[e-16],1);let i=n[0],a=n[1],s=n[2],c=n[3],l=n[4];for(let e=0;e<80;++e){let n=Math.floor(e/20),o=Zr(i,5)+Xr(n,a,s,c)+l+t[n]+r[e]>>>0;l=c,c=s,s=Zr(a,30)>>>0,a=i,i=o}n[0]=n[0]+i>>>0,n[1]=n[1]+a>>>0,n[2]=n[2]+s>>>0,n[3]=n[3]+c>>>0,n[4]=n[4]+l>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function $r(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}var ei=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,ti=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function ni(e,t,n,r,i,a){let o=typeof n==`string`?$r(n):n,s=typeof r==`string`?Ur(r):r;if(typeof r==`string`&&(r=Ur(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){if(a??=0,a<0||a+16>i.length)throw RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Gr(c)}function ri(e,t,n,r){return ni(80,Qr,e,t,n,r)}ri.DNS=ei,ri.URL=ti;var ii={};function ai(e,t,n){let r;if(e)r=si(e.random??e.rng?.()??qr(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=qr();oi(ii,e,i),r=si(i,ii.msecs,ii.seq,t,n)}return t??Gr(r)}function oi(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function si(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}var ci=`gen_ai.operation.name`,li=`gen_ai.system`,ui=`gen_ai.request.model`,di=`gen_ai.response.model`,fi=`gen_ai.usage.input_tokens`,pi=`gen_ai.usage.output_tokens`,mi=`gen_ai.usage.total_tokens`,hi=`gen_ai.request.max_tokens`,gi=`gen_ai.request.temperature`,_i=`gen_ai.request.top_p`,vi=`gen_ai.request.frequency_penalty`,yi=`gen_ai.request.presence_penalty`,bi=`gen_ai.response.finish_reasons`,xi=`gen_ai.prompt`,Si=`gen_ai.completion`,Ci=`gen_ai.request.extra_query`,wi=`gen_ai.request.extra_body`,Ti=`gen_ai.serialized.name`,Ei=`gen_ai.serialized.signature`,Di=`gen_ai.serialized.doc`,Oi=`gen_ai.response.id`,ki=`gen_ai.response.service_tier`,Ai=`gen_ai.response.system_fingerprint`,ji=`gen_ai.usage.input_token_details`,Mi=`gen_ai.usage.output_token_details`,Ni=`langsmith.trace.session_id`,Pi=`langsmith.trace.session_name`,Fi=`langsmith.span.kind`,Ii=`langsmith.trace.name`,Li=`langsmith.metadata`,Ri=`langsmith.span.tags`,zi=`langsmith.request.streaming`,Bi=`langsmith.request.headers`,Vi=`langsmith.usage_metadata`,Hi=(...e)=>fetch(...e),Ui=void 0,Wi=Symbol.for(`ls:fetch_implementation`),Gi=()=>globalThis[Wi]===void 0?!0:Ui??!1,Ki=e=>async(...t)=>{if(e||wo(`DEBUG`)===`true`){let[e,n]=t;console.log(`→ ${n?.method||`GET`} ${e}`)}let n=await(globalThis[Wi]??Hi)(...t);return(e||wo(`DEBUG`)===`true`)&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},qi=()=>wo(`PROJECT`)??Co(`LANGCHAIN_SESSION`)??`default`,Ji={};function Yi(e){Ji[e]||(console.warn(e),Ji[e]=!0)}var O=e=>BigInt(e),Xi=O(`0x9E3779B1`),Zi=O(`0x85EBCA77`),Qi=O(`0xC2B2AE3D`),$i=O(`0x9E3779B185EBCA87`),ea=O(`0xC2B2AE3D27D4EB4F`),ta=O(`0x165667B19E3779F9`),na=O(`0x85EBCA77C2B2AE63`),ra=O(`0x27D4EB2F165667C5`),ia=O(`0x165667919E3779F9`),aa=O(`0x9FB21C651E98DF25`);function oa(e){let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}var sa=oa(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),ca=(O(1)<<O(128))-O(1),la=(O(1)<<O(64))-O(1),ua=(O(1)<<O(32))-O(1),da=64,fa=da/8,pa=8,ma=4;function ha(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function ga(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function _a(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function va(e,t=0){return e[t]}var ya=e=>(e&O(255))<<O(56)|(e&O(65280))<<O(40)|(e&O(16711680))<<O(24)|(e&O(4278190080))<<O(8)|(e&O(0xff00000000))>>O(8)|(e&O(0xff0000000000))>>O(24)|(e&O(0xff000000000000))>>O(40)|(e&O(0xff00000000000000))>>O(56),ba=e=>(e=(e&O(65535))<<O(16)|(e&O(4294901760))>>O(16),e=(e&O(16711935))<<O(8)|(e&O(4278255360))>>O(8),e),xa=(e,t)=>(e&ua)*(t&ua)&la,Sa=e=>{if(!e)throw Error(`Assert failed`)};function Ca(e,t){return(e<<t|e>>O(32)-t)&ua}function wa(e,t,n){for(let r=0;r<fa;r++){let i=ga(t,r*8),a=i^ga(n,r*8);e[r^1]+=i,e[r]+=xa(a,a>>O(32))}return e}function Ta(e,t,n,r){for(let i=0;i<r;i++)wa(e,ha(t,i*da),ha(n,i*8));return e}function Ea(e,t){for(let n=0;n<fa;n++){let r=ga(t,n*8),i=e[n];i=La(i,O(47)),i^=r,i*=Xi,e[n]=i&la}return e}function Da(e,t){return ja(e[0]^ga(t,0),e[1]^ga(t,pa))}function Oa(e,t,n){let r=n;return r+=Da(e.slice(0),ha(t,0*ma)),r+=Da(e.slice(2),ha(t,4*ma)),r+=Da(e.slice(4),ha(t,8*ma)),r+=Da(e.slice(6),ha(t,12*ma)),Pa(r&la)}function ka(e,t,n,r,i){let a=Math.floor((n.byteLength-da)/8),o=da*a,s=Math.floor((t.byteLength-1)/o);for(let r=0;r<s;r++)e=Ta(e,ha(t,r*o),n,a),e=i(e,ha(n,n.byteLength-da));{let i=Math.floor((t.byteLength-1-o*s)/da);e=Ta(e,ha(t,s*o),n,i),e=r(e,ha(t,t.byteLength-da),ha(n,n.byteLength-da-7))}return e}function Aa(e,t,n){let r=new BigUint64Array([Qi,$i,ea,ta,na,Zi,ra,Xi]);Sa(e.length>128),r=ka(r,e,t,wa,Ea),Sa(r.length*8==64);{let n=Oa(r,ha(t,11),O(e.byteLength)*$i&la);return Oa(r,ha(t,t.byteLength-da-11),~(O(e.byteLength)*ea)&la)<<O(64)|n}}function ja(e,t){let n=e*t&ca;return n&la^n>>O(64)}function Ma(e,t,n){return ja((ga(e,0)^ga(t,0)+n)&la,(ga(e,8)^ga(t,8)-n)&la)}function Na(e,t,n,r,i){let a=e&la,o=e>>O(64)&la;return a+=Ma(t,r,i),a^=ga(n,0)+ga(n,8),a&=la,o+=Ma(n,ha(r,16),i),o^=ga(t,0)+ga(t,8),o&=la,o<<O(64)|a}function Pa(e){return e^=e>>O(37),e*=ia,e&=la,e^=e>>O(32),e}function Fa(e){return e^=e>>O(33),e*=ea,e&=la,e^=e>>O(29),e*=ta,e&=la,e^=e>>O(32),e}function Ia(e,t,n){let r=e.byteLength;Sa(r>0&&r<=3);let i=O(va(e,r-1))|O(r<<8)|O(va(e,0)<<16)|O(va(e,r>>1)<<24),a=(i^(O(_a(t,0))^O(_a(t,4)))+n)&la,o=(O(_a(t,8))^O(_a(t,12)))-n;return(Fa((Ca(ba(i),O(13))^o)&la)&la)<<O(64)|Fa(a)}function La(e,t){return e^e>>t}function Ra(e,t,n){let r=e.byteLength;Sa(r>=4&&r<=8);{let i=_a(e,0),a=_a(e,r-4),o=((O(i)|O(a)<<O(32))^(ga(t,16)^ga(t,24))+n&la)*($i+(O(r)<<O(2)))&ca;return o+=(o&la)<<O(65),o&=ca,o^=o>>O(67),La(La(o&la,O(35))*aa&la,O(28))|Pa(o>>O(64))<<O(64)}}function za(e,t,n){let r=e.byteLength;Sa(r>=9&&r<=16);{let i=(ga(t,32)^ga(t,40))+n&la,a=(ga(t,48)^ga(t,56))-n&la,o=ga(e),s=ga(e,r-8),c=(o^s^i)*$i,l=(c&la)+(O(r-1)<<O(54));c=c&(ca^la)|l,s^=a,c+=s+(s&ua)*(Zi-O(1))<<O(64),c&=ca,c^=ya(c>>O(64));let u=(c&la)*ea;return u+=(c>>O(64))*ea<<O(64),u&=ca,Pa(u&la)|Pa(u>>O(64))<<O(64)}}function Ba(e,t){let n=e.byteLength;return Sa(n<=16),n>8?za(e,sa,t):n>=4?Ra(e,sa,t):n>0?Ia(e,sa,t):Fa(t^ga(sa,64)^ga(sa,72))|Fa(t^ga(sa,80)^ga(sa,88))<<O(64)}function Va(e){return~e+O(1)&la}function Ha(e,t,n){let r=O(e.byteLength)*$i&la,i=O(e.byteLength-1)/O(32);for(;i>=0;){let a=Number(i);r=Na(r,ha(e,16*a),ha(e,e.byteLength-16*(a+1)),ha(t,32*a),n),i--}let a=r+(r>>O(64))&la;a=Pa(a);let o=(r&la)*$i+(r>>O(64))*na+(O(e.byteLength)-n&la)*ea;return o&=la,o=Va(Pa(o)),a|o<<O(64)}function Ua(e,t,n){let r=O(e.byteLength)*$i&la;for(let i=32;i<160;i+=32)r=Na(r,ha(e,i-32),ha(e,i-16),ha(t,i-32),n);r=Pa(r&la)|Pa(r>>O(64))<<O(64);for(let i=160;i<=e.byteLength;i+=32)r=Na(r,ha(e,i-32),ha(e,i-16),ha(t,3+i-160),n);r=Na(r,ha(e,e.byteLength-16),ha(e,e.byteLength-32),ha(t,103),Va(n));let i=r+(r>>O(64))&la;i=Pa(i);let a=(r&la)*$i+(r>>O(64))*na+(O(e.byteLength)-n&la)*ea;return a&=la,a=Va(Pa(a)),i|a<<O(64)}function Wa(e,t=O(0)){let n=e.byteLength;return n<=16?Ba(e,t):n<=128?Ha(e,sa,t):n<=240?Ua(e,sa,t):Aa(e,sa,t)}function Ga(e){let t=new Uint8Array(16),n=new DataView(t.buffer),r=e&la,i=e>>O(64);return n.setBigUint64(0,i,!1),n.setBigUint64(8,r,!1),t}var Ka=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function qa(e,t){if(!Ka.test(e)){let n=t===void 0?`Invalid UUID: ${e}`:`Invalid UUID for ${t}: ${e}`;throw Error(n)}return e}function Ja(e){return ai({msecs:typeof e==`string`?Date.parse(e):e,seq:0})}function Ya(e){if(!Ka.test(e))return null;let t=e[14];return parseInt(t,16)}function Xa(e){let t=e.replace(/-/g,``),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function Za(e){let t=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Qa=new TextEncoder;function $a(e){return Ga(Wa(Qa.encode(e)))}function eo(e,t){let n=$a(`${e}:${t}`),r=new Uint8Array(16);if(Ya(e)===7){let t=Xa(e);r.set(t.slice(0,6),0)}else{let e=Date.now();r[0]=e/1099511627776&255,r[1]=e/4294967296&255,r[2]=e/16777216&255,r[3]=e/65536&255,r[4]=e/256&255,r[5]=e&255}return r[6]=112|n[0]&15,r[7]=n[1],r[8]=128|n[2]&63,r.set(n.slice(3,10),9),Za(r)}var to={join:(...e)=>e.join(`/`),dirname:e=>e.split(`/`).slice(0,-1).join(`/`)};async function no(e){}async function ro(e,t){}async function io(e){return[]}async function ao(e){return{size:0}}function oo(e){return!1}function so(e){return``}function co(e,t){return t!==null&&Date.now()-e.createdAt>t*1e3}var lo=new class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:t}),this._metrics.hits+=1,n.value}set(e,t,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r={value:t,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,r)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&=(clearInterval(this.refreshTimer),void 0)}dump(e){let t={};for(let[e,n]of this.cache.entries())t[e]=n.value;to.dirname(e),`${e}`;try{JSON.stringify({entries:t},null,2)}catch(e){throw e}}load(e){if(!oo(e))return 0;let t;try{let n=so(e);t=JSON.parse(n).entries??null}catch{return 0}if(!t)return 0;let n=0,r=Date.now();for(let[e,i]of Object.entries(t)){if(this.cache.size>=this.maxSize)break;let t={value:i,createdAt:r};this.cache.set(e,t),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn(`Unexpected error in cache refresh loop:`,e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[t,n]of this.cache.entries())co(n,this.ttlSeconds)&&e.push([t,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[t,n]of e)if(n.refreshFunc!==void 0)try{let e=await n.refreshFunc();this.set(t,e,n.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},uo=`0.6.3`,fo,po=()=>typeof window<`u`&&window.document!==void 0,mo=()=>typeof globalThis==`object`&&globalThis.constructor&&globalThis.constructor.name===`DedicatedWorkerGlobalScope`,ho=()=>typeof window<`u`&&window.name===`nodejs`||typeof navigator<`u`&&navigator.userAgent.includes(`jsdom`),go=()=>typeof Deno<`u`,_o=()=>typeof process<`u`&&process.versions!==void 0&&process.versions.node!==void 0&&!go(),vo=()=>fo||(fo=typeof Bun<`u`?`bun`:po()?`browser`:_o()?`node`:mo()?`webworker`:ho()?`jsdom`:go()?`deno`:`other`,fo),yo;function bo(){return yo===void 0&&(yo={library:`langsmith`,runtime:vo(),sdk:`langsmith-js`,sdk_version:uo,...Eo()}),yo}function xo(){let e=So(),t={},n=[`LANGCHAIN_API_KEY`,`LANGCHAIN_ENDPOINT`,`LANGCHAIN_TRACING_V2`,`LANGCHAIN_PROJECT`,`LANGCHAIN_SESSION`,`LANGSMITH_API_KEY`,`LANGSMITH_ENDPOINT`,`LANGSMITH_TRACING_V2`,`LANGSMITH_CONFIG_FILE`,`LANGSMITH_PROJECT`,`LANGSMITH_SESSION`];for(let[r,i]of Object.entries(e))typeof i==`string`&&!n.includes(r)&&!r.toLowerCase().includes(`key`)&&!r.toLowerCase().includes(`secret`)&&!r.toLowerCase().includes(`token`)&&(r===`LANGCHAIN_REVISION_ID`?t.revision_id=i:t[r]=i);return t}function So(){let e={};try{if(typeof process<`u`)for(let[t,n]of Object.entries({}))(t.startsWith(`LANGCHAIN_`)||t.startsWith(`LANGSMITH_`))&&n!=null&&((t.toLowerCase().includes(`key`)||t.toLowerCase().includes(`secret`)||t.toLowerCase().includes(`token`))&&typeof n==`string`?e[t]=n.slice(0,2)+`*`.repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function Co(e){try{return typeof process<`u`?{}[e]:void 0}catch{return}}function wo(e){return Co(`LANGSMITH_${e}`)||Co(`LANGCHAIN_${e}`)}var To;function Eo(){if(To!==void 0)return To;let e=[`VERCEL_GIT_COMMIT_SHA`,`NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA`,`COMMIT_REF`,`RENDER_GIT_COMMIT`,`CI_COMMIT_SHA`,`CIRCLE_SHA1`,`CF_PAGES_COMMIT_SHA`,`REACT_APP_GIT_SHA`,`SOURCE_VERSION`,`GITHUB_SHA`,`TRAVIS_COMMIT`,`GIT_COMMIT`,`BUILD_VCS_NUMBER`,`bamboo_planRepository_revision`,`Build.SourceVersion`,`BITBUCKET_COMMIT`,`DRONE_COMMIT_SHA`,`SEMAPHORE_GIT_SHA`,`BUILDKITE_COMMIT`],t={};for(let n of e){let e=Co(n);e!==void 0&&(t[n]=e)}return To=t,t}function Do(){return Co(`OTEL_ENABLED`)===`true`||wo(`OTEL_ENABLED`)===`true`}var Oo=new Set([`langsmith`,`otel`]);function ko(e){if(e!==void 0)return e;let t=wo(`TRACING_MODE`);if(t!==void 0&&t!==``){let e=t.toLowerCase();if(!Oo.has(e))throw Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(t)}. Must be one of: ${[...Oo].sort().join(`, `)}`);return Do()&&console.warn(`Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence.`),e}return Do()?`otel`:`langsmith`}var Ao=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&ko()===`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 n;if(t.length===1&&typeof t[0]==`function`?n=t[0]:t.length===2&&typeof t[1]==`function`?n=t[1]:t.length===3&&typeof t[2]==`function`&&(n=t[2]),typeof n==`function`)return n()}},jo=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Ao})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},Mo=class{active(){return{}}with(e,t){return t()}},No=Symbol.for(`ls:otel_trace`),Po=Symbol.for(`ls:otel_context`),Fo=Symbol.for(`ls:otel_get_default_otlp_tracer_provider`),Io=new jo,Lo=new Mo,Ro=new class{getTraceInstance(){return globalThis[No]??Io}getContextInstance(){return globalThis[Po]??Lo}initializeGlobalInstances(e){globalThis[No]===void 0&&(globalThis[No]=e.trace),globalThis[Po]===void 0&&(globalThis[Po]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Fo]=e}getDefaultOTLPTracerComponents(){return globalThis[Fo]??void 0}};function zo(){return Ro.getTraceInstance()}function Bo(){return Ro.getContextInstance()}function Vo(){return Ro.getDefaultOTLPTracerComponents()}var Ho={llm:`chat`,tool:`execute_tool`,retriever:`embeddings`,embedding:`embeddings`,prompt:`chat`};function Uo(e){return Ho[e]||e}function Wo(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`}var Go=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(let n of e)try{if(!n.run)continue;if(n.operation===`post`){let e=this.createSpanForRun(n,n.run,t.get(n.id));e&&!n.run.end_time&&this.spans.set(n.id,e)}else this.updateSpanForRun(n,n.run)}catch(e){console.error(`Error processing operation ${n.id}:`,e)}}createSpanForRun(e,t,n){let r=n&&zo().getSpan(n);if(r)try{return this.finishSpanSetup(r,t,e)}catch(t){console.error(`Failed to create span for run ${e.id}:`,t);return}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(Error(t.error))):n.setStatus({code:1});let r=t.end_time;r&&(n.end(new Date(r)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){let t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){let e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,n){if(`run_type`in t&&t.run_type){e.setAttribute(Fi,t.run_type);let n=Uo(t.run_type||`chain`);e.setAttribute(ci,n)}`name`in t&&t.name&&e.setAttribute(Ii,t.name),`session_id`in t&&t.session_id&&e.setAttribute(Ni,t.session_id),`session_name`in t&&t.session_name&&e.setAttribute(Pi,t.session_name),this.setGenAiSystem(e,t);let r=this.extractModelName(t);r&&e.setAttribute(ui,r),t.extra?.metadata?.usage_metadata&&typeof t.extra.metadata.usage_metadata==`object`&&e.setAttribute(Vi,JSON.stringify(t.extra.metadata.usage_metadata)),`prompt_tokens`in t&&typeof t.prompt_tokens==`number`&&e.setAttribute(fi,t.prompt_tokens),`completion_tokens`in t&&typeof t.completion_tokens==`number`&&e.setAttribute(pi,t.completion_tokens),`total_tokens`in t&&typeof t.total_tokens==`number`&&e.setAttribute(mi,t.total_tokens),this.setInvocationParameters(e,t);let i=t.extra?.metadata||{};for(let[t,n]of Object.entries(i))n!=null&&e.setAttribute(`${Li}.${t}`,Wo(n)?String(n):JSON.stringify(n));let a=t.tags;if(a&&Array.isArray(a)?e.setAttribute(Ri,a.join(`, `)):a&&e.setAttribute(Ri,String(a)),`serialized`in t&&typeof t.serialized==`object`){let n=t.serialized;n.name&&e.setAttribute(Ti,String(n.name)),n.signature&&e.setAttribute(Ei,String(n.signature)),n.doc&&e.setAttribute(Di,String(n.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n=`langchain`,r=this.extractModelName(t);if(r){let e=r.toLowerCase();e.includes(`anthropic`)||e.startsWith(`claude`)?n=`anthropic`:e.includes(`bedrock`)?n=`aws.bedrock`:e.includes(`azure`)&&e.includes(`openai`)?n=`az.ai.openai`:e.includes(`azure`)&&e.includes(`inference`)?n=`az.ai.inference`:e.includes(`cohere`)?n=`cohere`:e.includes(`deepseek`)?n=`deepseek`:e.includes(`gemini`)?n=`gemini`:e.includes(`groq`)?n=`groq`:e.includes(`watson`)||e.includes(`ibm`)?n=`ibm.watsonx.ai`:e.includes(`mistral`)?n=`mistral_ai`:e.includes(`gpt`)||e.includes(`openai`)?n=`openai`:e.includes(`perplexity`)||e.includes(`sonar`)?n=`perplexity`:e.includes(`vertex`)?n=`vertex_ai`:(e.includes(`xai`)||e.includes(`grok`))&&(n=`xai`)}e.setAttribute(li,n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;let n=t.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(hi,n.max_tokens),n.temperature!==void 0&&e.setAttribute(gi,n.temperature),n.top_p!==void 0&&e.setAttribute(_i,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(vi,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(yi,n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{let n=t.run.inputs;typeof n==`object`&&n&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(ui,n.model),n.stream!==void 0&&e.setAttribute(zi,n.stream),n.extra_headers&&e.setAttribute(Bi,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Ci,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(wi,JSON.stringify(n.extra_body))),e.setAttribute(xi,JSON.stringify(n))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{let n=t.run.outputs,r=this.getUnifiedRunTokens(n);if(r&&(e.setAttribute(fi,r[0]),e.setAttribute(pi,r[1]),e.setAttribute(mi,r[0]+r[1])),n&&typeof n==`object`){if(n.model&&e.setAttribute(di,String(n.model)),n.id&&e.setAttribute(Oi,n.id),n.choices&&Array.isArray(n.choices)){let t=n.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute(bi,t.join(`, `))}if(n.service_tier&&e.setAttribute(ki,n.service_tier),n.system_fingerprint&&e.setAttribute(Ai,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata==`object`){let t=n.usage_metadata;e.setAttribute(Vi,JSON.stringify(t)),t.input_token_details&&e.setAttribute(ji,JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute(Mi,JSON.stringify(t.output_token_details))}}e.setAttribute(Si,JSON.stringify(n))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;let n=Object.keys(e);for(let r of n){let n=e[r];if(!(!n||typeof n!=`object`)&&(t=this.extractUnifiedRunTokens(n.usage_metadata),t||n.lc===1&&n.kwargs&&typeof n.kwargs==`object`&&(t=this.extractUnifiedRunTokens(n.kwargs.usage_metadata),t)))return t}let r=e.generations||[];if(!Array.isArray(r))return null;let i=Array.isArray(r[0])?r.flat():r;for(let e of i)if(typeof e==`object`&&e.message&&typeof e.message==`object`&&e.message.kwargs&&typeof e.message.kwargs==`object`&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!=`object`||typeof e.input_tokens!=`number`||typeof e.output_tokens!=`number`?null:[e.input_tokens,e.output_tokens]}},Ko=Object.prototype.toString,qo=e=>Ko.call(e)===`[object Error]`,Jo=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 Yo(e){if(!(e&&qo(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:Jo.has(t)}function Xo(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Zo(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var Qo=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function $o(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function es(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function ts({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof Qo)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),es(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=es(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!Yo(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=$o(n,i),f=Math.min(d,u);return f>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},f);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function ns(e,t={}){if(t={...t},Xo(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Zo(`factor`,t.factor,{min:0,allowInfinity:!1}),Zo(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Zo(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Zo(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await ts({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var rs=t(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),is=t(((e,t)=>{t.exports=(e,t)=>(t||=(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))})),as=t(((e,t)=>{var n=is(),r=class extends Error{constructor(e){super(e),this.name=`TimeoutError`}},i=(e,t,i)=>new Promise((a,o)=>{if(typeof t!=`number`||t<0)throw TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){a(e);return}let s=setTimeout(()=>{if(typeof i==`function`){try{a(i())}catch(e){o(e)}return}let n=typeof i==`string`?i:`Promise timed out after ${t} milliseconds`,s=i instanceof Error?i:new r(n);typeof e.cancel==`function`&&e.cancel(),o(s)},t);n(e.then(a,o),()=>{clearTimeout(s)})});t.exports=i,t.exports.default=i,t.exports.TimeoutError=r})),os=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e,t,n){let r=0,i=e.length;for(;i>0;){let a=i/2|0,o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}e.default=t})),ss=t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=os();e.default=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let i=t.default(this._queue,r,(e,t)=>t.priority-e.priority);this._queue.splice(i,0,r)}dequeue(){return this._queue.shift()?.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}})),cs=e(t((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=rs(),n=as(),r=ss(),i=()=>{},a=new n.TimeoutError;e.default=class extends t{constructor(e){if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=i,this._resolveIdle=i,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},e),!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit(`next`)}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=i,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=i,this.emit(`idle`))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let t=this._intervalEnd-e;if(t<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let t=this._queue.dequeue();return t?(this.emit(`active`),t(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((r,i)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{r(await(this._timeout===void 0&&t.timeout===void 0?e():n.default(Promise.resolve(e()),t.timeout===void 0?this._timeout:t.timeout,()=>{(t.throwOnTimeout===void 0?this._throwOnTimeout:t.throwOnTimeout)&&i(a)})))}catch(e){i(e)}this._next()},t),this._tryToStartAnother(),this.emit(`add`)})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}}))(),1),ls=`default`in cs.default?cs.default.default:cs.default,us=[408,425,429,500,502,503,504],ds=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 ls({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...n){let r=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&r>0&&this.queueSizeBytes+r>this.maxQueueSizeBytes)return Promise.reject(Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${r} bytes.`));r>0&&(this.queueSizeBytes+=r);let i=this.onFailedResponseHook,a=this.queue.add(()=>ns(()=>t(...n).catch(e=>{throw e instanceof Error?e:Error(e)}),{async onFailedAttempt({error:e}){if(typeof e!=`object`||!e)throw e;let t=`message`in e&&typeof e.message==`string`?e.message:void 0;if(t?.startsWith(`Cancel`)||t?.startsWith(`TimeoutError`)||t?.startsWith(`AbortError`)||`name`in e&&e.name===`TimeoutError`||`code`in e&&e.code===`ECONNABORTED`)throw e;let n=`response`in e?e.response:void 0;if(i&&await i(n))return;let r=n?.status??(`status`in e?e.status:void 0);if(r!=null&&(typeof r==`number`||typeof r==`string`)&&!us.includes(+r))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return r>0&&(a=a.finally(()=>{this.queueSizeBytes-=r})),e.signal?Promise.race([a,new Promise((t,n)=>{e.signal?.addEventListener(`abort`,()=>{n(Error(`AbortError`))})})]):a}};function fs(e){return typeof e?._getType==`function`}function ps(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}function ms(e){return`Invalid prompt identifier format: "${e}". Expected one of:\n - "prompt-name" (for private prompts)\n - "owner/prompt-name" (for prompts with explicit owner)\n - "prompt-name:commit-hash" (with commit reference)\n - "owner/prompt-name:commit-hash" (with owner and commit)`}var hs=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=`LangSmithConflictError`,this.status=409}},gs=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=`LangSmithNotFoundError`,this.status=404}};function _s(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithNotFoundError`}function vs(e){return typeof e==`object`&&!!e&&`name`in e&&e?.name===`LangSmithConflictError`}async function k(e,t,n){let r;if(e.ok){n&&(r=await e.text());return}if(e.status===403)try{(await e.json())?.error===`org_scoped_key_requires_workspace`&&(r=`This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.`)}catch{let t=Error(`${e.status} ${e.statusText}`);throw t.status=e?.status,t}if(r===void 0)try{r=await e.text()}catch{r=``}let i=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(e.status===404)throw new gs(i);if(e.status===409)throw new hs(i);let a=Error(i);throw a.status=e.status,a}var ys=`ERR_CONFLICTING_ENDPOINTS`,bs=class extends Error{constructor(){super(`You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS.`),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:ys}),this.name=`ConflictingEndpointsError`}};function xs(e){return typeof e==`object`&&!!e&&e.code===ys}function Ss(e){if(!e||e.split(`/`).length>2||e.startsWith(`/`)||e.endsWith(`/`)||e.split(`:`).length>2)throw Error(ms(e));let[t,n]=e.split(`:`),r=n||`latest`;if(t.includes(`/`)){let[n,i]=t.split(`/`,2);if(!n||!i)throw Error(ms(e));return[n,i,r]}else{if(!t)throw Error(ms(e));return[`-`,t,r]}}var Cs=`langsmith-cli`,ws=6e4,Ts=1e4;function Es(){let e=vo();return e===`browser`||e===`webworker`}function Ds(){let e=Co(`LANGSMITH_CONFIG_FILE`);if(e)return e;let t=Co(`HOME`)??Co(`USERPROFILE`);if(t)return to.join(t,`.langsmith`,`config.json`)}function Os(e){let t=Co(`LANGSMITH_PROFILE`);if(t)return t;if(e.current_profile)return e.current_profile;if(e.profiles?.default)return`default`}function ks(){if(Es())return;let e=Ds();if(!(!e||!oo(e)))try{let t=JSON.parse(so(e)),n=Os(t),r=n?t.profiles?.[n]:void 0;return!n||!r?void 0:{configPath:e,config:t,profileName:n,profile:r}}catch{return}}function As(e){return e!=null&&e.trim()!==``}function js(e){return e?.trim().replace(/^["']|["']$/g,``)}function Ms(e){let t=e.oauth;if(!t?.refresh_token)return!1;if(!t.access_token)return!0;if(!t.expires_at)return!1;let n=Date.parse(t.expires_at);return!Number.isNaN(n)&&n<=Date.now()+ws}function Ns(e){let t=e;for(;t.endsWith(`/`);)t=t.slice(0,-1);return t.endsWith(`/api/v1`)?t.slice(0,-7):t}function Ps(e,t){e.oauth??={},t.access_token&&(e.oauth.access_token=t.access_token),t.refresh_token&&(e.oauth.refresh_token=t.refresh_token),typeof t.expires_in==`number`&&t.expires_in>0&&(e.oauth.expires_at=new Date(Date.now()+t.expires_in*1e3).toISOString())}function Fs(e){return e.reason??Error(`The operation was aborted.`)}async function Is(e,t){if(!t)return e;if(t.aborted)throw Fs(t);let n,r=new Promise((e,r)=>{let i=()=>{r(Fs(t))};t.addEventListener(`abort`,i,{once:!0}),n=()=>{t.removeEventListener(`abort`,i)}});try{return await Promise.race([e,r])}finally{n?.()}}function Ls(){let e=ks(),t=e?.profile;if(!e||!t)return{};let n=js(t.api_key),r=js(t.oauth?.access_token),i=js(t.oauth?.refresh_token);return{apiUrl:t.api_url,apiKey:n,workspaceId:t.workspace_id,oauthAccessToken:r,oauthRefreshToken:i,profileAuth:n||r||i?new Rs(e):void 0}}var Rs=class{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(){let e=zs(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,t){Ms(this.state.profile)&&(this.refreshPromise||=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0}),await Is(this.refreshPromise,t));let n=Bs(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}async refreshOAuthToken(e){let t=this.state.profile.oauth?.refresh_token;if(!t)return;let n=js(this.state.profile.api_url)??`https://api.smith.langchain.com`;try{let r=new URLSearchParams({grant_type:`refresh_token`,client_id:Cs,refresh_token:t}),i=await e(`${Ns(n)}/oauth/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:r.toString(),signal:AbortSignal.timeout(Ts)});if(!i.ok)return;let a=await i.json();if(!a.access_token)return;Ps(this.state.profile,a),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await ro(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}\n`)}catch{return}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name===`Authorization`?e.value:void 0}};function zs(e){let t=js(e.oauth?.access_token);if(t)return{name:`Authorization`,value:`Bearer ${t}`};if(!js(e.oauth?.refresh_token))return Bs(e)}function Bs(e){let t=js(e.oauth?.access_token);if(t)return{name:`Authorization`,value:`Bearer ${t}`};let n=js(e.api_key);if(n)return{name:`x-api-key`,value:n}}var Vs=`[...]`,Hs={result:`[Circular]`},Us=[],Ws=[],Gs=new TextEncoder;function Ks(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function qs(e){return Gs.encode(e)}function Js(e){if(e&&typeof e==`object`&&e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e==`bigint`)return e.toString();return e}function Ys(e){return function(t,n){if(e){let r=e.call(this,t,n);if(r!==void 0)return r}return Js(n)}}function Xs(e){try{let t=new Set,n=0,r=typeof Buffer<`u`&&typeof Buffer.byteLength==`function`?e=>Buffer.byteLength(e,`utf8`):e=>e.length;function i(e){let t=r(e);return t>n&&(n=t),t+2}function a(e){return e===0?2:2+e*4}function o(e){return e===void 0||typeof e==`function`||typeof e==`symbol`}function s(e){return e===void 0||typeof e==`function`||typeof e==`symbol`?4:c(e)}function c(e){if(e===null)return 4;if(e===void 0)return 0;let n=typeof e;if(n===`boolean`)return 5;if(n===`number`)return Number.isFinite(e)?e.toString().length:4;if(n===`bigint`)return e.toString().length+2;if(n===`string`)return i(e);if(n===`function`||n===`symbol`)return 0;let l=e;if(l instanceof Date)return 26;if(l instanceof RegExp)return r(l.toString())+2;if(l instanceof Error){let e=l.name??``,t=l.message??``;return 22+r(e)+r(t)}if(typeof Buffer<`u`&&l instanceof Buffer)return 28+a(l.byteLength);if(ArrayBuffer.isView(l))return l instanceof DataView?2:2+(l.length??0)*(l instanceof Float32Array||l instanceof Float64Array?30:12);if(l instanceof ArrayBuffer)return 2;if(t.has(l))return 24;if(typeof l.toJSON==`function`){let e;try{e=l.toJSON(``)}catch{return 16}t.add(l);let n=c(e);return t.delete(l),n}t.add(l);let u;if(Array.isArray(l)){u=2;let e=l.length;for(let t=0;t<e;t++)u+=s(l[t]),t<e-1&&(u+=1)}else if(l instanceof Map){u=2;let e=0;for(let[t,n]of l)o(n)||(e>0&&(u+=1),u+=r(typeof t==`string`?t:String(t))+3,u+=c(n),e++)}else if(l instanceof Set){u=2;let e=0;for(let t of l)e>0&&(u+=1),u+=s(t),e++}else{u=2;let e=0,t=Object.keys(l);for(let n=0;n<t.length;n++){let i=t[n],a=l[i];o(a)||(e>0&&(u+=1),u+=r(i)+3,u+=c(a),e++)}}return t.delete(l),u}return{size:c(e),maxStringLen:n}}catch{return{size:Zs(e).length,maxStringLen:0}}}function Zs(e,t,n,r,i){try{return qs(JSON.stringify(e,Ys(n),r))}catch(a){if(!a.message?.includes(`Converting circular structure to JSON`))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`\nContext: ${t}`:``}`),qs(`[Unserializable]`);wo(`SUPPRESS_CIRCULAR_JSON_WARNINGS`)!==`true`&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`\nContext: ${t}`:``}`),i===void 0&&(i=Ks()),$s(e,``,0,[],void 0,0,i);let o;try{o=Ws.length===0?JSON.stringify(e,n,r):JSON.stringify(e,ec(n),r)}catch{return qs(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;Us.length!==0;){let e=Us.pop();e.length===4?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return qs(o)}}function Qs(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,Us.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),Us.push([r,n,t,i])):Ws.push([t,n,e])}function $s(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){Qs(Hs,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){Qs(Vs,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){Qs(Vs,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)$s(e[s],s,s,r,e,a,o);else{e=Js(e);var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];$s(e[l],l,s,r,e,a,o)}}r.pop()}}function ec(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(Ws.length>0)for(var r=0;r<Ws.length;r++){var i=Ws[r];if(i[1]===t&&i[0]===n){n=i[2],Ws.splice(r,1);break}}return e.call(this,t,n)}}var tc=class{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;let t=this.nextId++;return new Promise((n,r)=>{this.pending.set(t,{resolve:n,reject:r});try{this.worker.postMessage({id:t,op:`serialize`,payload:e})}catch(e){this.pending.delete(t),r(e)}})}async terminate(){this.worker&&=(await this.worker.terminate(),null);for(let[,e]of this.pending)e.reject(Error(`worker terminated`));this.pending.clear()}},nc=null;function rc(){return nc===null&&(nc=new tc),nc}var ic=64*1024,ac=2048;function oc(e,t=ic,n=ac){if(typeof e!=`object`||!e)return typeof e==`string`&&e.length>=t;let r=[e],i=new Set,a=0;for(;r.length>0;){if(a++>=n)return!1;let e=r.pop();if(e==null)continue;let o=typeof e;if(o===`string`){if(e.length>=t)return!0;continue}if(o!==`object`)continue;let s=e;if(i.has(s)||(i.add(s),s instanceof Date||s instanceof RegExp||s instanceof Error||s instanceof ArrayBuffer||ArrayBuffer.isView(s)))continue;if(Array.isArray(s)){for(let e=s.length-1;e>=0;e--)r.push(s[e]);continue}if(s instanceof Map){for(let[,e]of s)r.push(e);continue}if(s instanceof Set){for(let e of s)r.push(e);continue}let c=Object.keys(s);for(let e=c.length-1;e>=0;e--)r.push(s[c[e]])}return!1}function sc(e,t){let[n]=Ss(e);if(n!==`-`&&!t)throw 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 cc(e){return typeof e==`string`&&e.length>0&&!e.includes(`Z`)&&!e.includes(`+`)&&!e.includes(`-`,10)?e+`Z`:e}function lc(e){return{...e,start_time:cc(e.start_time),end_time:cc(e.end_time)}}function uc(e,t,n){if(n)return e;let r=bo(),i=t??xo(),a=e.extra??{},o=a.metadata;return e.extra={...a,runtime:{...r,...a?.runtime},metadata:{...i,...i.revision_id||`revision_id`in e&&e.revision_id?{revision_id:(`revision_id`in e?e.revision_id:void 0)??i.revision_id}:{},...o}},e}var dc=e=>{let t=e?.toString()??wo(`TRACING_SAMPLING_RATE`);if(t===void 0)return;let n=parseFloat(t);if(n<0||n>1)throw Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},fc=e=>{let t=e.replace(`http://`,``).replace(`https://`,``).split(`/`)[0].split(`:`)[0];return t===`localhost`||t===`127.0.0.1`||t===`::1`};async function pc(e){let t=[];for await(let n of e)t.push(n);return t}function mc(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,`$1`).replace(/^'(.*)'$/,`$1`)}var hc=async e=>{if(e?.status===429){let t=parseInt(e.headers.get(`retry-after`)??`10`,10)*1e3;if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function gc(e){return typeof e==`number`?Number(e.toFixed(4)):e}var _c=1e4,vc=100,yc=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??1073741824}peek(){return this.items[0]}push(e){let t,n=new Promise(e=>{t=e}),r=Xs(e.item).size;return this.sizeBytes+r>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${r} bytes.`),t(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:r}),this.sizeBytes+=r,n)}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw Error(`Number of bytes to pop off may not be less than 1.`);let n=[],r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<t;){let e=this.items.shift();e&&(n.push(e),r+=e.size,this.sizeBytes-=e.size)}if(n.length===0&&this.items.length>0){let e=this.items.shift();n.push(e),r+=e.size,this.sizeBytes-=e.size}return[n.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>n.forEach(e=>e.itemPromiseResolve())]}},bc=class e{get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||Ki(this.debug);return(async(t,n)=>{let r,i=this.getProfileManagedAuthorizationHeader(n);return this.apiKey===void 0?this.hasExplicitAuthHeader(n,i)||(r=await this.profileAuth?.getAuthHeader(e,n?.signal)):r={name:`x-api-key`,value:`${this.apiKey}`},e(t,this.applyCurrentAuthHeaders(n,r,i))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let t=new Headers(e.headers).get(`Authorization`);if(As(t))return this.profileAuth.isProfileAuthorizationHeader(t??``)?t??void 0:void 0}isProfileManagedAuthorizationHeader(e,t){return e===t||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,t){if(!e?.headers)return!1;let n=new Headers(e.headers);if(As(n.get(`x-api-key`)))return!0;let r=n.get(`Authorization`);return As(r)?!this.isProfileManagedAuthorizationHeader(r??``,t):!1}applyCurrentAuthHeaders(e,t,n){if(!t)return e;let r=e=>{if(this.apiKey!==void 0&&t.name===`x-api-key`)return e.delete(`Authorization`),e.has(`x-api-key`)||e.set(`x-api-key`,t.value),e;if(t.name===`Authorization`){if(As(e.get(`x-api-key`)))return e;let r=e.get(`Authorization`);return As(r)&&!this.isProfileManagedAuthorizationHeader(r??``,n)||e.set(`Authorization`,t.value),e}let r=e.get(`Authorization`);return As(r)&&!this.isProfileManagedAuthorizationHeader(r??``,n)?e:(As(r)&&e.delete(`Authorization`),e.has(`x-api-key`)||e.set(`x-api-key`,t.value),e)};if(!e)return{headers:{[t.name]:t.value}};if(e.headers instanceof Headers||Array.isArray(e.headers))return{...e,headers:r(new Headers(e.headers))};let i={...e.headers??{}},a=e=>Object.keys(i).find(t=>t.toLowerCase()===e),o=e=>{let t=a(e);return t?i[t]:void 0},s=As(o(`x-api-key`)),c=o(`authorization`),l=As(c)&&!this.isProfileManagedAuthorizationHeader(c??``,n);if(this.apiKey!==void 0&&t.name===`x-api-key`){let n=a(`authorization`);return n&&delete i[n],s||(i[`x-api-key`]=t.value),{...e,headers:i}}if(t.name===`Authorization`){if(!s&&!l){let e=a(`authorization`);e&&e!==`Authorization`&&delete i[e],i.Authorization=t.value}return{...e,headers:i}}if(!l){let e=a(`authorization`);e&&delete i[e],s||(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||!oc(e)||(this._serializeWorker===void 0&&(this._serializeWorker=rc()),this._serializeWorker===null))return Zs(e,t);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,Zs(e,t)):n}catch{return Zs(e,t)}}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Co(`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:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:wo(`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:Co(`LANGSMITH_DEBUG`)===`true`});let n=e.getDefaultClientConfig();this.tracingSampleRate=dc(t.tracingSamplingRate),this.apiUrl=mc(t.apiUrl??n.apiUrl)??``,this.apiUrl.endsWith(`/`)&&(this.apiUrl=this.apiUrl.slice(0,-1));let r=mc(t.apiKey??n.apiKey);if(this.apiKey=As(r)?r:void 0,this.profileAuth=this.apiKey===void 0?n.profileAuth:void 0,this.webUrl=mc(t.webUrl??n.webUrl),this.webUrl?.endsWith(`/`)&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=mc(t.workspaceId??n.workspaceId),this.timeout_ms=t.timeout_ms??9e4,this.caller=new ds({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw Error(`Trace batch concurrency must be positive.`);this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.failedTracesDir=wo(`FAILED_TRACES_DIR`)||void 0;let i=wo(`FAILED_TRACES_MAX_MB`);if(i){let e=parseInt(i,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=e*1024*1024)}let a=t.maxIngestMemoryBytes??1073741824;this.batchIngestCaller=new ds({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:a,...t.callerOptions??{},onFailedResponseHook:hc,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.hideMetadata=t.hideMetadata??n.hideMetadata,this.omitTracedRuntimeInfo=t.omitTracedRuntimeInfo??!1,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new yc(a),this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,this._tracingMode=ko(t.tracingMode),this._tracingMode===`otel`&&(this.langSmithToOTELTranslator=new Go),this.cachedLSEnvVarsForMetadata=xo(),t.cache!==void 0&&t.disablePromptCache&&Yi(`Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value.`),t.cache===void 0?t.disablePromptCache||(this._promptCache=lo):(Yi(`The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client.`),t.cache===!1?this._promptCache=void 0:t.cache===!0?this._promptCache=lo:this._promptCache=t.cache),this._customHeaders=t.headers??{}}static getDefaultClientConfig(){let e=Ls(),t=wo(`API_KEY`),n=wo(`ENDPOINT`),r=wo(`WORKSPACE_ID`),i=As(t),a=n??e.apiUrl??`https://api.smith.langchain.com`,o=r??e.workspaceId;return{apiUrl:a,apiKey:t,webUrl:void 0,hideInputs:wo(`HIDE_INPUTS`)===`true`,hideOutputs:wo(`HIDE_OUTPUTS`)===`true`,hideMetadata:wo(`HIDE_METADATA`)===`true`,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:fc(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(){let e={"User-Agent":`langsmith-js/${uo}`,...this._customHeaders};if(this.apiKey!==void 0)e[`x-api-key`]=`${this.apiKey}`;else{let t=this.profileAuth?.currentAuthHeader();t&&(e[t.name]=t.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(e=>{if(e.name===`new_token`){let{kwargs:t,...n}=e;return n}return e})}async prepareRunCreateOrUpdateInputs(e){let t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t.extra!=null&&`metadata`in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events!==void 0&&(t.events=this._filterNewTokenEvents(t.events)),t}async _getResponse(e,t){let n=t?.toString()??``,r=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let t=await this._fetch(r,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let r=Number(t.get(`offset`))||0,i=Number(t.get(`limit`))||100;for(;;){t.set(`offset`,String(r)),t.set(`limit`,String(i));let a=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{let t=await this._fetch(a,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`fetch ${e}`),t}),s=n?n(await o.json()):await o.json();if(s.length===0||(yield s,s.length<i))break;r+=s.length}}async*_getCursorPaginatedList(e,t=null,n=`POST`,r=`runs`){let i=t?{...t}:{};for(;;){let t=JSON.stringify(i),a=await(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await k(r,`fetch ${e}`),r})).json();if(!a||!a[r])break;yield a[r];let o=a.cursors;if(!o||!o.next)break;i.cursor=o.next}}_shouldSample(){return this.tracingSampleRate===void 0||Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){let t=[];for(let n of e)this.filteredPostUuids.has(n.trace_id)?n.id===n.trace_id&&this.filteredPostUuids.delete(n.trace_id):t.push(n);return t}else{let t=[];for(let n of e){let e=n.trace_id??n.id;this.filteredPostUuids.has(e)||(n.id===e?this._shouldSample()?t.push(n):this.filteredPostUuids.add(e):t.push(n))}return t}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??25165824}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??vc}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[r,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!r.length){i();break}let a=r.reduce((e,t)=>{let n=t.apiUrl??this.apiUrl,r=t.apiKey??this.apiKey,i=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?`default`:`${n}|${r}`;return e[i]||(e[i]=[]),e[i].push(t),e},{}),o=[];for(let[e,t]of Object.entries(a)){let n=this._processBatch(t,{apiUrl:e==="default"?void 0:e.split(`|`)[0],apiKey:e==="default"?void 0:e.split(`|`)[1]});o.push(n)}let s=Promise.all(o).finally(i);n.push(s)}return Promise.all(n)}static async _writeTraceToFallbackDir(t,n,r,i,a){try{let o=typeof n==`string`?Buffer.from(n,`utf8`):Buffer.from(n),s=JSON.stringify({version:1,endpoint:i,headers:r,body_base64:o.toString(`base64`)}),c=`trace_${Date.now()}_${Jr().slice(0,8)}.json`,l=to.join(t,c);if(e._fallbackDirsCreated.has(t)||(await no(t),e._fallbackDirsCreated.add(t)),a!==void 0&&a>0)try{let e=(await io(t)).filter(e=>e.startsWith(`trace_`)&&e.endsWith(`.json`)),n=0;for(let r of e){let{size:e}=await ao(to.join(t,r));n+=e}if(n>=a){console.warn(`Could not write trace to fallback dir ${t} as it's already over size limit (${n} bytes >= ${a} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await ro(l,s),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(e){console.error(`LangSmith tracing error: could not write trace to fallback dir ${t}:`,e)}}async _processBatch(e,t){if(!e.length)return;let n=e.reduce((e,t)=>e+(t.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let r={runCreates:e.filter(e=>e.action===`create`).map(e=>e.item),runUpdates:e.filter(e=>e.action===`update`).map(e=>e.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let e=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(r,{...t,useGzip:e,sizeBytes:n})}catch(e){if(_s(e))this._multipartDisabled=!0,await this.batchIngestRuns(r,{...t,sizeBytes:n});else throw e}}else await this.batchIngestRuns(r,{...t,sizeBytes:n})}}catch(e){console.error(`Error exporting batch:`,e)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let t=new Map,n=[];for(let r of e)r.item.id&&r.otelContext&&(t.set(r.item.id,r.otelContext),r.action===`create`?n.push({operation:`post`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):n.push({operation:`patch`,id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=uc(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;let n=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>r)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r}))},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){let e=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/info`,{method:`GET`,headers:{...this._mergedHeaders,Accept:`application/json`},signal:AbortSignal.timeout(_c),...this.fetchOptions});return await k(e,`get server info`),e})).json();return this.debug&&console.log(`
|
|
9
9
|
=== LangSmith Server Configuration ===
|
|
10
10
|
`+JSON.stringify(e,null,2)+`
|
|
11
11
|
`),e}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??`Unspecified status code`} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||=this._get(`/settings`),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){let e=zo(),t=Bo();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;let n={...this._mergedHeaders,"Content-Type":`application/json`},r=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let e=this._cloneCurrentOTELContext();this.processRunOperation({action:`create`,item:i,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}let a=uc(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);t?.apiKey!==void 0&&(n[`x-api-key`]=t.apiKey),t?.workspaceId!==void 0&&(n[`x-tenant-id`]=t.workspaceId);let o=Zs(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:`POST`,headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(e,`create run`,!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let r=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),i=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(r.length>0&&i.length>0){let e=r.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let n of i)n.id!==void 0&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);r=Object.values(e),i=t}let a={post:r,patch:i};if(!a.post.length&&!a.patch.length)return;let o={post:[],patch:[]};for(let e of[`post`,`patch`]){let t=e,n=a[t].reverse(),r=n.pop();for(;r!==void 0;)o[t].push(r),r=n.pop()}if(o.post.length>0||o.patch.length>0){let e=o.post.map(e=>e.id).concat(o.patch.map(e=>e.id)).join(`,`);await this._postBatchIngestRuns(await this._serializeBody(o,`Ingesting runs with ids: ${e}`),n)}}async _postBatchIngestRuns(e,t){let n={...this._mergedHeaders,"Content-Type":`application/json`,Accept:`application/json`};t?.apiKey!==void 0&&(n[`x-api-key`]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{let r=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:`POST`,headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await k(r,`batch create run`,!0),r})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(e===void 0&&t===void 0)return;let r={},i=[];for(let t of e??[]){let e=await this.prepareRunCreateOrUpdateInputs(t);e.id!==void 0&&e.attachments!==void 0&&(r[e.id]=e.attachments),delete e.attachments,i.push(e)}let a=[];for(let e of t??[])a.push(await this.prepareRunCreateOrUpdateInputs(e));if(i.find(e=>e.trace_id===void 0||e.dotted_order===void 0)!==void 0)throw Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`);if(a.find(e=>e.trace_id===void 0||e.dotted_order===void 0)!==void 0)throw Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`);if(i.length>0&&a.length>0){let e=i.reduce((e,t)=>(t.id&&(e[t.id]=t),e),{}),t=[];for(let n of a)n.id!==void 0&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);i=Object.values(e),a=t}if(i.length===0&&a.length===0)return;let o=[],s=[];for(let[e,t]of[[`post`,i],[`patch`,a]])for(let n of t){let{inputs:t,outputs:i,events:a,extra:c,error:l,serialized:u,attachments:d,...f}=n,p={inputs:t,outputs:i,events:a,extra:c,error:l,serialized:u},m=await this._serializeBody(f,`Serializing for multipart ingestion of run with id: ${f.id}`);s.push({name:`${e}.${f.id}`,payload:new Blob([m],{type:`application/json; length=${m.length}`})});for(let[t,n]of Object.entries(p)){if(n===void 0)continue;let r=await this._serializeBody(n,`Serializing ${t} for multipart ingestion of run with id: ${f.id}`);s.push({name:`${e}.${f.id}.${t}`,payload:new Blob([r],{type:`application/json; length=${r.length}`})})}if(f.id!==void 0){let e=r[f.id];if(e){delete r[f.id];for(let[t,n]of Object.entries(e)){let e,r;if(Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(`.`)){console.warn(`Skipping attachment '${t}' for run ${f.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}s.push({name:`attachment.${f.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}}o.push(`trace=${f.trace_id},id=${f.id}`)}await this._sendMultipartRequest(s,o.join(`; `),n)}async _createNodeFetchBody(e,t){let n=[];for(let r of e)n.push(new Blob([`--${t}\r\n`])),n.push(new Blob([`Content-Disposition: form-data; name="${r.name}"\r\n`,`Content-Type: ${r.payload.type}\r\n\r\n`])),n.push(r.payload),n.push(new Blob([`\r
|
|
12
12
|
`]));return n.push(new Blob([`--${t}--\r\n`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,t){let n=new TextEncoder;return new ReadableStream({async start(r){let i=async e=>{typeof e==`string`?r.enqueue(n.encode(e)):r.enqueue(e)};for(let n of e){await i(`--${t}\r\n`),await i(`Content-Disposition: form-data; name="${n.name}"\r\n`),await i(`Content-Type: ${n.payload.type}\r\n\r\n`);let e=n.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)r.enqueue(t.value)}finally{e.releaseLock()}await i(`\r
|
|
13
13
|
`)}await i(`--${t}--\r\n`),r.close()}})}async _sendMultipartRequest(t,n,r){let i=`----LangSmithFormBoundary`+Math.random().toString(36).slice(2),a=()=>this._createNodeFetchBody(t,i),o=()=>this._createMultipartStream(t,i),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let t=await e(),n={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};r?.apiKey!==void 0&&(n[`x-api-key`]=r.apiKey);let a=t;r?.useGzip&&typeof t==`object`&&`pipeThrough`in t&&(a=t.pipeThrough(new CompressionStream(`gzip`)),n[`Content-Encoding`]=`gzip`);let o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:`POST`,headers:n,body:a,duplex:`half`,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(o,`Failed to send multipart request`,!0),o});try{let e,t=!1;Gi()&&!this.multipartStreamingDisabled&&vo()!==`bun`?(t=!0,e=await s(o)):e=await s(a),(!this.multipartStreamingDisabled||t)&&e.status===422&&(r?.apiUrl??this.apiUrl)!==`https://api.smith.langchain.com`&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,e=await s(a))}catch(r){if(_s(r))throw r;if(console.warn(`${r.message.trim()}\n\nContext: ${n}`),this.failedTracesDir){let n=await this._createNodeFetchBody(t,i).catch(()=>null);n&&await e._writeTraceToFallbackDir(this.failedTracesDir,n,{"Content-Type":`multipart/form-data; boundary=${i}`},`runs/multipart`,this.failedTracesMaxBytes)}}}async updateRun(e,t,n){qa(e),t.inputs&&=await this.processInputs(t.inputs),t.outputs&&=await this.processOutputs(t.outputs),t.extra!=null&&`metadata`in t.extra&&(t.extra={...t.extra,metadata:await this.processMetadata(t.extra.metadata)}),t.events&&=this._filterNewTokenEvents(t.events);let r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&r.trace_id!==void 0&&r.dotted_order!==void 0){let e=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&r.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:`update`,item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:`update`,item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this._mergedHeaders,"Content-Type":`application/json`};n?.apiKey!==void 0&&(i[`x-api-key`]=n.apiKey),n?.workspaceId!==void 0&&(i[`x-tenant-id`]=n.workspaceId);let a=Zs(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let t=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:`PATCH`,headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(t,`update run`,!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){qa(e);let n=lc(await this._get(`/runs/${e}`));return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(t!==void 0){let e;e=t.session_id?t.session_id:n?.projectName?(await this.readProject({projectName:n?.projectName})).id:n?.projectId?n?.projectId:(await this.readProject({projectName:wo(`PROJECT`)||`default`})).id;let r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${e}/r/${t.id}?poll=true`}else if(e!==void 0){let t=await this.readRun(e);if(!t.app_path)throw Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}else throw Error(`Must provide either runId or run`)}async _loadChildRuns(e){let t=await pc(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},r={};t.sort((e,t)=>(e?.dotted_order??``).localeCompare(t?.dotted_order??``));for(let i of t){if(i.parent_run_id===null||i.parent_run_id===void 0)throw Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??``)&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),r[i.id]=i)}e.child_runs=n[e.id]||[];for(let t in n)t!==e.id&&(r[t].child_runs=n[t]);return e}async*listRuns(e){let{projectId:t,projectName:n,parentRunId:r,traceId:i,referenceExampleId:a,startTime:o,executionOrder:s,isRoot:c,runType:l,error:u,id:d,query:f,filter:p,traceFilter:m,treeFilter:h,limit:g,select:_,order:v}=e,y=[];if(t&&(y=Array.isArray(t)?t:[t]),n){let e=Array.isArray(n)?n:[n],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));y.push(...t)}let b={session:y.length?y:null,run_type:l,reference_example:a,query:f,filter:p,trace_filter:m,tree_filter:h,execution_order:s,parent_run:r,start_time:o?o.toISOString():null,error:u,id:d,limit:g,trace:i,select:_||`app_path.completion_cost.completion_tokens.dotted_order.end_time.error.events.extra.feedback_stats.first_token_time.id.inputs.name.outputs.parent_run_id.parent_run_ids.prompt_cost.prompt_tokens.reference_example_id.run_type.session_id.start_time.status.tags.total_cost.total_tokens.trace_id`.split(`.`),is_root:c,order:v};b.select.includes(`child_run_ids`)&&Yi(`Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.`);let x=0;for await(let e of this._getCursorPaginatedList(`/runs/query`,b)){let t=e.map(lc);if(g){if(x>=g)break;if(t.length+x>g){yield*t.slice(0,g-x);break}x+=t.length,yield*t}else yield*t}}async*listGroupRuns(e){let{projectId:t,projectName:n,groupBy:r,filter:i,startTime:a,endTime:o,limit:s,offset:c}=e,l={session_id:t||(await this.readProject({projectName:n})).id,group_by:r,filter:i,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(s)||100},u=Number(c)||0,d=`/runs/group`,f=`${this.apiUrl}${d}`;for(;;){let e={...l,offset:u},t=Object.fromEntries(Object.entries(e).filter(([e,t])=>t!==void 0)),n=JSON.stringify(t),{groups:r,total:i}=await(await this.caller.call(async()=>{let e=await this._fetch(f,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await k(e,`Failed to fetch ${d}`),e})).json();if(r.length===0)break;for(let e of r)yield e;if(u+=r.length,u>=i)break}}async*readThread(e){let{threadId:t,projectId:n,projectName:r,isRoot:i=!0,limit:a,filter:o,order:s=`asc`}=e;if(!n&&!r)throw Error(`threadId requires projectId or projectName`);let c=`eq(thread_id, ${JSON.stringify(t)})`,l=o?`and(${c}, ${o})`:c;yield*this.listRuns({projectId:n??void 0,projectName:r??void 0,isRoot:i,limit:a,filter:l,order:s})}async listThreads(e){let{projectId:t,projectName:n,limit:r,offset:i=0,filter:a,startTime:o,isRoot:s=!0}=e;if(!t&&!n)throw Error(`Either projectId or projectName must be provided`);if(t&&n)throw Error(`Provide exactly one of projectId or projectName`);let c=t??(await this.readProject({projectName:n})).id,l=o??new Date(Date.now()-1440*60*1e3),u={session:[c],is_root:s,limit:100,order:`desc`,select:[`id`,`name`,`status`,`start_time`,`end_time`,`thread_id`,`trace_id`,`run_type`,`error`,`tags`,`session_id`,`parent_run_id`,`total_tokens`,`total_cost`,`dotted_order`,`reference_example_id`,`feedback_stats`,`app_path`,`completion_cost`,`completion_tokens`,`prompt_cost`,`prompt_tokens`,`first_token_time`],start_time:l.toISOString()};a!=null&&(u.filter=a);let d=new Map;for await(let e of this._getCursorPaginatedList(`/runs/query`,u))for(let t of e){let e=lc(t),n=e.thread_id;if(n){let t=d.get(n)??[];t.push(e),d.set(n,t)}}let f=[];for(let[e,t]of d.entries()){t.sort((e,t)=>{let n=e,r=t,i=n.start_time??``,a=r.start_time??``;if(i!==a)return i.localeCompare(a);let o=n.dotted_order??``,s=r.dotted_order??``;return o.localeCompare(s)});let n=[...t.map(e=>e.start_time).filter(Boolean)].sort(),r=n.length?n[0]:``,i=n.length?n[n.length-1]:``;f.push({thread_id:e,runs:t,count:t.length,filter:``,total_tokens:0,total_cost:null,min_start_time:r,max_start_time:i,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:``,last_outputs:``,last_error:null})}f.sort((e,t)=>{let n=e.max_start_time??``;return(t.max_start_time??``).localeCompare(n)});let p=i>0?f.slice(i):f;return r===void 0?p:p.slice(0,r)}async getRunStats({id:e,trace:t,parentRun:n,runType:r,projectNames:i,projectIds:a,referenceExampleIds:o,startTime:s,endTime:c,error:l,query:u,filter:d,traceFilter:f,treeFilter:p,isRoot:m,dataSourceType:h}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);let _=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:n,run_type:r,session:g,reference_example:o,start_time:s,end_time:c,error:l,query:u,filter:d,trace_filter:f,tree_filter:p,is_root:m,data_source_type:h}).filter(([e,t])=>t!==void 0)),v=JSON.stringify(_);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/runs/stats`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await k(e,`get run stats`),e})).json()}async shareRun(e,{shareId:t}={}){let n={run_id:e,share_token:t||Jr()};qa(e);let r=JSON.stringify(n),i=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`PUT`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await k(t,`share run`),t})).json();if(i===null||!(`share_token`in i))throw Error(`Invalid response from server`);return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){qa(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`unshare run`,!0),t})}async readRunSharedLink(e){qa(e);let t=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`read run shared link`),t})).json();if(!(t===null||!(`share_token`in t)))return`${this.getHostUrl()}/public/${t.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){let n=new URLSearchParams({share_token:e});if(t!==void 0)for(let e of t)n.append(`id`,e);return qa(e),(await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`list shared runs`),t})).json()).map(lc)}async readDatasetSharedSchema(e,t){if(!e&&!t)throw Error(`Either datasetId or datasetName must be given`);e||=(await this.readDataset({datasetName:t})).id,qa(e);let n=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`read dataset shared schema`),t})).json();return n.url=`${this.getHostUrl()}/public/${n.share_token}/d`,n}async shareDataset(e,t){if(!e&&!t)throw Error(`Either datasetId or datasetName must be given`);e||=(await this.readDataset({datasetName:t})).id;let n={dataset_id:e};qa(e);let r=JSON.stringify(n),i=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`PUT`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await k(t,`share dataset`),t})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){qa(e),await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`unshare dataset`,!0),t})}async readSharedDataset(e){return qa(e),await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`read shared dataset`),t})).json()}async listSharedExamples(e,t){let n={};t?.exampleIds&&(n.id=t.exampleIds);let r=new URLSearchParams;Object.entries(n).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r.append(e,t)):r.append(e,t)});let i=await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${r.toString()}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`list shared examples`),t}),a=await i.json();if(!i.ok)throw`detail`in a?Error(`Failed to list shared examples.\nStatus: ${i.status}\nMessage: ${Array.isArray(a.detail)?a.detail.join(`
|
|
14
|
-
`):`Unspecified error`}`):Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:r=!1,projectExtra:i=null,referenceDatasetId:a=null}){let o=r?`?upsert=true`:``,s=`${this.apiUrl}/sessions${o}`,c=i||{};n&&(c.metadata=n);let l={name:e,extra:c,description:t};a!==null&&(l.reference_dataset_id=a);let u=JSON.stringify(l);return await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await k(e,`create project`),e})).json()}async updateProject(e,{name:t=null,description:n=null,metadata:r=null,projectExtra:i=null,endTime:a=null}){let o=`${this.apiUrl}/sessions/${e}`,s=i;r&&(s={...s||{},metadata:r});let c=JSON.stringify({name:t,extra:s,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let e=await this._fetch(o,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(e,`update project`),e})).json()}async hasProject({projectId:e,projectName:t}){let n=`/sessions`,r=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)qa(e),n+=`/${e}`;else if(t!==void 0)r.append(`name`,t);else throw Error(`Must provide projectName or projectId`);let i=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}?${r}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`has project`),e});try{let e=await i.json();return i.ok
|
|
14
|
+
`):`Unspecified error`}`):Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:r=!1,projectExtra:i=null,referenceDatasetId:a=null}){let o=r?`?upsert=true`:``,s=`${this.apiUrl}/sessions${o}`,c=i||{};n&&(c.metadata=n);let l={name:e,extra:c,description:t};a!==null&&(l.reference_dataset_id=a);let u=JSON.stringify(l);return await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await k(e,`create project`),e})).json()}async updateProject(e,{name:t=null,description:n=null,metadata:r=null,projectExtra:i=null,endTime:a=null}){let o=`${this.apiUrl}/sessions/${e}`,s=i;r&&(s={...s||{},metadata:r});let c=JSON.stringify({name:t,extra:s,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let e=await this._fetch(o,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(e,`update project`),e})).json()}async hasProject({projectId:e,projectName:t}){let n=`/sessions`,r=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)qa(e),n+=`/${e}`;else if(t!==void 0)r.append(`name`,t);else throw Error(`Must provide projectName or projectId`);let i=await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}?${r}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`has project`),e});try{let e=await i.json();return i.ok?!Array.isArray(e)||e.length>0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let r=`/sessions`,i=new URLSearchParams;if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);if(e!==void 0)qa(e),r+=`/${e}`;else if(t!==void 0)i.append(`name`,t);else throw Error(`Must provide projectName or projectId`);n!==void 0&&i.append(`include_stats`,n.toString());let a=await this._get(r,i),o;if(Array.isArray(a)){if(a.length===0)throw Error(`Project[id=${e}, name=${t}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw Error(`Must provide either projectName or projectId`);let n=await this.readProject({projectId:e,projectName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw Error(`Must provide either datasetName or datasetId`);let n=await this.readDataset({datasetId:e,datasetName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:`1`});for await(let t of this._getPaginated(`/sessions`,e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw Error(`No projects found to resolve tenant.`)}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:r,referenceDatasetName:i,includeStats:a,datasetVersion:o,referenceFree:s,metadata:c}={}){let l=new URLSearchParams;if(e!==void 0)for(let t of e)l.append(`id`,t);if(t!==void 0&&l.append(`name`,t),n!==void 0&&l.append(`name_contains`,n),r!==void 0)l.append(`reference_dataset`,r);else if(i!==void 0){let e=await this.readDataset({datasetName:i});l.append(`reference_dataset`,e.id)}a!==void 0&&l.append(`include_stats`,a.toString()),o!==void 0&&l.append(`dataset_version`,o),s!==void 0&&l.append(`reference_free`,s.toString()),c!==void 0&&l.append(`metadata`,JSON.stringify(c));for await(let e of this._getPaginated(`/sessions`,l))yield*e}async deleteProject({projectId:e,projectName:t}){let n;if(e===void 0&&t===void 0)throw Error(`Must provide projectName or projectId`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either projectName or projectId, not both`);n=e===void 0?(await this.readProject({projectName:t})).id:e,qa(n),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete session ${n} (${t})`,!0),e})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:r,description:i,dataType:a,name:o}){let s=`${this.apiUrl}/datasets/upload`,c=new FormData,l=new Blob([e],{type:`text/csv`});return c.append(`file`,l,t),n.forEach(e=>{c.append(`input_keys`,e)}),r.forEach(e=>{c.append(`output_keys`,e)}),i&&c.append(`description`,i),a&&c.append(`data_type`,a),o&&c.append(`name`,o),await(await this.caller.call(async()=>{let e=await this._fetch(s,{method:`POST`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(e,`upload CSV`),e})).json()}async createDataset(e,{description:t,dataType:n,inputsSchema:r,outputsSchema:i,metadata:a}={}){let o={name:e,description:t,extra:{source:`sdk`,...a?{metadata:a}:{}}};n&&(o.data_type=n),r&&(o.inputs_schema_definition=r),i&&(o.outputs_schema_definition=i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await k(e,`create dataset`),e})).json()}async readDataset({datasetId:e,datasetName:t}){let n=`/datasets`,r=new URLSearchParams({limit:`1`});if(e&&t)throw Error(`Must provide either datasetName or datasetId, not both`);if(e)qa(e),n+=`/${e}`;else if(t)r.append(`name`,t);else throw Error(`Must provide datasetName or datasetId`);let i=await this._get(n,r),a;if(Array.isArray(i)){if(i.length===0)throw Error(`Dataset[id=${e}, name=${t}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes(`not found`))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:r}){let i=e;if(i===void 0&&t===void 0)throw Error(`Must provide either datasetName or datasetId`);if(i!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);i===void 0&&(i=(await this.readDataset({datasetName:t})).id);let a=new URLSearchParams({from_version:typeof n==`string`?n:n.toISOString(),to_version:typeof r==`string`?r:r.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw Error(`Must provide either datasetName or datasetId`);return(await(await this._getResponse(`/datasets/${e}/openai_ft`)).text()).trim().split(`
|
|
15
15
|
`).map(e=>JSON.parse(e))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:r,datasetNameContains:i,metadata:a}={}){let o=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(n!==void 0)for(let e of n)o.append(`id`,e);r!==void 0&&o.append(`name`,r),i!==void 0&&o.append(`name_contains`,i),a!==void 0&&o.append(`metadata`,JSON.stringify(a));for await(let e of this._getPaginated(`/datasets`,o))yield*e}async updateDataset(e){let{datasetId:t,datasetName:n,...r}=e;if(!t&&!n)throw Error(`Must provide either datasetName or datasetId`);let i=t??(await this.readDataset({datasetName:n})).id;qa(i);let a=JSON.stringify(r);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(e,`update dataset`),e})).json()}async updateDatasetTag(e){let{datasetId:t,datasetName:n,asOf:r,tag:i}=e;if(!t&&!n)throw Error(`Must provide either datasetName or datasetId`);let a=t??(await this.readDataset({datasetName:n})).id;qa(a);let o=JSON.stringify({as_of:typeof r==`string`?r:r.toISOString(),tag:i});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:`PUT`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(e,`update dataset tags`,!0),e})}async deleteDataset({datasetId:e,datasetName:t}){let n=`/datasets`,r=e;if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);if(t!==void 0&&(r=(await this.readDataset({datasetName:t})).id),r!==void 0)qa(r),n+=`/${r}`;else throw Error(`Must provide datasetName or datasetId`);await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+n,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete ${n}`,!0),e})}async createExample(e,t,n){if(xc(e)&&(t!==void 0||n!==void 0))throw Error(`Cannot provide outputs or options when using ExampleCreate object`);let r=t?n?.datasetId:e.dataset_id,i=t?n?.datasetName:e.dataset_name;if(r===void 0&&i===void 0)throw Error(`Must provide either datasetName or datasetId`);if(r!==void 0&&i!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);r===void 0&&(r=(await this.readDataset({datasetName:i})).id);let a=(t?n?.createdAt:e.created_at)||new Date,o;o=xc(e)?e:{inputs:e,outputs:t,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let s=await this._uploadExamplesMultipart(r,[o]);return await this.readExample(s.example_ids?.[0]??Jr())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let t=e,n=t[0].dataset_id,r=t[0].dataset_name;if(n===void 0&&r===void 0)throw Error(`Must provide either datasetName or datasetId`);if(n!==void 0&&r!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);n===void 0&&(n=(await this.readDataset({datasetName:r})).id);let i=await this._uploadExamplesMultipart(n,t);return await Promise.all(i.example_ids.map(e=>this.readExample(e)))}let{inputs:t,outputs:n,metadata:r,splits:i,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:s,attachments:c,exampleIds:l,datasetId:u,datasetName:d}=e;if(t===void 0)throw Error(`Must provide inputs when using legacy parameters`);let f=u,p=d;if(f===void 0&&p===void 0)throw Error(`Must provide either datasetName or datasetId`);if(f!==void 0&&p!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);f===void 0&&(f=(await this.readDataset({datasetName:p})).id);let m=t.map((e,t)=>({dataset_id:f,inputs:e,outputs:n?.[t],metadata:r?.[t],split:i?.[t],id:l?.[t],attachments:c?.[t],source_run_id:a?.[t],use_source_run_io:o?.[t],use_source_run_attachments:s?.[t]})),h=await this._uploadExamplesMultipart(f,m);return await Promise.all(h.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){let r=e.map(e=>fs(e)?ps(e):e),i=fs(t)?ps(t):t;return this.createExample({input:r},{output:i},n)}async readExample(e){qa(e);let t=`/examples/${e}`,{attachment_urls:n,...r}=await this._get(t),i=r;return n&&(i.attachments=Object.entries(n).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type},e),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:r,splits:i,inlineS3Urls:a,metadata:o,limit:s,offset:c,filter:l,includeAttachments:u}={}){let d;if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);if(e!==void 0)d=e;else if(t!==void 0)d=(await this.readDataset({datasetName:t})).id;else throw Error(`Must provide a datasetName or datasetId`);let f=new URLSearchParams({dataset:d}),p=r?typeof r==`string`?r:r?.toISOString():void 0;p&&f.append(`as_of`,p);let m=a??!0;if(f.append(`inline_s3_urls`,m.toString()),n!==void 0)for(let e of n)f.append(`id`,e);if(i!==void 0)for(let e of i)f.append(`splits`,e);if(o!==void 0){let e=JSON.stringify(o);f.append(`metadata`,e)}s!==void 0&&f.append(`limit`,s.toString()),c!==void 0&&f.append(`offset`,c.toString()),l!==void 0&&f.append(`filter`,l),u===!0&&[`attachment_urls`,`outputs`,`metadata`].forEach(e=>f.append(`select`,e));let h=0;for await(let e of this._getPaginated(`/examples`,f)){for(let t of e){let{attachment_urls:e,...n}=t,r=n;e&&(r.attachments=Object.entries(e).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type||void 0},e),{})),yield r,h++}if(s!==void 0&&h>=s)break}}async deleteExample(e){qa(e);let t=`/examples/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete ${t}`,!0),e})}async deleteExamples(e,t){if(e.forEach(e=>qa(e)),t?.hardDelete){let t=this._getPlatformEndpointPath(`datasets/examples/delete`);await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}${t}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(n,`hard delete examples`,!0),n})}else{let t=new URLSearchParams;e.forEach(e=>t.append(`example_ids`,e)),await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/examples?${t.toString()}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete examples`,!0),e})}}async updateExample(e,t){let n;n=t?e:e.id,qa(n);let r;r=t?{id:n,...t}:e;let i;return i=r.dataset_id===void 0?(await this.readExample(n)).dataset_id:r.dataset_id,this._updateExamplesMultipart(i,[r])}async updateExamples(e){let t;return t=e[0].dataset_id===void 0?(await this.readExample(e[0].id)).dataset_id:e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:r}){let i;if(i=e||(await this.readDataset({datasetName:t})).id,qa(i),n&&r||!n&&!r)throw Error(`Exactly one of asOf and tag must be specified.`);let a=new URLSearchParams;return n!==void 0&&a.append(`as_of`,typeof n==`string`?n:n.toISOString()),r!==void 0&&a.append(`tag`,r),await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:`GET`,headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`read dataset version`),e})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let r;if(e===void 0&&t===void 0)throw Error(`Must provide dataset name or ID`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);r=e===void 0?(await this.readDataset({datasetName:t})).id:e,qa(r);let i=new URLSearchParams,a=n?typeof n==`string`?n:n?.toISOString():void 0;return a&&i.append(`as_of`,a),await this._get(`/datasets/${r}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:r,remove:i=!1}){let a;if(e===void 0&&t===void 0)throw Error(`Must provide dataset name or ID`);if(e!==void 0&&t!==void 0)throw Error(`Must provide either datasetName or datasetId, not both`);a=e===void 0?(await this.readDataset({datasetName:t})).id:e,qa(a);let o={split_name:n,examples:r.map(e=>(qa(e),e)),remove:i},s=JSON.stringify(o);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:`PUT`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await k(e,`update dataset splits`,!0),e})}async createFeedback(e,t,{score:n,value:r,correction:i,comment:a,sourceInfo:o,feedbackSourceType:s=`api`,sourceRunId:c,feedbackId:l,feedbackConfig:u,projectId:d,comparativeExperimentId:f,sessionId:p,startTime:m}){if(!e&&!d)throw Error(`One of runId or projectId must be provided`);if(e&&d)throw Error(`Only one of runId or projectId can be provided`);let h={type:s??`api`,metadata:o??{}};c!==void 0&&h?.metadata!==void 0&&!h.metadata.__run&&(h.metadata.__run={run_id:c}),h?.metadata!==void 0&&h.metadata.__run?.run_id!==void 0&&qa(h.metadata.__run.run_id);let g={id:l??ai(),run_id:e,key:t,score:gc(n),value:r,correction:i,comment:a,feedback_source:h,comparative_experiment_id:f,feedbackConfig:u,session_id:p??d,start_time:m},_=JSON.stringify(g),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let e=await this._fetch(v,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await k(e,`create feedback`,!0),e}),g}async updateFeedback(e,{score:t,value:n,correction:r,comment:i}){let a={};t!=null&&(a.score=gc(t)),n!=null&&(a.value=n),r!=null&&(a.correction=r),i!=null&&(a.comment=i),qa(e);let o=JSON.stringify(a);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await k(t,`update feedback`,!0),t})}async readFeedback(e){qa(e);let t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){qa(e);let t=`/feedback/${e}`;await this.caller.call(async()=>{let e=await this._fetch(this.apiUrl+t,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete ${t}`,!0),e})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){let r=new URLSearchParams;if(e)for(let t of e)qa(t),r.append(`run`,t);if(t)for(let e of t)r.append(`key`,e);if(n)for(let e of n)r.append(`source`,e);for await(let e of this._getPaginated(`/feedback`,r))yield*e}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:r}={}){let i={run_id:e,feedback_key:t,feedback_config:r};n?typeof n==`string`?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(e,`create presigned feedback token`),e})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:r,description:i,metadata:a,id:o}){if(t.length===0)throw Error(`At least one experiment is required`);if(n||=(await this.readProject({projectId:t[0]})).reference_dataset_id,!n==null)throw Error(`A reference dataset is required`);let s={id:o,name:e,experiment_ids:t,reference_dataset_id:n,description:i,created_at:(r??new Date)?.toISOString(),extra:{}};a&&(s.extra.metadata=a);let c=JSON.stringify(s);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(e,`create comparative experiment`),e})).json()}async*listPresignedFeedbackTokens(e){qa(e);let t=new URLSearchParams({run_id:e});for await(let e of this._getPaginated(`/feedback/tokens`,t))yield*e}_selectEvalResults(e){let t;return t=`results`in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,n){let r=this._selectEvalResults(e),i=[];for(let e of r){let r=n||{};e.evaluatorInfo&&(r={...e.evaluatorInfo,...r});let a=null;e.targetRunId?a=e.targetRunId:t&&(a=t.id),i.push(await this.createFeedback(a,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:r,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:`model`,sessionId:t?.session_id,startTime:t?.start_time}))}return[r,i]}async logEvaluationFeedback(e,t,n){let[r]=await this._logEvaluationFeedback(e,t,n);return r}async createFeedbackConfig(e){let{feedbackKey:t,feedbackConfig:n,isLowerScoreBetter:r=!1}=e,i={feedback_key:t,feedback_config:n,is_lower_score_better:r};return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await k(e,`create feedback config`),e})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:t,nameContains:n,limit:r}=e,i=new URLSearchParams;t&&t.forEach(e=>{i.append(`key`,e)}),n&&i.append(`name_contains`,n),i.append(`limit`,(r===void 0?100:Math.min(r,100)).toString());let a=0;for await(let e of this._getPaginated(`/feedback-configs`,i))if(yield*e,a+=e.length,r!==void 0&&a>=r)break}async updateFeedbackConfig(e,t={}){let{feedbackConfig:n,isLowerScoreBetter:r}=t,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),r!==void 0&&(i.is_lower_score_better=r),(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await k(e,`update feedback config`),e})).json()}async deleteFeedbackConfig(e){let t=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/feedback-configs?${t}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete feedback config`,!0),e})}async*listAnnotationQueues(e={}){let{queueIds:t,name:n,nameContains:r,limit:i}=e,a=new URLSearchParams;t&&t.forEach((e,t)=>{qa(e,`queueIds[${t}]`),a.append(`ids`,e)}),n&&a.append(`name`,n),r&&a.append(`name_contains`,r),a.append(`limit`,(i===void 0?100:Math.min(i,100)).toString());let o=0;for await(let e of this._getPaginated(`/annotation-queues`,a))if(yield*e,o++,i!==void 0&&o>=i)break}async createAnnotationQueue(e){let{name:t,description:n,queueId:r,rubricInstructions:i,rubricItems:a}=e,o={name:t,description:n,id:r||Jr(),rubric_instructions:i,rubric_items:a},s=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([e,t])=>t!==void 0)));return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await k(e,`create annotation queue`),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${qa(e,`queueId`)}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`read annotation queue`),t})).json()}async updateAnnotationQueue(e,t){let{name:n,description:r,rubricInstructions:i,rubricItems:a}=t,o={};n!==void 0&&(o.name=n),r!==void 0&&(o.description=r),i!==void 0&&(o.rubric_instructions=i),a!==void 0&&(o.rubric_items=a);let s=JSON.stringify(o);await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${qa(e,`queueId`)}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await k(t,`update annotation queue`,!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${qa(e,`queueId`)}`,{method:`DELETE`,headers:{...this._mergedHeaders,Accept:`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`delete annotation queue`,!0),t})}async addRunsToAnnotationQueue(e,t){let n=JSON.stringify(t.map((e,t)=>qa(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${qa(e,`queueId`)}/runs`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await k(t,`add runs to annotation queue`,!0),t})}async getRunFromAnnotationQueue(e,t){let n=`/annotation-queues/${qa(e,`queueId`)}/run`;return lc(await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`get run from annotation queue`),e})).json())}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${qa(e,`queueId`)}/runs/${qa(t,`queueRunId`)}`,{method:`DELETE`,headers:{...this._mergedHeaders,Accept:`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(n,`delete run from annotation queue`,!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/annotation-queues/${qa(e,`queueId`)}/size`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`get size from annotation queue`),t})).json()}async _currentTenantIsOwner(e){let t=await this._getSettings();return e==`-`||t.tenant_handle===e}async _ownerConflictError(e,t){let n=await this._getSettings();return Error(`Cannot ${e} for another tenant.\n
|
|
16
16
|
Current tenant: ${n.tenant_handle}\n
|
|
17
17
|
Requested tenant: ${t}`)}async _getLatestCommitHash(e){let t=await(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(t,`get latest commit hash`),t})).json();if(t.commits.length!==0)return t.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){let[n,r,i]=Ss(e),a=JSON.stringify({like:t});return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/likes/${n}/${r}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(e,`${t?`like`:`unlike`} prompt`),e})).json()}async _getPromptUrl(e){let[t,n,r]=Ss(e);if(await this._currentTenantIsOwner(t)){let e=await this._getSettings();return r===`latest`?`${this.getHostUrl()}/prompts/${n}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${n}/${r.substring(0,8)}?organizationId=${e.id}`}else return r===`latest`?`${this.getHostUrl()}/hub/${t}/${n}`:`${this.getHostUrl()}/hub/${t}/${n}/${r.substring(0,8)}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){let[t,n,r]=Ss(e);for await(let e of this._getPaginated(`/commits/${t}/${n}/`,new URLSearchParams,e=>e.commits))yield*e}async*listPrompts(e){let t=new URLSearchParams;t.append(`sort_field`,e?.sortField??`updated_at`),t.append(`sort_direction`,`desc`),t.append(`is_archived`,(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append(`is_public`,e.isPublic.toString()),e?.query&&t.append(`query`,e.query);for await(let e of this._getPaginated(`/repos`,t,e=>e.repos))yield*e}async getPrompt(e){let[t,n,r]=Ss(e),i=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return e?.status===404?null:(await k(e,`get prompt`),e)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){let n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw Error(`Cannot create a public prompt without first
|
|
@@ -22,8 +22,8 @@ Please upgrade your packages to versions that set`,"message tool calls. e.g., `p
|
|
|
22
22
|
https://smith.langchain.com/prompts`);let[r,i,a]=Ss(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`create a prompt`,r);let o={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},s=JSON.stringify(o),{repo:c}=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await k(e,`create prompt`),e})).json();return c}async createCommit(e,t,n){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[r,i,a]=Ss(e),o=n?.parentCommitHash===`latest`||!n?.parentCommitHash?await this._getLatestCommitHash(`${r}/${i}`):n?.parentCommitHash,s={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o,...n?.description!==void 0&&{description:n.description}},c=JSON.stringify(s),l=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${i}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await k(e,`create commit`),e})).json();return this._getPromptUrl(`${r}/${i}${l.commit_hash?`:${l.commit_hash}`:``}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error(`Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.`);let n=new FormData;for(let e of t){let t=e.id,r=Zs({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=Zs(e.inputs,`Serializing inputs for example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=Zs(e.outputs,`Serializing outputs whle updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}if(e.attachments_operations){let r=Zs(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.attachments_operations`,i)}}let r=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:`PATCH`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await k(e,`update examples`),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error(`Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.`);let n=new FormData;for(let e of t){let t=(e.id??Jr()).toString(),r=Zs({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=Zs(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=Zs(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:`POST`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await k(t,`upload examples`),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[n,r]=Ss(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError(`update a prompt`,n);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),Object.keys(i).length===0)throw Error(`No valid update options provided`);let a=JSON.stringify(i);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await k(e,`update prompt`),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[t,n,r]=Ss(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError(`delete a prompt`,t);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete prompt`),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?`:with_model`:``}`}async _fetchPromptFromApi(e,t){let[n,r,i]=Ss(e),a=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${n}/${r}/${i}${t?.includeModel?`?include_model=true`:``}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`pull prompt commit`),e})).json();return{owner:n,repo:r,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples,hub_model_config:a.model_config,hub_model_provider:a.model_provider}}async pullPromptCommit(e,t){sc(e,t?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){let r=this._getPromptCacheKey(e,t?.includeModel),i=this._promptCache.get(r,n);if(i)return i;let a=await n();return this._promptCache.set(r,a,n),a}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){let n=await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache,dangerouslyPullPublicPrompt:t?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(e=>e!==`object`)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash,description:t?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[t,n]=Ss(e);return this._repoExists(t,n)}async skillExists(e){let[t,n]=Ss(e);return this._repoExists(t,n)}async pullAgent(e,t){return await this._pullDirectory(e,`agent`,t?.version)}async pullSkill(e,t){return await this._pullDirectory(e,`skill`,t?.version)}async pushAgent(e,t){return this._pushDirectory(e,`agent`,t)}async pushSkill(e,t){return this._pushDirectory(e,`skill`,t)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType(`agent`,e)}async*listSkills(e){yield*this._listReposByType(`skill`,e)}async*_listReposByType(e,t){let n=new URLSearchParams;n.append(`repo_type`,e),n.append(`is_archived`,(!!t?.isArchived).toString()),t?.isPublic!==void 0&&n.append(`is_public`,t.isPublic.toString()),t?.query&&n.append(`query`,t.query);for await(let e of this._getPaginated(`/repos`,n,e=>e.repos))yield*e}async _pullDirectory(e,t,n){let[r,i,a]=Ss(e),o=n??(a===`latest`?void 0:a),s=new URL(`${this.apiUrl}/v1/platform/hub/repos/${r}/${i}/directories`);return s.searchParams.set(`repo_type`,t),o&&s.searchParams.set(`commit`,o),await(await this.caller.call(async()=>{let e=await this._fetch(s.toString(),{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`pull directory`),e})).json()}async _pushDirectory(e,t,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw Error(`parent_commit must be 8-64 characters`);let[r,i]=Ss(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`push ${t}`,r);if(await this._repoExists(r,i))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(r,i,n);else{let e=/^[a-z][a-z0-9-_]*$/;if(!e.test(i))throw Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${e}`);await this._createRepo(i,t,n)}let a={files:n.files};n.parentCommit&&(a.parent_commit=n.parentCommit);let o=(await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${r}/${i}/directories/commits`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await k(e,`push ${t}`),e})).json()).commit.commit_hash,s=r;return r===`-`&&(s=(await this._getSettings()).tenant_handle||r),`${this.getHostUrl()}/hub/${s}/${i}:${o.slice(0,8)}`}async _deleteDirectory(e){let[t,n]=Ss(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError(`delete`,t);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/v1/platform/hub/repos/${t}/${n}/directories`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(e,`delete directory`),e})}async _repoExists(e,t){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await k(n,`check repo exists`),n}),!0}catch(e){if(_s(e))return!1;throw e}}async _createRepo(e,t,n){let r={repo_handle:e,repo_type:t,is_public:!!n.isPublic};n.description!==void 0&&(r.description=n.description),n.readme!==void 0&&(r.readme=n.readme),n.tags!==void 0&&(r.tags=n.tags);try{await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)});return await k(e,`create ${t}`),e})}catch(e){if(vs(e))return;throw e}}async _updateRepoMetadata(e,t,n){let r={};n.description!==void 0&&(r.description=n.description),n.readme!==void 0&&(r.readme=n.readme),n.tags!==void 0&&(r.tags=n.tags),n.isPublic!==void 0&&(r.is_public=n.isPublic),Object.keys(r).length!==0&&await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)});return await k(n,`update repo metadata`),n})}async clonePublicDataset(t,n={}){let{sourceApiUrl:r=this.apiUrl,datasetName:i}=n,[a,o]=this.parseTokenOrUrl(t,r),s=new e({apiUrl:a,apiKey:`placeholder`}),c=await s.readSharedDataset(o),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let u=await s.listSharedExamples(o),d=await this.createDataset(l,{description:c.description,dataType:c.data_type||`kv`,inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:d.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,n=2,r=`dataset`){try{return qa(e),[t,e]}catch{}try{let i=new URL(e).pathname.split(`/`).filter(e=>e!==``);if(i.length>=n)return[t,i[i.length-n]];throw Error(`Invalid public ${r} URL: ${e}`)}catch{throw Error(`Invalid public ${r} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Vo()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(` `)}]`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.toString()}};Object.defineProperty(bc,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function xc(e){return`dataset_id`in e||`dataset_name`in e}var Sc=e=>e===void 0?!![`TRACING_V2`,`TRACING`].find(e=>wo(e)===`true`):e,Cc=Symbol.for(`lc:context_variables`),wc=Symbol.for(`langsmith:replica_trace_roots`);function Tc(e,t){if(Cc in e)return e[Cc][t]}function Ec(e,t,n){let r=Cc in e?e[Cc]:{};r[t]=n,e[Cc]=r}var Dc=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`;function Oc(e){return ri(Object.keys(e).sort().map(t=>`${t}:${e[t]??``}`).join(`|`),Dc)}function kc(e){return e.replace(/[-:.]/g,``)}function Ac(e,t=1){let n=t.toFixed(0).slice(0,3).padStart(3,`0`);return`${new Date(e).toISOString().slice(0,-1)}${n}Z`}function jc(e,t,n=1){let r=Ac(e,n);return{dottedOrder:kc(r)+t,microsecondPrecisionDatestring:r}}var Mc=new Set([`projectName`,`updates`,`reroot`]);function Nc(e){let t={};for(let n of Object.keys(e))Mc.has(n)&&(t[n]=e[n]);return t}var Pc=class e{constructor(e,t,n,r){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=n,this.replicas=r}static fromHeader(t){let n=t.split(`,`),r={},i=[],a,o;for(let e of n){let[t,n]=e.split(`=`),s=decodeURIComponent(n);t===`langsmith-metadata`?r=JSON.parse(s):t===`langsmith-tags`?i=s.split(`,`):t===`langsmith-project`?a=s:t===`langsmith-replicas`&&(o=JSON.parse(s).map(e=>Array.isArray(e)?e:Nc(e)))}return new e(r,i,a,o)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(`,`))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(`,`)}},Fc=class e{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ic(t)){Object.assign(this,{...t});return}let n=e.getDefaultConfig(),{metadata:r,...i}=t,a=i.client??e.getSharedClient(),o={...r,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},`id`in i&&i.id==null&&delete i.id,Object.assign(this,{...n,...i,client:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Ac(this.start_time,this.execution_order)),this.id||=Ja(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=Hc(this.replicas),!this.dotted_order){let{dottedOrder:e}=jc(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+`.`+e:this.dotted_order=e}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:`chain`,project_name:qi(),child_runs:[],api_url:Co(`LANGCHAIN_ENDPOINT`)??`http://localhost:1984`,api_key:Co(`LANGCHAIN_API_KEY`),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||=new bc,e.sharedClient}createChild(t){let n=this.child_execution_order+1,r=this.replicas?.map(e=>{let{reroot:t,...n}=e;return n}),i=t.replicas??r,a=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),o=this.extra?.metadata??{},s=a.extra?.metadata??{};Object.keys(o).length>0&&(a.extra={...a.extra,metadata:{...o,...s}}),Cc in this&&(a[Cc]=this[Cc]);let c=Symbol.for(`lc:child_config`),l=t.extra?.[c]??this.extra[c];if(Bc(l)){let e={...l},t=zc(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:a.id}),t.handlers?.find(Lc)?.updateFromRunTree?.(a),e.callbacks=t),a.extra[c]=e}let u=new Set,d=this;for(;d!=null&&!u.has(d.id);)u.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,n),d=d.parent_run;return this.child_runs.push(a),a}async end(e,t,n=Date.now(),r){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(e,t,n=!0){let r=e.extra??{};if(r?.runtime?.library===void 0&&(r.runtime||={},t))for(let[e,n]of Object.entries(t))r.runtime[e]||(r.runtime[e]=n);let i=e.parent_run?.id??e.parent_run_id,a;return a=n?[]:e.child_runs.map(e=>this._convertToCreate(e,t,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:r,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){let n=t.dotted_order.split(`.`),r=null;for(let t=0;t<n.length;t++)if(n[t].slice(-36)===e){r=t;break}if(r!==null){let e=n.slice(r+1);t.dotted_order=e.join(`.`),e.length>0?t.trace_id=e[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let n=Tc(this,wc)??{};n[e]=t,Ec(this,wc,n);for(let n of this.child_runs)n._setReplicaTraceRoot(e,t)}_remapForProject(e){let{projectName:t,runtimeEnv:n,excludeChildRuns:r=!0,reroot:i=!1,distributedParentId:a,apiUrl:o,apiKey:s,workspaceId:c}=e,l=this._convertToCreate(this,n,r);if(t===this.project_name)return{...l,session_name:t};if(i){if(a)this._sliceParentId(a,l);else if(l.parent_run_id=void 0,l.dotted_order){let e=l.dotted_order.split(`.`);e.length>0&&(l.dotted_order=e[e.length-1],l.trace_id=l.id)}let e=Oc({projectName:t,apiUrl:o,apiKey:s,workspaceId:c});this._setReplicaTraceRoot(e,l.id)}let u;if(!i&&(u=(Tc(this,wc)??{})[Oc({projectName:t,apiUrl:o,apiKey:s,workspaceId:c})],u&&(l.trace_id=u,l.dotted_order))){let e=l.dotted_order.split(`.`),t=null;for(let n=0;n<e.length;n++)if(e[n].slice(-36)===u){t=n;break}t!==null&&(l.dotted_order=e.slice(t).join(`.`))}let d=l.id,f=eo(d,t),p;p=l.trace_id?eo(l.trace_id,t):f;let m;l.parent_run_id&&(m=eo(l.parent_run_id,t));let h;return l.dotted_order&&(h=l.dotted_order.split(`.`).map(e=>{let n=eo(e.slice(-36),t);return e.slice(0,-36)+n}).join(`.`)),{...l,id:f,trace_id:p,parent_run_id:m,dotted_order:h,session_name:t}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=bo();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:n,apiUrl:r,workspaceId:i,reroot:a,client:o}of this.replicas){let s=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i});await(o??this.client).createRun(s,{apiKey:n,apiUrl:r,workspaceId:i})}else{let n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){Yi(`Posting with excludeChildRuns=false is deprecated and will be removed in a future version.`);for(let e of this.child_runs)await e.postRun(!1)}this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:n,apiUrl:r,workspaceId:i,updates:a,reroot:o,client:s}of this.replicas){let c=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i}),l={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...a};e?.excludeInputs||(l.inputs=c.inputs),await(s??this.client).updateRun(c.id,l,{apiKey:n,apiUrl:r,workspaceId:i})}else try{let t={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||=[],typeof e==`string`?this.events.push({name:`event`,time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(t,n){let r=t?.callbacks,i,a,o,s=Sc();if(r){let e=r?.getParentRunId?.()??``,t=r?.handlers?.find(e=>e?.name==`langchain_tracer`);i=t?.getRun?.(e),a=t?.projectName,o=t?.client,s||=!!t}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:s,project_name:a,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(n):new e({...n,client:o,tracingEnabled:s,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(t,n){let r=`get`in t&&typeof t.get==`function`?{"langsmith-trace":t.get(`langsmith-trace`),baggage:t.get(`baggage`)}:t,i=r[`langsmith-trace`];if(!i||typeof i!=`string`)return;let a=i.trim(),o=a.split(`.`).map(e=>{let[t,n]=e.split(`Z`);return{strTime:t,time:Date.parse(t+`Z`),uuid:n}}),s=o[0].uuid,c={...n,name:n?.name??`parent`,run_type:n?.run_type??`chain`,start_time:n?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:s,dotted_order:a};if(r.baggage&&typeof r.baggage==`string`){let e=Pc.fromHeader(r.baggage);c.metadata=e.metadata,c.tags=e.tags,c.project_name=e.project_name,c.replicas=e.replicas}let l=new e(c);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new Pc(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,r]of Object.entries(t))e.set(n,r);return t}};Object.defineProperty(Fc,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ic(e){return e!=null&&typeof e.createChild==`function`&&typeof e.postRun==`function`}function Lc(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&e.name===`langchain_tracer`}function Rc(e){return Array.isArray(e)&&e.some(e=>Lc(e))}function zc(e){return typeof e==`object`&&!!e&&Array.isArray(e.handlers)}function Bc(e){let t=e?.callbacks;return e!=null&&typeof t==`object`&&(Rc(t?.handlers)||Rc(t))}function Vc(){let e=Co(`LANGSMITH_RUNS_ENDPOINTS`);if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let e=[];for(let n of t){if(typeof n!=`object`||!n){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!=`string`){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!=`string`){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}e.push({apiUrl:n.api_url.replace(/\/$/,``),apiKey:n.api_key})}return e}else if(typeof t==`object`&&t){Uc(t);let e=[];for(let[n,r]of Object.entries(t)){let t=n.replace(/\/$/,``);if(typeof r==`string`)e.push({apiUrl:t,apiKey:r});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof r}`);continue}}return e}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(e){if(xs(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 Hc(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Vc()}function Uc(e){if(Object.keys(e).length>0&&wo(`ENDPOINT`))throw new bs}var Wc=s({BaseTracer:()=>Yc,isBaseTracer:()=>Jc}),Gc=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function Kc(e,t){if(e)return new Fc({...e,start_time:e._serialized_start_time??e.start_time,parent_run:Kc(t),child_runs:e.child_runs.map(e=>Kc(e)).filter(e=>e!==void 0),extra:{...e.extra,runtime:Nr()},tracingEnabled:!1})}function qc(e,t){return e&&!Array.isArray(e)&&typeof e==`object`?e:{[t]:e}}function Jc(e){return typeof e._addRunToRunMap==`function`}var Yc=class extends zr{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?Gc(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:``):typeof e==`string`?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:n}=jc(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},i=this.getRunById(r.parent_run_id);if(r.parent_run_id===void 0?(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n):i?(this._addChildRun(i,r),i.child_execution_order=Math.max(i.child_execution_order,r.child_execution_order),r.trace_id=i.trace_id,i.dotted_order!==void 0&&(r.dotted_order=[i.dotted_order,t].join(`.`),r._serialized_start_time=n)):r.parent_run_id=void 0,this.usesRunTreeMap){let e=Kc(r,i);e!==void 0&&this.runTreeMap.set(r.id,e)}else this.runMap.set(r.id,r);return r}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:`start`,time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:`llm`,extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleLLMStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:l,serialized:e,events:[{name:`start`,time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:`llm`,extra:u??{},tags:a||[]};return this._addRunToRunMap(d)}async handleChatModelStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw Error(`No LLM run to end.`);return a.end_time=Date.now(),a.outputs=e,a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw Error(`No LLM run to end.`);return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:`error`,time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,r,i,a,o,s,c){let l=this._getExecutionOrder(r),u=Date.now(),d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:u,serialized:e,events:[{name:`start`,time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:o??`chain`,child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.outputs=qc(e,`output`),a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=qc(i.inputs,`input`)),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:`error`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=qc(i.inputs,`input`)),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{input:t},execution_order:s,child_execution_order:s,run_type:`tool`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onToolStart?.(s),s}async handleToolEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`chain`)return;let r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:`agent_action`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`agent_end`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{query:t},execution_order:s,child_execution_order:s,run_type:`retriever`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onRetrieverStart?.(s),s}async handleRetrieverEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`text`,time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,r,i,a){let o=this.getRunById(n);if(!o||o?.run_type!==`llm`)throw Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);return o.events.push({name:`new_token`,time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:a?.chunk}),o}},Xc=s({ConsoleCallbackHandler:()=>rl}),Zc={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 Qc(e,t){return`${e.open}${t}${e.close}`}function $c(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function el(e){return typeof e==`string`?e.trim():e==null?e:$c(e,e.toString())}function tl(e){if(!e.end_time)return``;let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:nl}=Zc,rl=class extends Yc{name=`console_callback_handler`;persistRun(e){return Promise.resolve()}getParents(e){let t=[],n=e;for(;n.parent_run_id;){let e=this.runMap.get(n.parent_run_id);if(e)t.push(e),n=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,n)=>{let r=`${e.execution_order}:${e.run_type}:${e.name}`;return t===n.length-1?Qc(Zc.bold,r):r}).join(` > `);return Qc(nl.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.green,`[chain/start]`)} [${t}] Entering Chain run with input: ${$c(e.inputs,`[inputs]`)}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.cyan,`[chain/end]`)} [${t}] [${tl(e)}] Exiting Chain run with output: ${$c(e.outputs,`[outputs]`)}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.red,`[chain/error]`)} [${t}] [${tl(e)}] Chain run errored with error: ${$c(e.error,`[error]`)}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),n=`prompts`in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${Qc(nl.green,`[llm/start]`)} [${t}] Entering LLM run with input: ${$c(n,`[inputs]`)}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.cyan,`[llm/end]`)} [${t}] [${tl(e)}] Exiting LLM run with output: ${$c(e.outputs,`[response]`)}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.red,`[llm/error]`)} [${t}] [${tl(e)}] LLM run errored with error: ${$c(e.error,`[error]`)}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.green,`[tool/start]`)} [${t}] Entering Tool run with input: "${el(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.cyan,`[tool/end]`)} [${t}] [${tl(e)}] Exiting Tool run with output: "${el(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.red,`[tool/error]`)} [${t}] [${tl(e)}] Tool run errored with error: ${$c(e.error,`[error]`)}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.green,`[retriever/start]`)} [${t}] Entering Retriever run with input: ${$c(e.inputs,`[inputs]`)}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.cyan,`[retriever/end]`)} [${t}] [${tl(e)}] Exiting Retriever run with output: ${$c(e.outputs,`[outputs]`)}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${Qc(nl.red,`[retriever/error]`)} [${t}] [${tl(e)}] Retriever run errored with error: ${$c(e.error,`[error]`)}`)}onAgentAction(e){let t=e,n=this.getBreadcrumbs(e);console.log(`${Qc(nl.blue,`[agent/action]`)} [${n}] Agent selected action: ${$c(t.actions[t.actions.length-1],`[action]`)}`)}},il,al=()=>(il===void 0&&(il=new bc(Pr(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`?{blockOnRootRunFinalization:!0}:{})),il),ol=class{getStore(){}run(e,t){return t()}},sl=Symbol.for(`ls:tracing_async_local_storage`),cl=new ol,ll=new class{getInstance(){return globalThis[sl]??cl}initializeGlobalInstance(e){globalThis[sl]===void 0&&(globalThis[sl]=e)}};function ul(e=!1){let t=ll.getInstance().getStore();if(!e&&t===void 0)throw Error(`Could not get the current run tree.
|
|
23
23
|
|
|
24
24
|
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function dl(e){return typeof e==`function`&&`langsmith:traceable`in e}var fl=s({LangChainTracer:()=>hl,OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:()=>pl}),pl=new Set([`ls_agent_type`]);function ml(e){let t;for(let n of e)for(let e of n)$t.isInstance(e.message)&&e.message.usage_metadata!==void 0&&(t=Qt(t,e.message.usage_metadata));return t}var hl=class e extends Yc{name=`langchain_tracer`;projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;let{exampleId:n,projectName:r,client:i,replicas:a,metadata:o,tags:s}=t;this.projectName=r??qi(),this.replicas=a,this.exampleId=n,this.client=i??al(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=s??[];let c=e.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){gl(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){gl(this,e);let t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await t?.postRun():await t?.patchRun()}onLLMEnd(e){let t=e.outputs;if(t?.generations){let n=ml(t.generations);if(n!==void 0){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=n,e.extra.metadata=t}}}copyWithTracingConfig({metadata:t,tags:n}){let r;if(t===void 0)r=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)r={...t};else{r={...this.tracingMetadata};for(let[e,n]of Object.entries(t))(!Object.prototype.hasOwnProperty.call(r,e)||pl.has(e))&&(r[e]=n)}let i=n?Array.from(new Set([...this.tracingTags,...n])):[...this.tracingTags],a=new e({...this.fields,metadata:r,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();let r=[t];for(;r.length>0;){let e=r.shift();!e||n.has(e.id)||(n.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&r.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new Fc({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return ul(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!=`object`||!e)return!1;let t=e;return`name`in t&&t.name===`langchain_tracer`&&`copyWithTracingConfig`in t&&typeof t.copyWithTracingConfig==`function`&&`getRunTreeWithTracingConfig`in t&&typeof t.getRunTreeWithTracingConfig==`function`}};function gl(e,t){if(e.tracingMetadata){t.extra??={};let n=t.extra.metadata??{},r=!1;for(let[t,i]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,t)||pl.has(t))&&n[t]!==i&&(n[t]=i,r=!0);r&&(t.extra.metadata=n)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}var _l=Symbol.for(`ls:tracing_async_local_storage`),vl=Symbol.for(`lc:context_variables`),yl=e=>{globalThis[_l]=e},bl=()=>globalThis[_l],xl;function Sl(){return new(`default`in cs.default?cs.default.default:cs.default)({autoStart:!0,concurrency:1})}function Cl(){return xl===void 0&&(xl=Sl()),xl}async function wl(e,t){if(t===!0){let t=bl();t===void 0?await e():await t.run(void 0,async()=>e())}else xl=Cl(),xl.add(async()=>{let t=bl();t===void 0?await e():await t.run(void 0,async()=>e())})}async function Tl(){let e=al();await Promise.allSettled([xl===void 0?Promise.resolve():xl.onIdle(),e.awaitPendingTraceBatches()])}var El=s({awaitAllCallbacks:()=>Tl,consumeCallback:()=>wl}),Dl=e=>e===void 0?!![`LANGSMITH_TRACING_V2`,`LANGCHAIN_TRACING_V2`,`LANGSMITH_TRACING`,`LANGCHAIN_TRACING`].find(e=>Pr(e)===`true`):e;function Ol(e){let t=bl();if(t!==void 0)return t.getStore()?.[vl]?.[e]}var kl=Symbol(`lc:configure_hooks`),Al=()=>Ol(kl)||[],jl=s({BaseCallbackManager:()=>Nl,BaseRunManager:()=>Pl,CallbackManager:()=>zl,CallbackManagerForChainRun:()=>Ll,CallbackManagerForLLMRun:()=>Il,CallbackManagerForRetrieverRun:()=>Fl,CallbackManagerForToolRun:()=>Rl,ensureHandler:()=>Bl,parseCallbackConfigArg:()=>Ml});function Ml(e){return e?Array.isArray(e)||`name`in e?{callbacks:e}:e:{}}var Nl=class{setHandler(e){return this.setHandlers([e])}},Pl=class{constructor(e,t,n,r,i,a,o,s){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=o,this._parentRunId=s}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>wl(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,i){await Promise.all(this.handlers.map(n=>wl(async()=>{try{await n.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}},Fl=class extends Pl{getChild(e){let t=new zl(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},Il=class extends Pl{async handleLLMNewToken(e,t,n,r,i,a){await Promise.all(this.handlers.map(n=>wl(async()=>{if(!n.ignoreLLM)try{await n.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMNewToken: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMError(e,t,n,r,i){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,n,r,i){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},Ll=class extends Pl{getChild(e){let t=new zl(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,r,i){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,n,r,i){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},Rl=class extends Pl{getChild(e){let t=new zl(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>wl(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},zl=class e extends Nl{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name=`callback_manager`;_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:Sr();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return Jc(n)&&n._createRunForLLMStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),wl(async()=>{try{await n.handleLLMStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Il(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:Sr();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return Jc(n)&&n._createRunForChatModelStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),wl(async()=>{try{if(n.handleChatModelStart)await n.handleChatModelStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s);else if(n.handleLLMStart){let r=On(t);await n.handleLLMStart?.(e,[r],a,this._parentRunId,i,this.tags,this.metadata,s)}}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new Il(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=Sr(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0,c=void 0){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return Jc(i)&&i._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c),wl(async()=>{try{await i.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new Ll(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=Sr(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreAgent)return Jc(r)&&r._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),wl(async()=>{try{await r.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o,s)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Rl(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=Sr(),r=void 0,i=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreRetriever)return Jc(r)&&r._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),wl(async()=>{try{await r.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Fl(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,r,i){await Promise.all(this.handlers.map(r=>wl(async()=>{if(!r.ignoreCustomEvent)try{await r.handleCustomEvent?.(e,t,n,this.tags,this.metadata)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],n=!0){let r=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)r.handlers.filter(e=>e.name===`console_callback_handler`).some(t=>t.name===e.name)||r.addHandler(e,n);return r}static fromHandlers(e){class t extends zr{name=Sr();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new t),n}static configure(e,t,n,r,i,a,o){return this._configureSync(e,t,n,r,i,a,o)}static _configureSync(t,n,r,i,a,o,s){let c;(t||n)&&(Array.isArray(t)||!t?(c=new e,c.setHandlers(t?.map(Bl)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(Bl):n?.handlers,!1));let l=Pr(`LANGCHAIN_VERBOSE`)===`true`||s?.verbose,u=hl.getTraceableRunTree(),d=u?.tracingEnabled??Dl();if(u?.tracingEnabled===!1&&c){let e=c.handlers.filter(e=>e.name===`langchain_tracer`);for(let t of e)c.removeHandler(t)}let f=d||(Pr(`LANGCHAIN_TRACING`)??!1);if(l||f){if(c||=new e,l&&!c.handlers.some(e=>e.name===rl.prototype.name)){let e=new rl;c.addHandler(e,!0)}if(f&&!c.handlers.some(e=>e.name===`langchain_tracer`)&&d){let e=new hl;c.addHandler(e,!0)}d&&u&&c._parentRunId===void 0&&(c._parentRunId=u.id,c.handlers.find(e=>e.name===`langchain_tracer`)?.updateFromRunTree(u))}for(let{contextVar:t,inheritable:n=!0,handlerClass:r,envVar:i}of Al()){let a=i&&Pr(i)===`true`&&r,o,s=t===void 0?void 0:Ol(t);s&&Br(s)?o=s:a&&(o=new r({})),o!==void 0&&(c||=new e,c.handlers.some(e=>e.name===o.name)||c.addHandler(o,n))}(r||i)&&c&&(c.addTags(r??[]),c.addTags(i??[],!1)),(a||o)&&c&&(c.addMetadata(a??{}),c.addMetadata(o??{},!1));let p=s?.tracerInheritableMetadata,m=s?.tracerInheritableTags;return c&&(p||m)&&(c.handlers=c.handlers.map(e=>e instanceof hl?e.copyWithTracingConfig({metadata:p,tags:m}):e),c.inheritableHandlers=c.inheritableHandlers.map(e=>e instanceof hl?e.copyWithTracingConfig({metadata:p,tags:m}):e)),c}};function Bl(e){return`name`in e?e:zr.fromMethods(e)}var Vl=class{getStore(){}run(e,t){return t()}enterWith(e){}},Hl=new Vl,Ul=Symbol.for(`lc:child_config`),Wl=new class{getInstance(){return bl()??Hl}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Ul]}runWithConfig(e,t,n){let r=zl._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),a=i.getStore(),o=r?.getParentRunId(),s=r?.handlers?.find(e=>e?.name===`langchain_tracer`),c;return s&&o?c=s.getRunTreeWithTracingConfig(o):n||(c=new Fc({name:`<runnable_lambda>`,tracingEnabled:!1})),c&&(c.extra={...c.extra,[Ul]:e}),a!==void 0&&a[vl]!==void 0&&(c===void 0&&(c={}),c[vl]=a[vl]),i.run(c,t)}initializeGlobalInstance(e){bl()===void 0&&yl(e)}},Gl=s({AsyncLocalStorageProviderSingleton:()=>Wl,MockAsyncLocalStorage:()=>Vl,_CONTEXT_VARIABLES_KEY:()=>vl}),Kl=new Set([`api_key`]),ql=new Set([`string`,`number`,`boolean`]);function Jl(e){let t=e.configurable??{},n=e.metadata??{},r={};for(let[e,i]of Object.entries(t))!e.startsWith(`__`)&&!Object.prototype.hasOwnProperty.call(n,e)&&!Kl.has(e)&&ql.has(typeof i)&&(r[e]=i);return Object.keys(r).length>0?r:void 0}async function Yl(e){return zl._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?Jl(e):void 0})}function Xl(...e){let t={};for(let n of e.filter(e=>!!e))for(let e of Object.keys(n))if(e===`metadata`)t[e]={...t[e],...n[e]};else if(e===`tags`){let r=t[e]??[];t[e]=[...new Set(r.concat(n[e]??[]))]}else if(e===`configurable`)t[e]={...t[e],...n[e]};else if(e===`timeout`)t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(e===`signal`)t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&(`any`in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(e===`callbacks`){let e=t.callbacks,r=n.callbacks;if(Array.isArray(r))if(!e)t.callbacks=r;else if(Array.isArray(e))t.callbacks=e.concat(r);else{let n=e.copy();for(let e of r)n.addHandler(Bl(e),!0);t.callbacks=n}else if(r)if(!e)t.callbacks=r;else if(Array.isArray(e)){let n=r.copy();for(let t of e)n.addHandler(Bl(t),!0);t.callbacks=n}else t.callbacks=new zl(r._parentRunId,{handlers:e.handlers.concat(r.handlers),inheritableHandlers:e.inheritableHandlers.concat(r.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(r.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(r.inheritableTags))),metadata:{...e.metadata,...r.metadata}})}else{let r=e;t[r]=n[r]??t[r]}return t}function Zl(e){let t=Wl.getRunnableConfig(),n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:r,...i}=t;n=Object.entries(i).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)}if(e&&(n=Object.entries(e).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)),n?.configurable&&typeof n.configurable.model==`string`&&n.metadata?.model===void 0&&(n.metadata||={},n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw Error(`Timeout must be a positive number`);let e=n.timeout,t=AbortSignal.timeout(e);n.metadata||={},n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=e),n.signal===void 0?n.signal=t:`any`in AbortSignal&&(n.signal=AbortSignal.any([n.signal,t])),delete n.timeout}return n}function Ql(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:i,configurable:a,runId:o}={}){let s=Zl(e);return t!==void 0&&(delete s.runName,s.callbacks=t),r!==void 0&&(s.recursionLimit=r),n!==void 0&&(s.maxConcurrency=n),i!==void 0&&(s.runName=i),a!==void 0&&(s.configurable={...s.configurable,...a}),o!==void 0&&delete s.runId,s}function $l(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function eu(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,r)=>{n=()=>{r(tu(t))},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&r(tu(t))})]).finally(()=>t.removeEventListener(`abort`,n))}function tu(e){return e?.reason instanceof Error?e.reason:typeof e?.reason==`string`?Error(e.reason):Error(`Aborted`)}var nu=s({AsyncGeneratorWithSetup:()=>ou,IterableReadableStream:()=>ru,atee:()=>iu,concat:()=>au,pipeGeneratorWithSetup:()=>su}),ru=class e extends ReadableStream{reader;ensureReader(){this.reader||=this.getReader()}async next(){this.ensureReader();try{let e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let n=t.getReader();return new e({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:n,done:r}=await t.next();r&&e.close(),e.enqueue(n)},async cancel(e){await t.return(e)}})}};function iu(e,t=2){let n=Array.from({length:t},()=>[]);return n.map(async function*(t){for(;;)if(t.length===0){let t=await e.next();for(let e of n)e.push(t)}else if(t[0].done)return;else yield t.shift().value})}function au(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e==`string`&&typeof t==`string`||typeof e==`number`&&typeof t==`number`)return e+t;if(`concat`in e&&typeof e.concat==`function`)return e.concat(t);if(typeof e==`object`&&typeof t==`object`){let n={...e};for(let[e,r]of Object.entries(t))e in n&&!Array.isArray(n[e])?n[e]=au(n[e],r):n[e]=r;return n}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}var ou=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{Wl.runWithConfig($l(e.config),async()=>{this.firstResult=this.signal?eu(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(e=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Wl.runWithConfig($l(this.config),this.signal?async()=>eu(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function su(e,t,n,r,...i){let a=new ou({generator:t,startSetup:n,signal:r}),o=await a.setup;return{output:e(a,o,...i),setup:o}}var cu=Object.prototype.hasOwnProperty;function lu(e,t){return cu.call(e,t)}function uu(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=``+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)lu(e,n)&&t.push(n);return t}function du(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function fu(e){let t=0,n=e.length,r;for(;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function pu(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function mu(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function hu(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(hu(e[t]))return!0}else if(typeof e==`object`){let n=uu(e),r=n.length;for(var t=0;t<r;t++)if(hu(e[n[t]]))return!0}}return!1}function gu(e,t){let n=[e];for(let e in t){let r=typeof t[e]==`object`?JSON.stringify(t[e],null,2):t[e];r!==void 0&&n.push(`${e}: ${r}`)}return n.join(`
|
|
25
|
-
`)}var _u=class extends Error{constructor(e,t,n,r,i){super(gu(e,{name:t,index:n,operation:r,tree:i})),this.name=t,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=gu(e,{name:t,index:n,operation:r,tree:i})}},vu=s({JsonPatchError:()=>yu,_areEquals:()=>ku,applyOperation:()=>wu,applyPatch:()=>Tu,applyReducer:()=>Eu,deepClone:()=>bu,getValueByPointer:()=>Cu,validate:()=>Ou,validator:()=>Du}),yu=_u,bu=du,xu={add:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=Cu(n,this.path);r&&=du(r);let i=wu(n,{op:`remove`,path:this.from}).removed;return wu(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=Cu(n,this.from);return wu(n,{op:`add`,path:this.path,value:du(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:ku(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Su={add:function(e,t,n){return fu(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:xu.move,copy:xu.copy,test:xu.test,_get:xu._get};function Cu(e,t){if(t==``)return e;var n={op:`_get`,path:t};return wu(e,n),n.value}function wu(e,t,n=!1,r=!0,i=!0,a=0){if(n&&(typeof n==`function`?n(t,0,e,t.path):Du(t,0)),t.path===``){let r={newDocument:e};if(t.op===`add`)return r.newDocument=t.value,r;if(t.op===`replace`)return r.newDocument=t.value,r.removed=e,r;if(t.op===`move`||t.op===`copy`)return r.newDocument=Cu(e,t.from),t.op===`move`&&(r.removed=e),r;if(t.op===`test`){if(r.test=ku(e,t.value),r.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r.newDocument=e,r}else if(t.op===`remove`)return r.removed=e,r.newDocument=null,r;else if(t.op===`_get`)return t.value=e,r;else if(n)throw new yu("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return r}else{r||(e=du(e));let o=(t.path||``).split(`/`),s=e,c=1,l=o.length,u,d,f;for(f=typeof n==`function`?n:Du;;){if(d=o[c],d&&d.indexOf(`~`)!=-1&&(d=mu(d)),i&&(d==`__proto__`||d==`prototype`&&c>0&&o[c-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(s[d]===void 0?u=o.slice(0,c).join(`/`):c==l-1&&(u=t.path),u!==void 0&&f(t,0,e,u)),c++,Array.isArray(s)){if(d===`-`)d=s.length;else if(n&&!fu(d))throw new yu(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else fu(d)&&(d=~~d);if(c>=l){if(n&&t.op===`add`&&d>s.length)throw new yu(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);let r=Su[t.op].call(t,s,d,e);if(r.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r}}else if(c>=l){let n=xu[t.op].call(t,s,d,e);if(n.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return n}if(s=s[d],n&&c<l&&(!s||typeof s!=`object`))throw new yu(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function Tu(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new yu(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=du(e));let a=Array(t.length);for(let r=0,o=t.length;r<o;r++)a[r]=wu(e,t[r],n,!0,i,r),e=a[r].newDocument;return a.newDocument=e,a}function Eu(e,t,n){let r=wu(e,t);if(r.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function Du(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new yu(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!xu[e.op])throw new yu("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new yu("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new yu('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new yu("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new yu("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&hu(e.value))throw new yu("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new yu("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new yu(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=Ou([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new yu(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function Ou(e,t,n){try{if(!Array.isArray(e))throw new yu(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Tu(du(t),du(e),n||!0);else{n||=Du;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof yu)return e;throw e}}function ku(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!ku(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!ku(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function Au(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=uu(t),o=uu(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(lu(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Au(u,d,n,r+`/`+pu(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+pu(l),value:du(u)}),n.push({op:`replace`,path:r+`/`+pu(l),value:du(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+pu(l),value:du(u)}),n.push({op:`remove`,path:r+`/`+pu(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!lu(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+pu(l),value:du(t[l])})}}}function ju(e,t,n=!1){var r=[];return Au(e,t,r,``,n),r}({...vu});var Mu=s({LogStreamCallbackHandler:()=>zu,RunLog:()=>Pu,RunLogPatch:()=>Nu,isLogStreamHandler:()=>Fu}),Nu=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=Tu({},t);return new Pu({ops:t,state:n[n.length-1].newDocument})}},Pu=class e extends Nu{state;constructor(e){super(e),this.state=e.state}concat(t){let n=this.ops.concat(t.ops),r=Tu(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=Tu({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}},Fu=e=>e.name===`log_stream_tracer`;async function Iu(e,t){if(t===`original`)throw Error(`Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.`);let{inputs:n}=e;if([`retriever`,`llm`,`prompt`].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===``))return n.input}async function Lu(e,t){let{outputs:n}=e;return t===`original`||[`retriever`,`llm`,`prompt`].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function Ru(e){return e!==void 0&&e.message!==void 0}var zu=class extends Yc{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat=`original`;rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name=`log_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ru.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new Nu({ops:[{op:`add`,path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Nu({ops:[{op:`replace`,path:``,value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat===`streaming_events`&&(n.inputs=await Iu(e,this._schemaFormat)),await this.writer.write(new Nu({ops:[{op:`add`,path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat===`streaming_events`&&n.push({op:`replace`,path:`/logs/${t}/inputs`,value:await Iu(e,this._schemaFormat)}),n.push({op:`add`,path:`/logs/${t}/final_output`,value:await Lu(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:`add`,path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new Nu({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new Nu({ops:[{op:`replace`,path:`/final_output`,value:await Lu(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let i=e.inputs.messages!==void 0,a;a=i?Ru(n?.chunk)?n?.chunk:new nn({id:`run-${e.id}`,content:t}):t;let o=new Nu({ops:[{op:`add`,path:`/logs/${r}/streamed_output_str/-`,value:t},{op:`add`,path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(o)}},Bu=s({ChatGenerationChunk:()=>Uu,GenerationChunk:()=>Hu,RUN_KEY:()=>Vu}),Vu=`__run`,Hu=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Uu=class e extends Hu{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Wu({name:e,serialized:t}){return e===void 0?t?.name===void 0?t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:`Unnamed`:t.name:e}var Gu=e=>e.name===`event_stream_tracer`,Ku=class extends Yc{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name=`event_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ru.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function i(e,t){return e===`llm`&&typeof t==`string`?new Hu({text:t}):t}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(e=>{o=e}),this.tappedPromises.set(e,a);try{let a={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...a,data:{chunk:i(r.runType,n.value)}},r),yield n.value;for await(let e of t)r.runType!==`tool`&&r.runType!==`retriever`&&await this.send({...a,data:{chunk:i(r.runType,e)}},r),yield e}finally{o?.()}}else{yield n.value;for await(let e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n===void 0?await this.send(e,t):n.then(()=>{this.send(e,t)})}async onLLMStart(e){let t=Wu(e),n=e.inputs.messages===void 0?`llm`:`chat_model`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);let i=`on_${n}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){let r=this.runInfoMap.get(e.id),i,a;if(r===void 0)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType===`chat_model`)a=`on_chat_model_stream`,i=n?.chunk===void 0?new nn({content:t,id:`run-${e.id}`}):n.chunk.message;else if(r.runType===`llm`)a=`on_llm_stream`,i=n?.chunk===void 0?new Hu({text:t}):n.chunk;else throw Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let r=e.outputs?.generations,i;if(t.runType===`chat_model`){for(let e of r??[]){if(i!==void 0)break;i=e[0]?.message}n=`on_chat_model_end`}else if(t.runType===`llm`)i={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n=`on_llm_end`;else throw Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Wu(e),n=e.run_type??`chain`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===``&&Object.keys(e.inputs).length===1?(i={},r.inputs={}):e.inputs.input===void 0?(i.input=e.inputs,r.inputs=e.inputs):(i.input=e.inputs.input,r.inputs=e.inputs.input),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(i.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Wu(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`tool`,inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:`on_tool_start`,data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:`on_tool_end`,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:`on_tool_error`,data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=Wu(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`retriever`,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:`on_retriever_start`,data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:`on_retriever_end`,data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){let r=this.runInfoMap.get(n);if(r===void 0)throw Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:`on_custom_event`,run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},qu=Object.prototype.toString,Ju=e=>qu.call(e)===`[object Error]`,Yu=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 Xu(e){if(!(e&&Ju(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:Yu.has(t)}function Zu(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Qu(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var $u=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function ed(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function td(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function nd({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof $u)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),td(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=td(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!Xu(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=ed(n,i),f=typeof a.retryAfterMs==`number`&&a.retryAfterMs>=0?a.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));let p=Math.min(d,u);return p>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},p);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function rd(e,t={}){if(t={...t},Zu(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Qu(`factor`,t.factor,{min:0,allowInfinity:!1}),Qu(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Qu(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Qu(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await nd({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var id=s({AsyncCaller:()=>bd,classifyRateLimitError:()=>vd,parseRetryAfterMs:()=>_d}),ad=[400,401,402,403,404,405,406,407,409],od=6e4,sd=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],cd=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function ld(e){return typeof e==`object`&&e&&`response`in e&&typeof e.response==`object`&&e.response!==null&&`status`in e.response&&typeof e.response.status==`number`?e.response.status:void 0}function ud(e){if(!(typeof e!=`object`||!e)){if(`status`in e&&typeof e.status==`number`)return e.status;if(`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}}function dd(e){return typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:void 0}function fd(e){if(!(typeof e!=`object`||!e))return`code`in e&&typeof e.code==`string`?e.code:`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&typeof e.error.code==`string`?e.error.code:void 0}function pd(e){if(e?.headers)return typeof e.headers.get==`function`?e.headers.get(`retry-after`):e.headers[`retry-after`]??e.headers[`Retry-After`];if(e?.response?.headers)return typeof e.response.headers.get==`function`?e.response.headers.get(`retry-after`):e.response.headers[`retry-after`]??e.response.headers[`Retry-After`]}function md(e){if(e==null)return;let t=cd.exec(e);if(!t)return;let n=Number(t[1]),r=t[2]?.toLowerCase();if(!(Number.isNaN(n)||!r))return r===`ms`||r.startsWith(`millisecond`)?n:r===`m`||r.startsWith(`min`)?n*6e4:r===`h`||r.startsWith(`hr`)||r.startsWith(`hour`)?n*36e5:n*1e3}function hd(e,t){if(e instanceof Error)return e;let n=Error(t);return typeof e==`object`&&e&&Object.assign(n,e),n}function gd(e,t){if(typeof e!=`object`||!e)return;let n=e;n.rateLimitType=t.action,n.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(n.retryAfterMs=t.retryAfterMs)}function _d(e){if(e==null)return;let t=e.trim();if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return n*1e3;let r=Date.parse(t);if(!Number.isNaN(r)){let e=r-Date.now();return e>0?e:0}}function vd(e){if((ld(e)??ud(e))!==429)return;if(fd(e)===`insufficient_quota`)return{action:`stop`,reason:`insufficient_quota`};let t=dd(e);if(t&&sd.some(e=>e.test(t)))return{action:`stop`,reason:`quota_message`};let n=_d(pd(e))??md(t);return n===void 0?{action:`capacity`,reason:`headerless_429`}:n<=od?{action:`wait`,retryAfterMs:n,reason:`retry_after_hint`}:{action:`capacity`,retryAfterMs:n,reason:`retry_after_too_large`}}var yd=e=>{if(typeof e!=`object`||!e)return;if(`message`in e&&typeof e.message==`string`&&(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`))||`name`in e&&typeof e.name==`string`&&e.name===`AbortError`||`code`in e&&typeof e.code==`string`&&e.code===`ECONNABORTED`)throw e;let t=ld(e)??ud(e);if(t&&ad.includes(+t))throw e;if(fd(e)===`insufficient_quota`){let t=hd(e,dd(e)??`Insufficient quota`);throw t.name=`InsufficientQuotaError`,gd(t,{action:`stop`,reason:`insufficient_quota`}),t}let n=vd(e);if(n){if(n.action===`wait`){gd(e,n);return}let t=hd(e,dd(e)??`Rate limit exceeded`);throw t.name===`Error`&&(t.name=n.action===`stop`?`RateLimitQuotaExhaustedError`:`RateLimitCapacityError`),gd(t,n),t}},bd=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??yd;let t=`default`in cs.default?cs.default.default:cs.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>rd(()=>e(...t).catch(e=>{throw e instanceof Error?e:Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((t,n)=>{r=()=>{n(tu(e.signal))},e.signal?.addEventListener(`abort`,r,{once:!0})})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener(`abort`,r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},xd=class extends Yc{name=`RootListenersTracer`;rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Sd(e){return e?e.lc_runnable:!1}var Cd=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(t)),this.includeTags!==void 0&&(n||=r.some(e=>this.includeTags?.includes(e))),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n&&=r.every(e=>!this.excludeTags?.includes(e))),n}},wd=e=>btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``),Td;function A(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Ed=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Dd=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Td=globalThis).__zod_globalConfig??(Td.__zod_globalConfig={});var Od=globalThis.__zod_globalConfig;function kd(e){return e&&Object.assign(Od,e),Od}function Ad(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function jd(e,t){return typeof t==`bigint`?t.toString():t}function Md(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function Nd(e){return e==null}function Pd(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Fd(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var Id=Symbol(`evaluating`);function Ld(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Id)return r===void 0&&(r=Id,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rd(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function zd(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function Bd(e){return JSON.stringify(e)}function Vd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Hd=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ud(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wd=Md(()=>{if(Od.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Gd(e){if(Ud(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Ud(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Kd(e){return Gd(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var qd=new Set([`string`,`number`,`symbol`]);function Jd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Yd(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Xd(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Zd={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Qd(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Yd(e,zd(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Rd(this,`shape`,e),e},checks:[]}))}function $d(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Yd(e,zd(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Rd(this,`shape`,r),r},checks:[]}))}function ef(e,t){if(!Gd(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Yd(e,zd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rd(this,`shape`,n),n}}))}function tf(e,t){if(!Gd(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Yd(e,zd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rd(this,`shape`,n),n}}))}function nf(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Yd(e,zd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Rd(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function rf(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Yd(t,zd(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Rd(this,`shape`,i),i},checks:[]}))}function af(e,t,n){return Yd(t,zd(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Rd(this,`shape`,i),i}}))}function of(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function sf(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function cf(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function lf(e){return typeof e==`string`?e:e?.message}function uf(e,t,n){let r=e.message?e.message:lf(e.inst?._zod.def?.error?.(e))??lf(t?.error?.(e))??lf(n.customError?.(e))??lf(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function df(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ff(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var pf=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jd,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},mf=A(`$ZodError`,pf),hf=A(`$ZodError`,pf,{Parent:Error});function gf(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function _f(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...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{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}function vf(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function yf(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${vf(e.path)}`);return t.join(`
|
|
26
|
-
`)}var bf=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Ed;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>uf(e,a,kd())));throw Hd(t,i?.callee),t}return o.value},xf=bf(hf),Sf=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>uf(e,a,kd())));throw Hd(t,i?.callee),t}return o.value},Cf=Sf(hf),wf=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ed;return a.issues.length?{success:!1,error:new(e??mf)(a.issues.map(e=>uf(e,i,kd())))}:{success:!0,data:a.value}},Tf=wf(hf),Ef=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>uf(e,i,kd())))}:{success:!0,data:a.value}},Df=Ef(hf),Of=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return bf(e)(t,n,i)},kf=e=>(t,n,r)=>bf(e)(t,n,r),Af=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Sf(e)(t,n,i)},jf=e=>async(t,n,r)=>Sf(e)(t,n,r),Mf=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return wf(e)(t,n,i)},Nf=e=>(t,n,r)=>wf(e)(t,n,r),Pf=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ef(e)(t,n,i)},Ff=e=>async(t,n,r)=>Ef(e)(t,n,r),If=/^[cC][0-9a-z]{6,}$/,Lf=/^[0-9a-z]+$/,Rf=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zf=/^[0-9a-vA-V]{20}$/,Bf=/^[A-Za-z0-9]{27}$/,Vf=/^[a-zA-Z0-9_-]{21}$/,Hf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Uf=/^([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})$/,Wf=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Gf=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Kf=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function qf(){return new RegExp(Kf,`u`)}var Jf=/^(?:(?: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=/^(([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}|:))$/,Xf=/^((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])$/,Zf=/^(([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])$/,Qf=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$f=/^[A-Za-z0-9_-]*$/,ep=/^https?$/,tp=/^\+[1-9]\d{6,14}$/,np=`(?:(?:\\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])))`,rp=RegExp(`^${np}$`);function ip(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ap(e){return RegExp(`^${ip(e)}$`)}function op(e){let t=ip({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${np}T(?:${r})$`)}var sp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},cp=/^-?\d+$/,lp=/^-?\d+(?:\.\d+)?$/,up=/^(?:true|false)$/i,dp=/^[^A-Z]*$/,fp=/^[^a-z]*$/,pp=A(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),mp={number:`number`,bigint:`bigint`,object:`date`},hp=A(`$ZodCheckLessThan`,(e,t)=>{pp.init(e,t);let n=mp[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),gp=A(`$ZodCheckGreaterThan`,(e,t)=>{pp.init(e,t);let n=mp[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_p=A(`$ZodCheckMultipleOf`,(e,t)=>{pp.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Fd(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),vp=A(`$ZodCheckNumberFormat`,(e,t)=>{pp.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Zd[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=cp)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),yp=A(`$ZodCheckMaxLength`,(e,t)=>{var n;pp.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=df(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),bp=A(`$ZodCheckMinLength`,(e,t)=>{var n;pp.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=df(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),xp=A(`$ZodCheckLengthEquals`,(e,t)=>{var n;pp.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=df(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Sp=A(`$ZodCheckStringFormat`,(e,t)=>{var n,r;pp.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Cp=A(`$ZodCheckRegex`,(e,t)=>{Sp.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),wp=A(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=dp,Sp.init(e,t)}),Tp=A(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=fp,Sp.init(e,t)}),Ep=A(`$ZodCheckIncludes`,(e,t)=>{pp.init(e,t);let n=Jd(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Dp=A(`$ZodCheckStartsWith`,(e,t)=>{pp.init(e,t);let n=RegExp(`^${Jd(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Op=A(`$ZodCheckEndsWith`,(e,t)=>{pp.init(e,t);let n=RegExp(`.*${Jd(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),kp=A(`$ZodCheckOverwrite`,(e,t)=>{pp.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Ap=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
25
|
+
`)}var _u=class extends Error{constructor(e,t,n,r,i){super(gu(e,{name:t,index:n,operation:r,tree:i})),this.name=t,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=gu(e,{name:t,index:n,operation:r,tree:i})}},vu=s({JsonPatchError:()=>yu,_areEquals:()=>ku,applyOperation:()=>wu,applyPatch:()=>Tu,applyReducer:()=>Eu,deepClone:()=>bu,getValueByPointer:()=>Cu,validate:()=>Ou,validator:()=>Du}),yu=_u,bu=du,xu={add:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=Cu(n,this.path);r&&=du(r);let i=wu(n,{op:`remove`,path:this.from}).removed;return wu(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=Cu(n,this.from);return wu(n,{op:`add`,path:this.path,value:du(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:ku(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Su={add:function(e,t,n){return fu(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:xu.move,copy:xu.copy,test:xu.test,_get:xu._get};function Cu(e,t){if(t==``)return e;var n={op:`_get`,path:t};return wu(e,n),n.value}function wu(e,t,n=!1,r=!0,i=!0,a=0){if(n&&(typeof n==`function`?n(t,0,e,t.path):Du(t,0)),t.path===``){let r={newDocument:e};if(t.op===`add`)return r.newDocument=t.value,r;if(t.op===`replace`)return r.newDocument=t.value,r.removed=e,r;if(t.op===`move`||t.op===`copy`)return r.newDocument=Cu(e,t.from),t.op===`move`&&(r.removed=e),r;if(t.op===`test`){if(r.test=ku(e,t.value),r.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r.newDocument=e,r}else if(t.op===`remove`)return r.removed=e,r.newDocument=null,r;else if(t.op===`_get`)return t.value=e,r;else if(n)throw new yu("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return r}else{r||(e=du(e));let o=(t.path||``).split(`/`),s=e,c=1,l=o.length,u,d,f;for(f=typeof n==`function`?n:Du;;){if(d=o[c],d&&d.indexOf(`~`)!=-1&&(d=mu(d)),i&&(d==`__proto__`||d==`prototype`&&c>0&&o[c-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(s[d]===void 0?u=o.slice(0,c).join(`/`):c==l-1&&(u=t.path),u!==void 0&&f(t,0,e,u)),c++,Array.isArray(s)){if(d===`-`)d=s.length;else if(n&&!fu(d))throw new yu(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else fu(d)&&(d=~~d);if(c>=l){if(n&&t.op===`add`&&d>s.length)throw new yu(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);let r=Su[t.op].call(t,s,d,e);if(r.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r}}else if(c>=l){let n=xu[t.op].call(t,s,d,e);if(n.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return n}if(s=s[d],n&&c<l&&(!s||typeof s!=`object`))throw new yu(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function Tu(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new yu(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=du(e));let a=Array(t.length);for(let r=0,o=t.length;r<o;r++)a[r]=wu(e,t[r],n,!0,i,r),e=a[r].newDocument;return a.newDocument=e,a}function Eu(e,t,n){let r=wu(e,t);if(r.test===!1)throw new yu(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function Du(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new yu(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!xu[e.op])throw new yu("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new yu("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new yu('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new yu("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new yu("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&hu(e.value))throw new yu("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new yu("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new yu(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=Ou([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new yu(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function Ou(e,t,n){try{if(!Array.isArray(e))throw new yu(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Tu(du(t),du(e),n||!0);else{n||=Du;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof yu)return e;throw e}}function ku(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!ku(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!ku(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function Au(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=uu(t),o=uu(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(lu(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Au(u,d,n,r+`/`+pu(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+pu(l),value:du(u)}),n.push({op:`replace`,path:r+`/`+pu(l),value:du(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+pu(l),value:du(u)}),n.push({op:`remove`,path:r+`/`+pu(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!lu(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+pu(l),value:du(t[l])})}}}function ju(e,t,n=!1){var r=[];return Au(e,t,r,``,n),r}({...vu});var Mu=s({LogStreamCallbackHandler:()=>zu,RunLog:()=>Pu,RunLogPatch:()=>Nu,isLogStreamHandler:()=>Fu}),Nu=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=Tu({},t);return new Pu({ops:t,state:n[n.length-1].newDocument})}},Pu=class e extends Nu{state;constructor(e){super(e),this.state=e.state}concat(t){let n=this.ops.concat(t.ops),r=Tu(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=Tu({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}},Fu=e=>e.name===`log_stream_tracer`;async function Iu(e,t){if(t===`original`)throw Error(`Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.`);let{inputs:n}=e;if([`retriever`,`llm`,`prompt`].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===``))return n.input}async function Lu(e,t){let{outputs:n}=e;return t===`original`||[`retriever`,`llm`,`prompt`].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function Ru(e){return e!==void 0&&e.message!==void 0}var zu=class extends Yc{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat=`original`;rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name=`log_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ru.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new Nu({ops:[{op:`add`,path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Nu({ops:[{op:`replace`,path:``,value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat===`streaming_events`&&(n.inputs=await Iu(e,this._schemaFormat)),await this.writer.write(new Nu({ops:[{op:`add`,path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat===`streaming_events`&&n.push({op:`replace`,path:`/logs/${t}/inputs`,value:await Iu(e,this._schemaFormat)}),n.push({op:`add`,path:`/logs/${t}/final_output`,value:await Lu(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:`add`,path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new Nu({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new Nu({ops:[{op:`replace`,path:`/final_output`,value:await Lu(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let i=e.inputs.messages!==void 0,a;a=i?Ru(n?.chunk)?n?.chunk:new nn({id:`run-${e.id}`,content:t}):t;let o=new Nu({ops:[{op:`add`,path:`/logs/${r}/streamed_output_str/-`,value:t},{op:`add`,path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(o)}},Bu=s({ChatGenerationChunk:()=>Uu,GenerationChunk:()=>Hu,RUN_KEY:()=>Vu}),Vu=`__run`,Hu=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},Uu=class e extends Hu{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Wu({name:e,serialized:t}){return e===void 0?t?.name===void 0?t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:`Unnamed`:t.name:e}var Gu=e=>e.name===`event_stream_tracer`,Ku=class extends Yc{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name=`event_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ru.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function i(e,t){return e===`llm`&&typeof t==`string`?new Hu({text:t}):t}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(e=>{o=e}),this.tappedPromises.set(e,a);try{let a={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...a,data:{chunk:i(r.runType,n.value)}},r),yield n.value;for await(let e of t)r.runType!==`tool`&&r.runType!==`retriever`&&await this.send({...a,data:{chunk:i(r.runType,e)}},r),yield e}finally{o?.()}}else{yield n.value;for await(let e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n===void 0?await this.send(e,t):n.then(()=>{this.send(e,t)})}async onLLMStart(e){let t=Wu(e),n=e.inputs.messages===void 0?`llm`:`chat_model`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);let i=`on_${n}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){let r=this.runInfoMap.get(e.id),i,a;if(r===void 0)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType===`chat_model`)a=`on_chat_model_stream`,i=n?.chunk===void 0?new nn({content:t,id:`run-${e.id}`}):n.chunk.message;else if(r.runType===`llm`)a=`on_llm_stream`,i=n?.chunk===void 0?new Hu({text:t}):n.chunk;else throw Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let r=e.outputs?.generations,i;if(t.runType===`chat_model`){for(let e of r??[]){if(i!==void 0)break;i=e[0]?.message}n=`on_chat_model_end`}else if(t.runType===`llm`)i={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n=`on_llm_end`;else throw Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Wu(e),n=e.run_type??`chain`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===``&&Object.keys(e.inputs).length===1?(i={},r.inputs={}):e.inputs.input===void 0?(i.input=e.inputs,r.inputs=e.inputs):(i.input=e.inputs.input,r.inputs=e.inputs.input),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(i.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Wu(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`tool`,inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:`on_tool_start`,data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:`on_tool_end`,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:`on_tool_error`,data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=Wu(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`retriever`,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:`on_retriever_start`,data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:`on_retriever_end`,data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){let r=this.runInfoMap.get(n);if(r===void 0)throw Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:`on_custom_event`,run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},qu=Object.prototype.toString,Ju=e=>qu.call(e)===`[object Error]`,Yu=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 Xu(e){if(!(e&&Ju(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:Yu.has(t)}function Zu(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Qu(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var $u=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function ed(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function td(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function nd({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof $u)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),td(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=td(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!Xu(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=ed(n,i),f=typeof a.retryAfterMs==`number`&&a.retryAfterMs>=0?a.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));let p=Math.min(d,u);return p>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},p);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function rd(e,t={}){if(t={...t},Zu(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Qu(`factor`,t.factor,{min:0,allowInfinity:!1}),Qu(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Qu(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Qu(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await nd({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var id=s({AsyncCaller:()=>bd,classifyRateLimitError:()=>vd,parseRetryAfterMs:()=>_d}),ad=[400,401,402,403,404,405,406,407,409],od=6e4,sd=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],cd=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function ld(e){return typeof e==`object`&&e&&`response`in e&&typeof e.response==`object`&&e.response!==null&&`status`in e.response&&typeof e.response.status==`number`?e.response.status:void 0}function ud(e){if(!(typeof e!=`object`||!e)){if(`status`in e&&typeof e.status==`number`)return e.status;if(`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}}function dd(e){return typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:void 0}function fd(e){if(!(typeof e!=`object`||!e))return`code`in e&&typeof e.code==`string`?e.code:`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&typeof e.error.code==`string`?e.error.code:void 0}function pd(e){if(e?.headers)return typeof e.headers.get==`function`?e.headers.get(`retry-after`):e.headers[`retry-after`]??e.headers[`Retry-After`];if(e?.response?.headers)return typeof e.response.headers.get==`function`?e.response.headers.get(`retry-after`):e.response.headers[`retry-after`]??e.response.headers[`Retry-After`]}function md(e){if(e==null)return;let t=cd.exec(e);if(!t)return;let n=Number(t[1]),r=t[2]?.toLowerCase();if(!(Number.isNaN(n)||!r))return r===`ms`||r.startsWith(`millisecond`)?n:r===`m`||r.startsWith(`min`)?n*6e4:r===`h`||r.startsWith(`hr`)||r.startsWith(`hour`)?n*36e5:n*1e3}function hd(e,t){if(e instanceof Error)return e;let n=Error(t);return typeof e==`object`&&e&&Object.assign(n,e),n}function gd(e,t){if(typeof e!=`object`||!e)return;let n=e;n.rateLimitType=t.action,n.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(n.retryAfterMs=t.retryAfterMs)}function _d(e){if(e==null)return;let t=e.trim();if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return n*1e3;let r=Date.parse(t);if(!Number.isNaN(r)){let e=r-Date.now();return e>0?e:0}}function vd(e){if((ld(e)??ud(e))!==429)return;if(fd(e)===`insufficient_quota`)return{action:`stop`,reason:`insufficient_quota`};let t=dd(e);if(t&&sd.some(e=>e.test(t)))return{action:`stop`,reason:`quota_message`};let n=_d(pd(e))??md(t);return n===void 0?{action:`capacity`,reason:`headerless_429`}:n<=od?{action:`wait`,retryAfterMs:n,reason:`retry_after_hint`}:{action:`capacity`,retryAfterMs:n,reason:`retry_after_too_large`}}var yd=e=>{if(typeof e!=`object`||!e)return;if(`message`in e&&typeof e.message==`string`&&(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`))||`name`in e&&typeof e.name==`string`&&e.name===`AbortError`||`code`in e&&typeof e.code==`string`&&e.code===`ECONNABORTED`)throw e;let t=ld(e)??ud(e);if(t&&ad.includes(+t))throw e;if(fd(e)===`insufficient_quota`){let t=hd(e,dd(e)??`Insufficient quota`);throw t.name=`InsufficientQuotaError`,gd(t,{action:`stop`,reason:`insufficient_quota`}),t}let n=vd(e);if(n){if(n.action===`wait`){gd(e,n);return}let t=hd(e,dd(e)??`Rate limit exceeded`);throw t.name===`Error`&&(t.name=n.action===`stop`?`RateLimitQuotaExhaustedError`:`RateLimitCapacityError`),gd(t,n),t}},bd=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??yd;let t=`default`in cs.default?cs.default.default:cs.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>rd(()=>e(...t).catch(e=>{throw e instanceof Error?e:Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((t,n)=>{r=()=>{n(tu(e.signal))},e.signal?.addEventListener(`abort`,r,{once:!0})})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener(`abort`,r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},xd=class extends Yc{name=`RootListenersTracer`;rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Sd(e){return e?e.lc_runnable:!1}var Cd=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(t)),this.includeTags!==void 0&&(n||=r.some(e=>this.includeTags?.includes(e))),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n&&=r.every(e=>!this.excludeTags?.includes(e))),n}},wd=e=>btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``),Td;function A(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Ed=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Dd=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Td=globalThis).__zod_globalConfig??(Td.__zod_globalConfig={});var Od=globalThis.__zod_globalConfig;function kd(e){return e&&Object.assign(Od,e),Od}function Ad(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function jd(e,t){return typeof t==`bigint`?t.toString():t}function Md(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function Nd(e){return e==null}function Pd(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Fd(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var Id=Symbol(`evaluating`);function Ld(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Id)return r===void 0&&(r=Id,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rd(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function zd(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Bd(e){return JSON.stringify(e)}function Vd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Hd=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ud(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wd=Md(()=>{if(Od.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Gd(e){if(Ud(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Ud(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Kd(e){return Gd(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var qd=new Set([`string`,`number`,`symbol`]);function Jd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Yd(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Xd(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Zd={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Qd(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Yd(e,zd(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Rd(this,`shape`,e),e},checks:[]}))}function $d(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Yd(e,zd(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Rd(this,`shape`,r),r},checks:[]}))}function ef(e,t){if(!Gd(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Yd(e,zd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rd(this,`shape`,n),n}}))}function tf(e,t){if(!Gd(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Yd(e,zd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Rd(this,`shape`,n),n}}))}function nf(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Yd(e,zd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Rd(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function rf(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Yd(t,zd(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Rd(this,`shape`,i),i},checks:[]}))}function af(e,t,n){return Yd(t,zd(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Rd(this,`shape`,i),i}}))}function of(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function sf(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function cf(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function lf(e){return typeof e==`string`?e:e?.message}function uf(e,t,n){let r=e.message?e.message:lf(e.inst?._zod.def?.error?.(e))??lf(t?.error?.(e))??lf(n.customError?.(e))??lf(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function df(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ff(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var pf=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jd,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},mf=A(`$ZodError`,pf),hf=A(`$ZodError`,pf,{Parent:Error});function gf(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function _f(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...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{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}function vf(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function yf(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${vf(e.path)}`);return t.join(`
|
|
26
|
+
`)}var bf=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Ed;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>uf(e,a,kd())));throw Hd(t,i?.callee),t}return o.value},xf=bf(hf),Sf=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>uf(e,a,kd())));throw Hd(t,i?.callee),t}return o.value},Cf=Sf(hf),wf=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ed;return a.issues.length?{success:!1,error:new(e??mf)(a.issues.map(e=>uf(e,i,kd())))}:{success:!0,data:a.value}},Tf=wf(hf),Ef=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>uf(e,i,kd())))}:{success:!0,data:a.value}},Df=Ef(hf),Of=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return bf(e)(t,n,i)},kf=e=>(t,n,r)=>bf(e)(t,n,r),Af=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Sf(e)(t,n,i)},jf=e=>async(t,n,r)=>Sf(e)(t,n,r),Mf=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return wf(e)(t,n,i)},Nf=e=>(t,n,r)=>wf(e)(t,n,r),Pf=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Ef(e)(t,n,i)},Ff=e=>async(t,n,r)=>Ef(e)(t,n,r),If=/^[cC][0-9a-z]{6,}$/,Lf=/^[0-9a-z]+$/,Rf=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zf=/^[0-9a-vA-V]{20}$/,Bf=/^[A-Za-z0-9]{27}$/,Vf=/^[a-zA-Z0-9_-]{21}$/,Hf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Uf=/^([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})$/,Wf=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Gf=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Kf=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function qf(){return new RegExp(Kf,`u`)}var Jf=/^(?:(?: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=/^(([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}|:))$/,Xf=/^((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])$/,Zf=/^(([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])$/,Qf=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$f=/^[A-Za-z0-9_-]*$/,ep=/^https?$/,tp=/^\+[1-9]\d{6,14}$/,np=`(?:(?:\\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])))`,rp=RegExp(`^${np}$`);function ip(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ap(e){return RegExp(`^${ip(e)}$`)}function op(e){let t=ip({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${np}T(?:${r})$`)}var sp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},cp=/^-?\d+$/,lp=/^-?\d+(?:\.\d+)?$/,up=/^(?:true|false)$/i,dp=/^[^A-Z]*$/,fp=/^[^a-z]*$/,pp=A(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),mp={number:`number`,bigint:`bigint`,object:`date`},hp=A(`$ZodCheckLessThan`,(e,t)=>{pp.init(e,t);let n=mp[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),gp=A(`$ZodCheckGreaterThan`,(e,t)=>{pp.init(e,t);let n=mp[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_p=A(`$ZodCheckMultipleOf`,(e,t)=>{pp.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Fd(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),vp=A(`$ZodCheckNumberFormat`,(e,t)=>{pp.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Zd[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=cp)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),yp=A(`$ZodCheckMaxLength`,(e,t)=>{var n;pp.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=df(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),bp=A(`$ZodCheckMinLength`,(e,t)=>{var n;pp.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=df(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),xp=A(`$ZodCheckLengthEquals`,(e,t)=>{var n;pp.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=df(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Sp=A(`$ZodCheckStringFormat`,(e,t)=>{var n,r;pp.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Cp=A(`$ZodCheckRegex`,(e,t)=>{Sp.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),wp=A(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=dp,Sp.init(e,t)}),Tp=A(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=fp,Sp.init(e,t)}),Ep=A(`$ZodCheckIncludes`,(e,t)=>{pp.init(e,t);let n=Jd(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Dp=A(`$ZodCheckStartsWith`,(e,t)=>{pp.init(e,t);let n=RegExp(`^${Jd(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Op=A(`$ZodCheckEndsWith`,(e,t)=>{pp.init(e,t);let n=RegExp(`.*${Jd(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),kp=A(`$ZodCheckOverwrite`,(e,t)=>{pp.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Ap=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
27
27
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
28
28
|
`))}},jp={major:4,minor:4,patch:3},Mp=A(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=jp;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=of(e),i;for(let a of t){if(a._zod.def.when){if(sf(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Ed;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=of(e,t))});else{if(e.issues.length===t)continue;r||=of(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(of(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Ed;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Ed;return o.then(e=>t(e,r,a))}return t(o,r,a)}}Ld(e,`~standard`,()=>({validate:t=>{try{let n=Tf(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Df(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Np=A(`$ZodString`,(e,t)=>{Mp.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??sp(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Pp=A(`$ZodStringFormat`,(e,t)=>{Sp.init(e,t),Np.init(e,t)}),Fp=A(`$ZodGUID`,(e,t)=>{t.pattern??=Uf,Pp.init(e,t)}),Ip=A(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Wf(e)}else t.pattern??=Wf();Pp.init(e,t)}),Lp=A(`$ZodEmail`,(e,t)=>{t.pattern??=Gf,Pp.init(e,t)}),Rp=A(`$ZodURL`,(e,t)=>{Pp.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===ep.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),zp=A(`$ZodEmoji`,(e,t)=>{t.pattern??=qf(),Pp.init(e,t)}),Bp=A(`$ZodNanoID`,(e,t)=>{t.pattern??=Vf,Pp.init(e,t)}),Vp=A(`$ZodCUID`,(e,t)=>{t.pattern??=If,Pp.init(e,t)}),Hp=A(`$ZodCUID2`,(e,t)=>{t.pattern??=Lf,Pp.init(e,t)}),Up=A(`$ZodULID`,(e,t)=>{t.pattern??=Rf,Pp.init(e,t)}),Wp=A(`$ZodXID`,(e,t)=>{t.pattern??=zf,Pp.init(e,t)}),Gp=A(`$ZodKSUID`,(e,t)=>{t.pattern??=Bf,Pp.init(e,t)}),Kp=A(`$ZodISODateTime`,(e,t)=>{t.pattern??=op(t),Pp.init(e,t)}),qp=A(`$ZodISODate`,(e,t)=>{t.pattern??=rp,Pp.init(e,t)}),Jp=A(`$ZodISOTime`,(e,t)=>{t.pattern??=ap(t),Pp.init(e,t)}),Yp=A(`$ZodISODuration`,(e,t)=>{t.pattern??=Hf,Pp.init(e,t)}),Xp=A(`$ZodIPv4`,(e,t)=>{t.pattern??=Jf,Pp.init(e,t),e._zod.bag.format=`ipv4`}),Zp=A(`$ZodIPv6`,(e,t)=>{t.pattern??=Yf,Pp.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Qp=A(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Xf,Pp.init(e,t)}),$p=A(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Zf,Pp.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function em(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var tm=A(`$ZodBase64`,(e,t)=>{t.pattern??=Qf,Pp.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{em(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function nm(e){if(!$f.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return em(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var rm=A(`$ZodBase64URL`,(e,t)=>{t.pattern??=$f,Pp.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{nm(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),im=A(`$ZodE164`,(e,t)=>{t.pattern??=tp,Pp.init(e,t)});function am(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var om=A(`$ZodJWT`,(e,t)=>{Pp.init(e,t),e._zod.check=n=>{am(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),sm=A(`$ZodNumber`,(e,t)=>{Mp.init(e,t),e._zod.pattern=e._zod.bag.pattern??lp,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),cm=A(`$ZodNumberFormat`,(e,t)=>{vp.init(e,t),sm.init(e,t)}),lm=A(`$ZodBoolean`,(e,t)=>{Mp.init(e,t),e._zod.pattern=up,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),um=A(`$ZodAny`,(e,t)=>{Mp.init(e,t),e._zod.parse=e=>e}),dm=A(`$ZodUnknown`,(e,t)=>{Mp.init(e,t),e._zod.parse=e=>e}),fm=A(`$ZodNever`,(e,t)=>{Mp.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function pm(e,t,n){e.issues.length&&t.issues.push(...cf(n,e.issues)),t.value[n]=e.value}var mm=A(`$ZodArray`,(e,t)=>{Mp.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>pm(t,n,e))):pm(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function hm(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...cf(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function gm(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Xd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function _m(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>hm(e,n,i,t,u,d))):hm(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var vm=A(`$ZodObject`,(e,t)=>{if(Mp.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=Md(()=>gm(t));Ld(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Ud,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>hm(n,t,e,s,r,i))):hm(a,t,e,s,r,i)}return i?_m(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),ym=A(`$ZodObjectJIT`,(e,t)=>{vm.init(e,t);let n=e._zod.parse,r=Md(()=>gm(t)),i=e=>{let t=new Ap([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Bd(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Bd(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
29
29
|
if (${n}.issues.length) {
|
|
@@ -86,7 +86,7 @@ Please make sure you are calling this method within a traceable function and tha
|
|
|
86
86
|
|
|
87
87
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Ud,s=!Od.jitless,c=s&&Wd.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?_m([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function bm(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!of(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>uf(e,r,kd())))}),t)}var xm=A(`$ZodUnion`,(e,t)=>{Mp.init(e,t),Ld(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),Ld(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Ld(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ld(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Pd(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>bm(t,r,e,i)):bm(o,r,e,i)}}),Sm=A(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,xm.init(e,t);let n=e._zod.parse;Ld(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=Md(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Ud(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),Cm=A(`$ZodIntersection`,(e,t)=>{Mp.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Tm(e,t,n)):Tm(e,i,a)}});function wm(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Gd(e)&&Gd(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=wm(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=wm(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Tm(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),of(e))return e;let o=wm(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Em=A(`$ZodTuple`,(e,t)=>{Mp.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=Dm(n,`optin`),c=Dm(n,`optout`);if(!t.rest){if(a.length<s)return r.issues.push({code:`too_small`,minimum:s,inclusive:!0,input:a,inst:e,origin:`array`}),r;a.length>n.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>Om(t,r,e))):Om(a,r,e)}}return o.length?Promise.all(o).then(()=>km(l,r,n,a,c)):km(l,r,n,a,c)}});function Dm(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function Om(e,t,n){e.issues.length&&t.issues.push(...cf(n,e.issues)),t.value[n]=e.value}function km(e,t,n,r,i){for(let a=0;a<n.length;a++){let n=e[a],o=a<r.length;if(n.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...cf(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var Am=A(`$ZodRecord`,(e,t)=>{Mp.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Gd(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>uf(e,r,kd())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...cf(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...cf(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&lp.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>uf(e,r,kd())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...cf(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...cf(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),jm=A(`$ZodEnum`,(e,t)=>{Mp.init(e,t);let n=Ad(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>qd.has(typeof e)).map(e=>typeof e==`string`?Jd(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Mm=A(`$ZodLiteral`,(e,t)=>{if(Mp.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Jd(e):e?Jd(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Nm=A(`$ZodTransform`,(e,t)=>{Mp.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Dd(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Ed;return n.value=i,n.fallback=!0,n}});function Pm(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Fm=A(`$ZodOptional`,(e,t)=>{Mp.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,Ld(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ld(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Pd(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Pm(e,r)):Pm(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Im=A(`$ZodExactOptional`,(e,t)=>{Fm.init(e,t),Ld(e._zod,`values`,()=>t.innerType._zod.values),Ld(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Lm=A(`$ZodNullable`,(e,t)=>{Mp.init(e,t),Ld(e._zod,`optin`,()=>t.innerType._zod.optin),Ld(e._zod,`optout`,()=>t.innerType._zod.optout),Ld(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Pd(e.source)}|null)$`):void 0}),Ld(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Rm=A(`$ZodDefault`,(e,t)=>{Mp.init(e,t),e._zod.optin=`optional`,Ld(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>zm(e,t)):zm(r,t)}});function zm(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Bm=A(`$ZodPrefault`,(e,t)=>{Mp.init(e,t),e._zod.optin=`optional`,Ld(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Vm=A(`$ZodNonOptional`,(e,t)=>{Mp.init(e,t),Ld(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Hm(t,e)):Hm(i,e)}});function Hm(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Um=A(`$ZodCatch`,(e,t)=>{Mp.init(e,t),e._zod.optin=`optional`,Ld(e._zod,`optout`,()=>t.innerType._zod.optout),Ld(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>uf(e,n,kd()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>uf(e,n,kd()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Wm=A(`$ZodPipe`,(e,t)=>{Mp.init(e,t),Ld(e._zod,`values`,()=>t.in._zod.values),Ld(e._zod,`optin`,()=>t.in._zod.optin),Ld(e._zod,`optout`,()=>t.out._zod.optout),Ld(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Gm(e,t.in,n)):Gm(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Gm(e,t.out,n)):Gm(r,t.out,n)}});function Gm(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Km=A(`$ZodReadonly`,(e,t)=>{Mp.init(e,t),Ld(e._zod,`propValues`,()=>t.innerType._zod.propValues),Ld(e._zod,`values`,()=>t.innerType._zod.values),Ld(e._zod,`optin`,()=>t.innerType?._zod?.optin),Ld(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(qm):qm(r)}});function qm(e){return e.value=Object.freeze(e.value),e}var Jm=A(`$ZodCustom`,(e,t)=>{pp.init(e,t),Mp.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ym(t,n,r,e));Ym(i,n,r,e)}});function Ym(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ff(e))}}var Xm,Zm=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Qm(){return new Zm}(Xm=globalThis).__zod_globalRegistry??(Xm.__zod_globalRegistry=Qm());var $m=globalThis.__zod_globalRegistry;function eh(e,t){return new e({type:`string`,...j(t)})}function th(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...j(t)})}function nh(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...j(t)})}function rh(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...j(t)})}function ih(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...j(t)})}function ah(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...j(t)})}function oh(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...j(t)})}function sh(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...j(t)})}function ch(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...j(t)})}function lh(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...j(t)})}function uh(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...j(t)})}function dh(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...j(t)})}function fh(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...j(t)})}function ph(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...j(t)})}function mh(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...j(t)})}function hh(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...j(t)})}function gh(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...j(t)})}function _h(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...j(t)})}function vh(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...j(t)})}function yh(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...j(t)})}function bh(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...j(t)})}function xh(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...j(t)})}function Sh(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...j(t)})}function Ch(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...j(t)})}function wh(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...j(t)})}function Th(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...j(t)})}function Eh(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...j(t)})}function Dh(e,t){return new e({type:`number`,checks:[],...j(t)})}function Oh(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...j(t)})}function kh(e,t){return new e({type:`boolean`,...j(t)})}function Ah(e){return new e({type:`any`})}function jh(e){return new e({type:`unknown`})}function Mh(e,t){return new e({type:`never`,...j(t)})}function Nh(e,t){return new hp({check:`less_than`,...j(t),value:e,inclusive:!1})}function Ph(e,t){return new hp({check:`less_than`,...j(t),value:e,inclusive:!0})}function Fh(e,t){return new gp({check:`greater_than`,...j(t),value:e,inclusive:!1})}function Ih(e,t){return new gp({check:`greater_than`,...j(t),value:e,inclusive:!0})}function Lh(e,t){return new _p({check:`multiple_of`,...j(t),value:e})}function Rh(e,t){return new yp({check:`max_length`,...j(t),maximum:e})}function zh(e,t){return new bp({check:`min_length`,...j(t),minimum:e})}function Bh(e,t){return new xp({check:`length_equals`,...j(t),length:e})}function Vh(e,t){return new Cp({check:`string_format`,format:`regex`,...j(t),pattern:e})}function Hh(e){return new wp({check:`string_format`,format:`lowercase`,...j(e)})}function Uh(e){return new Tp({check:`string_format`,format:`uppercase`,...j(e)})}function Wh(e,t){return new Ep({check:`string_format`,format:`includes`,...j(t),includes:e})}function Gh(e,t){return new Dp({check:`string_format`,format:`starts_with`,...j(t),prefix:e})}function Kh(e,t){return new Op({check:`string_format`,format:`ends_with`,...j(t),suffix:e})}function qh(e){return new kp({check:`overwrite`,tx:e})}function Jh(e){return qh(t=>t.normalize(e))}function Yh(){return qh(e=>e.trim())}function Xh(){return qh(e=>e.toLowerCase())}function Zh(){return qh(e=>e.toUpperCase())}function Qh(){return qh(e=>Vd(e))}function $h(e,t,n){return new e({type:`array`,element:t,...j(n)})}function eg(e,t,n){let r=j(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function tg(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...j(n)})}function ng(e,t){let n=rg(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(ff(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(ff(r))}},e(t.value,t)),t);return n}function rg(e,t){let n=new pp({check:`custom`,...j(t)});return n._zod.check=e,n}function ig(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??$m,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function ag(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,ag(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&cg(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function og(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
88
88
|
|
|
89
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function sg(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:ug(t,`input`,e.processors),output:ug(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function cg(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return cg(r.element,n);if(r.type===`set`)return cg(r.valueType,n);if(r.type===`lazy`)return cg(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return cg(r.innerType,n);if(r.type===`intersection`)return cg(r.left,n)||cg(r.right,n);if(r.type===`record`||r.type===`map`)return cg(r.keyType,n)||cg(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:cg(r.in,n)||cg(r.out,n);if(r.type===`object`){for(let e in r.shape)if(cg(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(cg(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(cg(e,n))return!0;return!!(r.rest&&cg(r.rest,n))}return!1}var lg=(e,t={})=>n=>{let r=ig({...n,processors:t});return ag(e,r),og(r,e),sg(r,e)},ug=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ig({...i??{},target:a,io:t,processors:n});return ag(e,o),og(o,e),sg(o,e)},dg={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},fg=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=dg[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},pg=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},mg=(e,t,n,r)=>{n.type=`boolean`},hg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},gg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},_g=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},vg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},yg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},bg=(e,t,n,r)=>{n.not={}},xg=(e,t,n,r)=>{},Sg=(e,t,n,r)=>{},Cg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},wg=(e,t,n,r)=>{let i=e._zod.def,a=Ad(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Tg=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Eg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Dg=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Og=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},kg=(e,t,n,r)=>{n.type=`boolean`},Ag=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},jg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Mg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ng=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Pg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Fg=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=ag(a.element,t,{...r,path:[...r.path,`items`]})},Ig=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=ag(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=ag(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Lg=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>ag(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Rg=(e,t,n,r)=>{let i=e._zod.def,a=ag(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=ag(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},zg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>ag(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?ag(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Bg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=ag(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=ag(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=ag(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Vg=(e,t,n,r)=>{let i=e._zod.def,a=ag(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Hg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ug=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Wg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Gg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Kg=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;ag(o,t,r);let s=t.seen.get(e);s.ref=o},qg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Jg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Yg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xg={string:fg,number:pg,boolean:mg,bigint:hg,symbol:gg,null:_g,undefined:vg,void:yg,never:bg,any:xg,unknown:Sg,date:Cg,enum:wg,literal:Tg,nan:Eg,template_literal:Dg,file:Og,success:kg,custom:Ag,function:jg,transform:Mg,map:Ng,set:Pg,array:Fg,object:Ig,union:Lg,intersection:Rg,tuple:zg,record:Bg,nullable:Vg,nonoptional:Hg,default:Ug,prefault:Wg,catch:Gg,pipe:Kg,readonly:qg,promise:Jg,optional:Yg,lazy:(e,t,n,r)=>{let i=e._zod.innerType;ag(i,t,r);let a=t.seen.get(e);a.ref=i}};function Zg(e,t){if(`_idmap`in e){let n=e,r=ig({...t,processors:Xg}),i={};for(let e of n._idmap.entries()){let[t,n]=e;ag(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;og(r,n),a[t]=sg(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=ig({...t,processors:Xg});return ag(e,n),og(n,e),sg(n,e)}function Qg(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_zod`in t))return!1;let n=t._zod;return typeof n==`object`&&!!n&&`def`in n}function $g(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_def`in t)||`_zod`in t)return!1;let n=t._def;return typeof n==`object`&&!!n&&`typeName`in n}function e_(e){return Qg(e)&&console.warn(`[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.`),$g(e)}function t_(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:!!(Qg(e)||$g(e))}function n_(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodLiteral`)}function r_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`literal`):!1}function i_(e){return!!(n_(e)||r_(e))}async function a_(e,t){if(Qg(e))try{return{success:!0,data:await Cf(e,t)}}catch(e){return{success:!1,error:e}}if($g(e))return await e.safeParseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}async function o_(e,t){if(Qg(e))return await Cf(e,t);if($g(e))return await e.parseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function s_(e,t){if(Qg(e))try{return{success:!0,data:xf(e,t)}}catch(e){return{success:!1,error:e}}if($g(e))return e.safeParse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function c_(e,t){if(Qg(e))return xf(e,t);if($g(e))return e.parse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function l_(e){if(Qg(e))return $m.get(e)?.description;if($g(e)||`description`in e&&typeof e.description==`string`)return e.description}function u_(e){if(!t_(e))return!1;if($g(e)){let t=e._def;if(t.typeName===`ZodObject`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.typeName===`ZodRecord`)return!0}if(Qg(e)){let t=e._zod.def;if(t.type===`object`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.type===`record`)return!0}return!!(typeof e==`object`&&e&&!(`shape`in e))}function d_(e){return t_(e)?$g(e)?e._def.typeName===`ZodString`:Qg(e)?e._zod.def.type===`string`:!1:!1}function f_(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodObject`)}function p_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`object`):!1}function m_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`array`):!1}function h_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`optional`):!1}function g_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`nullable`):!1}function __(e){return!!(f_(e)||p_(e))}function v_(e){if($g(e))return e.shape;if(Qg(e))return e._zod.def.shape;throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function y_(e,t){if($g(e))return e.extend(t);if(Qg(e))return ef(e,t);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function b_(e){if($g(e))return e.partial();if(Qg(e))return rf(Fm,e,void 0);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function x_(e,t=!1){if(f_(e))return e.strict();if(p_(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(p_(i))n[r]=x_(i,t);else if(m_(i)){let e=i._zod.def.element;p_(e)&&(e=x_(e,t)),n[r]=Yd(i,{...i._zod.def,element:e})}else n[r]=i;let e=$m.get(i);e&&$m.add(n[r],e)}let r=Yd(e,{...e._zod.def,shape:n,catchall:Mh(fm)}),i=$m.get(e);return i&&$m.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function S_(e,t=!1){if(f_(e))return e.passthrough();if(p_(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(p_(i))n[r]=S_(i,t);else if(m_(i)){let e=i._zod.def.element;p_(e)&&(e=S_(e,t)),n[r]=Yd(i,{...i._zod.def,element:e})}else n[r]=i;let e=$m.get(i);e&&$m.add(n[r],e)}let r=Yd(e,{...e._zod.def,shape:n,catchall:jh(dm)}),i=$m.get(e);return i&&$m.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function C_(e){if($g(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(Qg(e))try{let t=xf(e,void 0);return()=>t}catch{return}}function w_(e){return $g(e)&&`typeName`in e._def&&e._def.typeName===`ZodEffects`}function T_(e){return Qg(e)&&e._zod.def.type===`pipe`}function E_(e,t,n){let r=n.get(e);if(r!==void 0)return r;if($g(e))return w_(e)?E_(e._def.schema,t,n):e;if(Qg(e)){let r=e;if(T_(e)&&(r=E_(e._zod.def.in,t,n)),t){if(p_(r)){let e={};for(let[i,a]of Object.entries(r._zod.def.shape))e[i]=E_(a,t,n);r=Yd(r,{...r._zod.def,shape:e})}else if(m_(r)){let e=E_(r._zod.def.element,t,n);r=Yd(r,{...r._zod.def,element:e})}else if(h_(r)){let e=E_(r._zod.def.innerType,t,n);r=Yd(r,{...r._zod.def,innerType:e})}else if(g_(r)){let e=E_(r._zod.def.innerType,t,n);r=Yd(r,{...r._zod.def,innerType:e})}}let i=$m.get(e);return i&&$m.add(r,i),n.set(e,r),r}throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function D_(e,t=!1){return E_(e,t,new WeakMap)}function O_(e,t){if($g(e)){let n=v_(e),r={};for(let[e,i]of Object.entries(n))t(e,i)?r[e]=i.optional():r[e]=i;return e.extend(r)}if(Qg(e)){let n=v_(e),r={...e._zod.def.shape};for(let[e,i]of Object.entries(n))t(e,i)&&(r[e]=new Fm({type:`optional`,innerType:i}));let i=Yd(e,{...e._zod.def,shape:r}),a=$m.get(e);return a&&$m.add(i,a),i}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function k_(e){return e instanceof Error&&(e.constructor.name===`ZodError`||e.constructor.name===`$ZodError`)}function A_(e){return e.replace(/[^a-zA-Z-_0-9]/g,`_`)}var j_=[`*`,`_`,"`"];function M_(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}function N_(e,t,n){let{firstNode:r,lastNode:i,nodeColors:a,withStyles:o=!0,curveStyle:s=`linear`,wrapLabelNWords:c=9}=n??{},l=o?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:`graph TD;
|
|
89
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function sg(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:ug(t,`input`,e.processors),output:ug(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function cg(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return cg(r.element,n);if(r.type===`set`)return cg(r.valueType,n);if(r.type===`lazy`)return cg(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return cg(r.innerType,n);if(r.type===`intersection`)return cg(r.left,n)||cg(r.right,n);if(r.type===`record`||r.type===`map`)return cg(r.keyType,n)||cg(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:cg(r.in,n)||cg(r.out,n);if(r.type===`object`){for(let e in r.shape)if(cg(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(cg(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(cg(e,n))return!0;return!!(r.rest&&cg(r.rest,n))}return!1}var lg=(e,t={})=>n=>{let r=ig({...n,processors:t});return ag(e,r),og(r,e),sg(r,e)},ug=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ig({...i??{},target:a,io:t,processors:n});return ag(e,o),og(o,e),sg(o,e)},dg={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},fg=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=dg[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},pg=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},mg=(e,t,n,r)=>{n.type=`boolean`},hg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},gg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},_g=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},vg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},yg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},bg=(e,t,n,r)=>{n.not={}},xg=(e,t,n,r)=>{},Sg=(e,t,n,r)=>{},Cg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},wg=(e,t,n,r)=>{let i=e._zod.def,a=Ad(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Tg=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Eg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},Dg=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Og=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},kg=(e,t,n,r)=>{n.type=`boolean`},Ag=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},jg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Mg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ng=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Pg=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},Fg=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=ag(a.element,t,{...r,path:[...r.path,`items`]})},Ig=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=ag(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=ag(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Lg=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>ag(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Rg=(e,t,n,r)=>{let i=e._zod.def,a=ag(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=ag(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},zg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>ag(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?ag(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Bg=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=ag(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=ag(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=ag(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Vg=(e,t,n,r)=>{let i=e._zod.def,a=ag(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Hg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ug=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Wg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Gg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Kg=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;ag(o,t,r);let s=t.seen.get(e);s.ref=o},qg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Jg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Yg=(e,t,n,r)=>{let i=e._zod.def;ag(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xg={string:fg,number:pg,boolean:mg,bigint:hg,symbol:gg,null:_g,undefined:vg,void:yg,never:bg,any:xg,unknown:Sg,date:Cg,enum:wg,literal:Tg,nan:Eg,template_literal:Dg,file:Og,success:kg,custom:Ag,function:jg,transform:Mg,map:Ng,set:Pg,array:Fg,object:Ig,union:Lg,intersection:Rg,tuple:zg,record:Bg,nullable:Vg,nonoptional:Hg,default:Ug,prefault:Wg,catch:Gg,pipe:Kg,readonly:qg,promise:Jg,optional:Yg,lazy:(e,t,n,r)=>{let i=e._zod.innerType;ag(i,t,r);let a=t.seen.get(e);a.ref=i}};function Zg(e,t){if(`_idmap`in e){let n=e,r=ig({...t,processors:Xg}),i={};for(let e of n._idmap.entries()){let[t,n]=e;ag(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;og(r,n),a[t]=sg(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=ig({...t,processors:Xg});return ag(e,n),og(n,e),sg(n,e)}function Qg(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_zod`in t))return!1;let n=t._zod;return typeof n==`object`&&!!n&&`def`in n}function $g(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_def`in t)||`_zod`in t)return!1;let n=t._def;return typeof n==`object`&&!!n&&`typeName`in n}function e_(e){return Qg(e)&&console.warn(`[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior.`),$g(e)}function t_(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:!!(Qg(e)||$g(e))}function n_(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodLiteral`)}function r_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`literal`):!1}function i_(e){return!!(n_(e)||r_(e))}async function a_(e,t){if(Qg(e))try{return{success:!0,data:await Cf(e,t)}}catch(e){return{success:!1,error:e}}if($g(e))return await e.safeParseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}async function o_(e,t){if(Qg(e))return await Cf(e,t);if($g(e))return await e.parseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function s_(e,t){if(Qg(e))try{return{success:!0,data:xf(e,t)}}catch(e){return{success:!1,error:e}}if($g(e))return e.safeParse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function c_(e,t){if(Qg(e))return xf(e,t);if($g(e))return e.parse(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function l_(e){if(Qg(e))return $m.get(e)?.description;if($g(e)||`description`in e&&typeof e.description==`string`)return e.description}function u_(e){if(!t_(e))return!1;if($g(e)){let t=e._def;if(t.typeName===`ZodObject`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.typeName===`ZodRecord`)return!0}if(Qg(e)){let t=e._zod.def;if(t.type===`object`){let t=e;return!t.shape||Object.keys(t.shape).length===0}if(t.type===`record`)return!0}return!!(typeof e==`object`&&e&&!(`shape`in e))}function d_(e){return t_(e)?$g(e)?e._def.typeName===`ZodString`:Qg(e)?e._zod.def.type===`string`:!1:!1}function f_(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodObject`)}function p_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`object`):!1}function m_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`array`):!1}function h_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`optional`):!1}function g_(e){return Qg(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`nullable`):!1}function __(e){return!!(f_(e)||p_(e))}function v_(e){if($g(e))return e.shape;if(Qg(e))return e._zod.def.shape;throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function y_(e,t){if($g(e))return e.extend(t);if(Qg(e))return ef(e,t);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function b_(e){if($g(e))return e.partial();if(Qg(e))return rf(Fm,e,void 0);throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function x_(e,t=!1){if(f_(e))return e.strict();if(p_(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(p_(i))n[r]=x_(i,t);else if(m_(i)){let e=i._zod.def.element;p_(e)&&(e=x_(e,t)),n[r]=Yd(i,{...i._zod.def,element:e})}else n[r]=i;let e=$m.get(i);e&&$m.add(n[r],e)}let r=Yd(e,{...e._zod.def,shape:n,catchall:Mh(fm)}),i=$m.get(e);return i&&$m.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function S_(e,t=!1){if(f_(e))return e.passthrough();if(p_(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(p_(i))n[r]=S_(i,t);else if(m_(i)){let e=i._zod.def.element;p_(e)&&(e=S_(e,t)),n[r]=Yd(i,{...i._zod.def,element:e})}else n[r]=i;let e=$m.get(i);e&&$m.add(n[r],e)}let r=Yd(e,{...e._zod.def,shape:n,catchall:jh(dm)}),i=$m.get(e);return i&&$m.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function C_(e){if($g(e))try{let t=e.parse(void 0);return()=>t}catch{return}if(Qg(e))try{let t=xf(e,void 0);return()=>t}catch{return}}function w_(e){return $g(e)&&`typeName`in e._def&&e._def.typeName===`ZodEffects`}function T_(e){return Qg(e)&&e._zod.def.type===`pipe`}function E_(e,t,n){let r=n.get(e);if(r!==void 0)return r;if($g(e))return w_(e)?E_(e._def.schema,t,n):e;if(Qg(e)){let r=e;if(T_(e)&&(r=E_(e._zod.def.in,t,n)),t){if(p_(r)){let e={};for(let[i,a]of Object.entries(r._zod.def.shape))e[i]=E_(a,t,n);r=Yd(r,{...r._zod.def,shape:e})}else if(m_(r)){let e=E_(r._zod.def.element,t,n);r=Yd(r,{...r._zod.def,element:e})}else if(h_(r)){let e=E_(r._zod.def.innerType,t,n);r=Yd(r,{...r._zod.def,innerType:e})}else if(g_(r)){let e=E_(r._zod.def.innerType,t,n);r=Yd(r,{...r._zod.def,innerType:e})}}let i=$m.get(e);return i&&$m.add(r,i),n.set(e,r),r}throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function D_(e,t=!1){return E_(e,t,new WeakMap)}function O_(e,t){if($g(e)){let n=v_(e),r={};for(let[e,i]of Object.entries(n))t(e,i)?r[e]=i.optional():r[e]=i;return e.extend(r)}if(Qg(e)){let n=v_(e),r={...e._zod.def.shape};for(let[e,i]of Object.entries(n))t(e,i)&&(r[e]=new Fm({type:`optional`,innerType:i}));let i=Yd(e,{...e._zod.def,shape:r}),a=$m.get(e);return a&&$m.add(i,a),i}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function k_(e){return e instanceof Error&&(e.constructor.name===`ZodError`||e.constructor.name===`$ZodError`)}function A_(e){return e.replace(/[^a-zA-Z-_0-9]/g,`_`)}var j_=[`*`,`_`,"`"];function M_(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}function N_(e,t,n){let{firstNode:r,lastNode:i,nodeColors:a,withStyles:o=!0,curveStyle:s=`linear`,wrapLabelNWords:c=9}=n??{},l=o?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:`graph TD;
|
|
90
90
|
`;if(o){let t=`default`,n={[t]:`{0}({1})`};r!==void 0&&(n[r]=`{0}([{1}]):::first`),i!==void 0&&(n[i]=`{0}([{1}]):::last`);for(let[r,i]of Object.entries(e)){let e=i.name.split(`:`).pop()??``,a=j_.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(i.metadata??{}).length&&(a+=`<hr/><small><em>${Object.entries(i.metadata??{}).map(([e,t])=>`${e} = ${t}`).join(`
|
|
91
91
|
`)}</em></small>`);let o=(n[r]??n[t]).replace(`{0}`,A_(r)).replace(`{1}`,a);l+=`\t${o}\n`}}let u={};for(let e of t){let t=e.source.split(`:`),n=e.target.split(`:`),r=t.filter((e,t)=>e===n[t]).join(`:`);u[r]||(u[r]=[]),u[r].push(e)}let d=new Set;function f(e){return[...e].sort((e,t)=>e.split(`:`).length-t.split(`:`).length)}function p(e,t){let n=e.length===1&&e[0].source===e[0].target;if(t&&!n){let e=t.split(`:`).pop();if(d.has(t))throw Error(`Found duplicate subgraph '${e}' at '${t} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(t),l+=`\tsubgraph ${e}\n`}let r=f(Object.keys(u).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(`:`).length===t.split(`:`).length+1));for(let e of r)p(u[e],e);for(let t of e){let{source:e,target:n,data:r,conditional:i}=t,a=``;if(r!==void 0){let e=r,t=e.split(` `);t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},(e,n)=>t.slice(n*c,(n+1)*c).join(` `)).join(` <br> `)),a=i?` -. ${e} .-> `:` -- ${e} --> `}else a=i?` -.-> `:` --> `;l+=`\t${A_(e)}${a}${A_(n)};\n`}t&&!n&&(l+=` end
|
|
92
92
|
`)}p(u[``]??[],``);for(let e in u)!e.includes(`:`)&&e!==``&&p(u[e],e);return o&&(l+=M_(a??{})),l}async function P_(e,t){let n=t?.backgroundColor??`white`,r=t?.imageType??`png`,i=wd(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let a=`https://mermaid.ink/img/${i}?bgColor=${n}&type=${r}`,o=await fetch(a);if(!o.ok)throw Error([`Failed to render the graph using the Mermaid.INK API.`,`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(`
|
|
@@ -97,7 +97,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
97
97
|
|
|
98
98
|
`)),n.close()}});return ru.fromReadableStream(n)}function hx(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var gx=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function _x(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function vx(e){return typeof e==`object`&&!!e&&typeof e.next==`function`}async function yx(e,t){try{let n=await e.next();for(;!n.done;)await t?.(n.value),n=await e.next();return n.value}finally{await e.return?.(void 0)}}function*bx(e,t){for(;;){let{value:n,done:r}=Wl.runWithConfig($l(e),t.next.bind(t),!0);if(r)break;yield n}}async function*xx(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await Wl.runWithConfig($l(e),n.next.bind(t),!0);if(i)break;yield r}}function Sx(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var Cx=class extends ve{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new Ex({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new wx({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new Nx({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Zl);if(t>1&&!Array.isArray(e)&&e.runId){console.warn(`Provided runId will be used only for the first element of the batch.`);let n=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`runId`));return Array.from({length:t},(t,r)=>Zl(r===0?e:n))}return Array.from({length:t},()=>Zl(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new bd({maxConcurrency:r[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:e=>{throw e}}),a=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=Zl(t),r=new ou({generator:this._streamIterator(e,n),config:n});return await r.setup,ru.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=Zl(e===void 0?e:{callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let r=Zl(n),i=await(await Yl(r))?.handleChainStart(this.toJSON(),Sx(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await eu(e.call(this,t,r,i),r.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(Sx(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(Yl)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),Sx(t[n],`input`),i[n].runId,i[n].runType,void 0,void 0,i[n].runName??this.getName());return delete i[n].runId,r})),s;try{s=await eu(e.call(this,t,i,o,r),i?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(Sx(s,`output`)))),s}_concatOutputChunks(e,t){return au(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=Zl(n),c=await Yl(s),l=this;async function*u(){for await(let t of e){if(i)if(r===void 0)r=t;else try{r=l._concatOutputChunks(r,t)}catch{r=void 0,i=!1}yield t}}let d;try{let e=await su(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:``},s.runId,s.runType,void 0,void 0,s.runName??this.getName(),void 0,{lc_defers_inputs:!0}),s.signal,s);delete s.runId,d=e.setup;let n=d?.handlers.find(Gu),r=e.output;n!==void 0&&d!==void 0&&(r=n.tapOutputIterable(d.runId,r));let i=d?.handlers.find(Fu);i!==void 0&&d!==void 0&&(r=i.tapOutputIterable(d.runId,r));for await(let e of r)if(yield e,o)if(a===void 0)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,o=!1}}catch(e){throw await d?.handleChainError(e,void 0,void 0,void 0,{inputs:Sx(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Sx(r,`input`)})}getGraph(e){let t=new dx,n=t.addNode({name:`${this.getName()}Input`,schema:by()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:by()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new Dx({first:this,last:Px(e)})}pick(e){return this.pipe(new Ix(e))}assign(e){return this.pipe(new Fx(new Ox({steps:e})))}async*transform(e,t){let n;for await(let t of e)n=n===void 0?t:this._concatOutputChunks(n,t);yield*this._streamIterator(n,Zl(t))}async*streamLog(e,t,n){let r=new zu({...n,autoClose:!1,_schemaFormat:`original`}),i=Zl(t);yield*this._streamLog(e,r,i)}async*_streamLog(e,t,n){let{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{let e=r.copy();e.addHandler(t,!0),n.callbacks=e}let i=this.stream(e,n);async function a(){try{let e=await i;for await(let n of e){let e=new Nu({ops:[{op:`add`,path:`/streamed_output/-`,value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}let o=a();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,n){let r;if(t.version===`v1`)r=this._streamEventsV1(e,t,n);else if(t.version===`v2`)r=this._streamEventsV2(e,t,n);else throw Error(`Only versions "v1" and "v2" of the schema are currently supported.`);return t.encoding===`text/event-stream`?mx(r):ru.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new Ku({...n,autoClose:!1}),i=Zl(t),a=i.runId??Sr();i.runId=a;let o=i.callbacks;if(o===void 0)i.callbacks=[r];else if(Array.isArray(o))i.callbacks=o.concat(r);else{let e=o.copy();e.addHandler(r,!0),i.callbacks=e}let s=new AbortController,c=this;async function l(){let t;try{if(i.signal)if(`any`in AbortSignal)t=AbortSignal.any([s.signal,i.signal]);else{let e=new AbortController;i.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),s.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),t=e.signal}else t=s.signal;let n=await c.stream(e,{...i,signal:t}),o=r.tapOutputIterable(a,n);for await(let e of o)if(s.signal.aborted)break}finally{await r.finish()}}let u=l(),d=!1,f;try{for await(let t of r){if(!d){t.data.input=e,d=!0,f=t.run_id,yield t;continue}t.run_id===f&&t.event.endsWith(`_end`)&&t.data?.input&&delete t.data.input,yield t}}finally{s.abort(),await u}}async*_streamEventsV1(e,t,n){let r,i=!1,a=Zl(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new zu({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new Cd({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):Pu.fromRunLogPatch(t),r.state===void 0)throw Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);if(!i){i=!0;let t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:o,metadata:s,data:{input:e}};u.includeEvent(n,t.type)&&(yield n)}let n=t.ops.filter(e=>e.path.startsWith(`/logs/`)).map(e=>e.path.split(`/`)[2]),a=[...new Set(n)];for(let e of a){let t,n={},i=r.state.logs[e];if(t=i.end_time===void 0?i.streamed_output.length>0?`stream`:`start`:`end`,t===`start`)i.inputs!==void 0&&(n.input=i.inputs);else if(t===`end`)i.inputs!==void 0&&(n.input=i.inputs),n.output=i.final_output;else if(t===`stream`){let e=i.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);n={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:n}}let{state:l}=r;if(l.streamed_output.length>0){let e=l.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);let t={chunk:l.streamed_output[0]};l.streamed_output=[];let n={event:`on_${l.type}_stream`,run_id:l.id,tags:o,metadata:s,name:c,data:t};u.includeEvent(n,l.type)&&(yield n)}}let f=r?.state;if(f!==void 0){let e={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:s,data:{output:f.final_output}};u.includeEvent(e,f.type)&&(yield e)}}static isRunnable(e){return Sd(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new wx({bound:this,config:{},configFactories:[r=>({callbacks:[new xd({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return Rx(this,e)}},wx=class e extends Cx{static lc_name(){return`RunnableBinding`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){let t=Xl(this.config,...e);return Xl(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Ex({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,n){let r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig(Zl(e),this.kwargs))):await this._mergeConfig(Zl(t),this.kwargs);return this.bound.batch(e,r,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(Zl(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(Zl(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(Zl(t),this.kwargs))}streamEvents(e,t,n){let r=this;return ru.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig(Zl(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&Cx.isRunnable(e.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new xd({config:e,onStart:t,onEnd:n,onError:r})]})]})}},Tx=class e extends Cx{static lc_name(){return`RunnableEach`}lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,Ql(t,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},Ex=class extends wx{static lc_name(){return`RunnableRetry`}lc_namespace=[`langchain_core`,`runnables`];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){let r=e>1?`retry:attempt:${e}`:void 0;return Ql(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return rd(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:({error:t})=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){let i={};try{await rd(async a=>{let o=e.map((e,t)=>t).filter(e=>i[e.toString()]===void 0||i[e.toString()]instanceof Error),s=o.map(t=>e[t]),c=o.map(e=>this._patchConfigForRetry(a,t?.[e],n?.[e])),l=await super.batch(s,c,{...r,returnExceptions:!0}),u;for(let e=0;e<l.length;e+=1){let t=l[e],n=o[e];t instanceof Error&&u===void 0&&(u=t,u.input=s[e]),i[n.toString()]=t}if(u)throw u;return l},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(r?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},Dx=class e extends Cx{static lc_name(){return`RunnableSequence`}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){let n=Zl(t),r=await(await Yl(n))?.handleChainStart(this.toJSON(),Sx(e,`input`),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,a;try{let e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)i=await eu(e[t].invoke(i,Ql(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw tu(n.signal);a=await this.last.invoke(i,Ql(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(Sx(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(Yl)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),Sx(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o=e;try{for(let e=0;e<this.steps.length;e+=1)o=await eu(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return Ql(r[n],{callbacks:i})}),n),r[0]?.signal)}catch(e){throw await Promise.all(a.map(t=>t?.handleChainError(e))),e}return await Promise.all(a.map(e=>e?.handleChainEnd(Sx(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await Yl(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),Sx(e,`input`),r,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last],s=!0,c;async function*l(){yield e}try{let e=o[0].transform(l(),Ql(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:1`)}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,Ql(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,s)if(c===void 0)c=n;else try{c=this._concatOutputChunks(c,n)}catch{c=void 0,s=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd(Sx(c,`output`))}getGraph(e){let t=new dx,n=null;return this.steps.forEach((r,i)=>{let a=r.getGraph(e);i!==0&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),t.extend(a);let o=a.firstNode();if(!o)throw Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,o),n=a.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:Px(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Cx.isRunnable(e)}static from([t,...n],r){let i={};return typeof r==`string`?i.name=r:r!==void 0&&(i=r),new e({...i,first:Px(t),middle:n.slice(0,-1).map(Px),last:Px(n[n.length-1])})}},Ox=class e extends Cx{static lc_name(){return`RunnableMap`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=Px(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=Zl(t),r=await(await Yl(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i={};try{let t=Object.entries(this.steps).map(async([t,a])=>{i[t]=await a.invoke(e,Ql(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await eu(Promise.all(t),n.signal)}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(i),i}async*_transform(e,t,n){let r={...this.steps},i=iu(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],Ql(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,o.next().then(t=>({key:e,gen:o,result:t}))]}));for(;a.size;){let{key:e,result:t,gen:r}=await eu(Promise.race(a.values()),n?.signal);a.delete(e),t.done||(yield{[e]:t.value},a.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=Zl(t),i=new ou({generator:this.transform(n(),r),config:r});return await i.setup,ru.fromAsyncGenerator(i)}},kx=class e extends Cx{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!dl(e.func))throw Error(`RunnableTraceable requires a function that is wrapped in traceable higher-order function`);this.func=e.func}async invoke(e,t){let[n]=this._getOptionsList(t??{},1),r=await Yl(n);return eu(this.func(Ql(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(_x(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(gx(r)){for(;;){n?.signal?.throwIfAborted();let e=r.next();if(e.done)break;yield e.value}return}yield r}static from(t){return new e({func:t})}};function Ax(e){if(dl(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var jx=class e extends Cx{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(dl(e.func))return kx.from(e.func);super(e),Ax(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,n){return new Promise((r,i)=>{let a=Ql(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});Wl.runWithConfig($l(a),async()=>{try{let n=await this.func(e,{...a});if(n&&Cx.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(_x(n)){let e;for await(let r of xx(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}else if(hx(n)){let e;for(let r of bx(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}r(n)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(let t of e)if(r===void 0)r=t;else try{r=this._concatOutputChunks(r,t)}catch{r=t}let i=Ql(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{Wl.runWithConfig($l(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&Cx.isRunnable(a)){if(n?.recursionLimit===0)throw Error(`Recursion limit reached.`);let e=await a.stream(r,i);for await(let t of e)yield t}else if(_x(a))for await(let e of xx(i,a))n?.signal?.throwIfAborted(),yield e;else if(hx(a))for(let e of bx(i,a))n?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=Zl(t),i=new ou({generator:this.transform(n(),r),config:r});return await i.setup,ru.fromAsyncGenerator(i)}},Mx=class extends Ox{},Nx=class extends Cx{static lc_name(){return`RunnableWithFallbacks`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let n=Zl(t),r=await Yl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),Sx(e,`input`),i,void 0,void 0,void 0,a?.runName),s=Ql(a,{callbacks:o?.getChild()});return await Wl.runWithConfig(s,async()=>{let t;for(let r of this.runnables()){n?.signal?.throwIfAborted();try{let t=await r.invoke(e,s);return await o?.handleChainEnd(Sx(t,`output`)),t}catch(e){t===void 0&&(t=e)}}throw t===void 0?Error(`No error stored at end of fallback.`):(await o?.handleChainError(t),t)})}async*_streamIterator(e,t){let n=Zl(t),r=await Yl(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),Sx(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=Ql(a,{callbacks:o?.getChild()});try{c=xx(r,await t.stream(e,r));break}catch(e){s===void 0&&(s=e)}}if(c===void 0){let e=s??Error(`No error stored at end of fallback.`);throw await o?.handleChainError(e),e}let l;try{for await(let e of c){yield e;try{l=l===void 0?l:this._concatOutputChunks(l,e)}catch{l=void 0}}}catch(e){throw await o?.handleChainError(e),e}await o?.handleChainEnd(Sx(l,`output`))}async batch(e,t,n){if(n?.returnExceptions)throw Error(`Not implemented.`);let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(e=>Yl(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),Sx(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o;for(let t of this.runnables()){r[0].signal?.throwIfAborted();try{let i=await t.batch(e,a.map((e,t)=>Ql(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(Sx(i[t],`output`)))),i}catch(e){o===void 0&&(o=e)}}throw o?(await Promise.all(a.map(e=>e?.handleChainError(o))),o):Error(`No error stored at end of fallbacks.`)}};function Px(e){if(typeof e==`function`)return new jx({func:e});if(Cx.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Px(r);return new Ox({steps:t})}else throw Error(`Expected a Runnable, function or object.
|
|
99
99
|
Instead got an unsupported type.`)}var Fx=class extends Cx{static lc_name(){return`RunnableAssign`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;mapper;constructor(e){e instanceof Ox&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){let r=this.mapper.getStepsKeys(),[i,a]=iu(e),o=this.mapper.transform(a,Ql(n,{callbacks:t?.getChild()})),s=o.next();for await(let e of i){if(typeof e!=`object`||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!r.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await s).value;for await(let e of o)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=Zl(t),i=new ou({generator:this.transform(n(),r),config:r});return await i.setup,ru.fromAsyncGenerator(i)}},Ix=class extends Cx{static lc_name(){return`RunnablePick`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;keys;constructor(e){(typeof e==`string`||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys==`string`)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let e=await this._pick(t);e!==void 0&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=Zl(t),i=new ou({generator:this.transform(n(),r),config:r});return await i.setup,ru.fromAsyncGenerator(i)}},Lx=class extends wx{name;description;schema;constructor(e){let t=Dx.from([jx.from(async e=>{let t;if(g(e))try{t=await o_(this.schema,e.args)}catch{throw new v(`Received tool input did not match expected schema`,JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return`RunnableToolLike`}};function Rx(e,t){let n=t.name??e.getName(),r=t.description??l_(t.schema);return d_(t.schema)?new Lx({name:n,description:r,schema:xy({input:yy()}).transform(e=>e.input),bound:e}):new Lx({name:n,description:r,schema:t.schema,bound:e})}var zx=class extends Cx{static lc_name(){return`RunnablePassthrough`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let n=Zl(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=Zl(t),r,i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,i)if(r===void 0)r=t;else try{r=au(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new Fx(new Ox({steps:e}))}},Bx=class extends Cx{static lc_name(){return`RouterRunnable`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.invoke(r,Zl(t))}async batch(e,t,n){let r=e.map(e=>e.key),i=e.map(e=>e.input);if(r.find(e=>this.runnables[e]===void 0)!==void 0)throw Error(`One or more keys do not have a corresponding runnable.`);let a=r.map(e=>this.runnables[e]),o=this._getOptionsList(t??{},e.length),s=o[0]?.maxConcurrency??n?.maxConcurrency,c=s&&s>0?s:e.length,l=[];for(let e=0;e<i.length;e+=c){let t=i.slice(e,e+c).map((e,t)=>a[t].invoke(e,o[t])),n=await Promise.all(t);l.push(n)}return l.flat()}async stream(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.stream(r,t)}},Vx=class extends Cx{static lc_name(){return`RunnableBranch`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw Error(`RunnableBranch requires at least one branch`);let t=e.slice(0,-1).map(([e,t])=>[Px(e),Px(t)]),n=Px(e[e.length-1]);return new this({branches:t,default:n})}async _invoke(e,t,n){let r;for(let i=0;i<this.branches.length;i+=1){let[a,o]=this.branches[i];if(await a.invoke(e,Ql(t,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await o.invoke(e,Ql(t,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||=await this.default.invoke(e,Ql(t,{callbacks:n?.getChild(`branch:default`)})),r}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let n=await(await Yl(t))?.handleChainStart(this.toJSON(),Sx(e,`input`),t?.runId,void 0,void 0,void 0,t?.runName),r,i=!0,a;try{for(let o=0;o<this.branches.length;o+=1){let[s,c]=this.branches[o];if(await s.invoke(e,Ql(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await c.stream(e,Ql(t,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=au(r,e)}catch{r=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,Ql(t,{callbacks:n?.getChild(`branch:default`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=au(r,e)}catch{r=void 0,i=!1}}}catch(e){throw await n?.handleChainError(e),e}await n?.handleChainEnd(r??{})}},Hx=(e,t)=>{let n=[...new Set(t?.map(e=>{if(typeof e==`string`)return e;let t=new e({});if(!(`getType`in t)||typeof t.getType!=`function`)throw Error(`Invalid type provided.`);return t.getType()}))],r=e.getType();return n.some(e=>e===r)};function Ux(e,t){return Array.isArray(e)?Wx(e,t):jx.from(t=>Wx(t,e))}function Wx(e,t={}){let{includeNames:n,excludeNames:r,includeTypes:i,excludeTypes:a,includeIds:o,excludeIds:s}=t,c=[];for(let t of e)r&&t.name&&r.includes(t.name)||a&&Hx(t,a)||s&&t.id&&s.includes(t.id)||(i||o||n?(n&&t.name&&n.some(e=>e===t.name)||i&&Hx(t,i)||o&&t.id&&o.some(e=>e===t.id))&&c.push(t):c.push(t));return c}function Gx(e){return Array.isArray(e)?Kx(e):jx.from(Kx)}function Kx(e){if(!e.length)return[];let t=[];for(let n of e){let e=n,r=t.pop();if(!r)t.push(e);else if(e.getType()===`tool`||e.getType()!==r.getType())t.push(r,e);else{let n=Nn(r),i=Nn(e),a=n.concat(i);typeof n.content==`string`&&typeof i.content==`string`&&(a.content=`${n.content}\n${i.content}`),t.push($x(a))}}return t}function qx(e,t){if(Array.isArray(e)){let n=e;if(!t)throw Error(`Options parameter is required when providing messages.`);return Jx(n,t)}else{let t=e;return jx.from(e=>Jx(e,t)).withConfig({runName:`trim_messages`})}}async function Jx(e,t){let{maxTokens:n,tokenCounter:r,strategy:i=`last`,allowPartial:a=!1,endOn:o,startOn:s,includeSystem:c=!1,textSplitter:l}=t;if(s&&i===`first`)throw Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&i===`first`)throw Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;u=`getNumTokens`in r?async e=>(await Promise.all(e.map(e=>r.getNumTokens(e.content)))).reduce((e,t)=>e+t,0):async e=>r(e);let d=eS;if(l&&(d=`splitText`in l?l.splitText:async e=>l(e)),i===`first`)return Yx(e,{maxTokens:n,tokenCounter:u,textSplitter:d,partialStrategy:a?`first`:void 0,endOn:o});if(i===`last`)return Xx(e,{maxTokens:n,tokenCounter:u,textSplitter:d,allowPartial:a,includeSystem:c,startOn:s,endOn:o});throw Error(`Unrecognized strategy: '${i}'. Must be one of 'first' or 'last'.`)}async function Yx(e,t){let{maxTokens:n,tokenCounter:r,textSplitter:i,partialStrategy:a,endOn:o}=t,s=[...e],c=0;for(let e=0;e<s.length;e+=1)if(await r(e>0?s.slice(0,-e):s)<=n){c=s.length-e;break}if(c<s.length&&a){let e=!1;if(Array.isArray(s[c].content)){let t=s[c];if(typeof t.content==`string`)throw Error(`Expected content to be an array.`);let i=t.content.length,o=a===`last`?[...t.content].reverse():t.content;for(let l=1;l<=i;l+=1){let i=a===`first`?o.slice(0,l):o.slice(-l),u=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`type`&&!e.startsWith(`lc_`))),d=Qx(t.getType(),{...u,content:i}),f=[...s.slice(0,c),d];if(await r(f)<=n)s=f,c+=1,e=!0;else break}e&&a===`last`&&(t.content=[...o].reverse())}if(!e){let e=s[c],t;if(Array.isArray(e.content)&&e.content.some(e=>typeof e==`string`||e.type===`text`)?t=e.content.find(e=>e.type===`text`&&e.text)?.text:typeof e.content==`string`&&(t=e.content),t){let o=await i(t),l=o.length;a===`last`&&o.reverse();for(let t=0;t<l-1;t+=1)if(o.pop(),e.content=o.join(``),await r([...s.slice(0,c),e])<=n){a===`last`&&(e.content=[...o].reverse().join(``)),s=[...s.slice(0,c),e],c+=1;break}}}}if(o){let e=Array.isArray(o)?o:[o];for(;c>0&&!Hx(s[c-1],e);)--c}return s.slice(0,c)}async function Xx(e,t){let{allowPartial:n=!1,includeSystem:r=!1,endOn:i,startOn:a,...o}=t,s=e.map(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`type`&&!e.startsWith(`lc_`)));return Qx(e.getType(),t,vt(e))});if(i){let e=Array.isArray(i)?i:[i];for(;s.length>0&&!Hx(s[s.length-1],e);)s=s.slice(0,-1)}let c=r&&s[0]?.getType()===`system`,l=c?s.slice(0,1).concat(s.slice(1).reverse()):s.reverse();return l=await Yx(l,{...o,partialStrategy:n?`last`:void 0,endOn:a}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}var Zx={human:{message:fn,messageChunk:pn},ai:{message:$t,messageChunk:nn},system:{message:_n,messageChunk:vn},developer:{message:_n,messageChunk:vn},tool:{message:xt,messageChunk:St},function:{message:cn,messageChunk:ln},generic:{message:rn,messageChunk:an},remove:{message:gn,messageChunk:gn}};function Qx(e,t,n){let r,i;switch(e){case`human`:n?r=new pn(t):i=new fn(t);break;case`ai`:if(n){let e={...t};`tool_calls`in e&&(e={...e,tool_call_chunks:e.tool_calls?.map(e=>({...e,type:`tool_call_chunk`,index:void 0,args:JSON.stringify(e.args)}))}),r=new nn(e)}else i=new $t(t);break;case`system`:n?r=new vn(t):i=new _n(t);break;case`developer`:n?r=new vn({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}}):i=new _n({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:`developer`}});break;case`tool`:if(`tool_call_id`in t)n?r=new St(t):i=new xt(t);else throw Error(`Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.`);break;case`function`:if(n)r=new ln(t);else{if(!t.name)throw Error(`FunctionMessage must have a 'name' field`);i=new cn(t)}break;case`generic`:if(`role`in t)n?r=new an(t):i=new rn(t);else throw Error(`Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.`);break;default:throw Error(`Unrecognized message type ${e}`)}if(n&&r)return r;if(i)return i;throw Error(`Unrecognized message type ${e}`)}function $x(e){let t=e.getType(),n,r=Object.fromEntries(Object.entries(e).filter(([e])=>![`type`,`tool_call_chunks`].includes(e)&&!e.startsWith(`lc_`)));if(t in Zx&&(n=Qx(t,r)),!n)throw Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(Zx)}`);return n}function eS(e){let t=e.split(`
|
|
100
|
-
`);return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}var tS=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],nS=[`image`,`video`,`audio`,`text-plain`,`file`],rS=[`text`,`reasoning`,...tS,...nS],iS=s({AIMessage:()=>$t,AIMessageChunk:()=>nn,BaseMessage:()=>rt,BaseMessageChunk:()=>ht,ChatMessage:()=>rn,ChatMessageChunk:()=>an,DEFAULT_MERGE_IGNORE_KEYS:()=>at,FunctionMessage:()=>cn,FunctionMessageChunk:()=>ln,HumanMessage:()=>fn,HumanMessageChunk:()=>pn,KNOWN_BLOCK_TYPES:()=>rS,RemoveMessage:()=>gn,SystemMessage:()=>_n,SystemMessageChunk:()=>vn,ToolMessage:()=>xt,ToolMessageChunk:()=>St,_isMessageFieldWithRole:()=>gt,_mergeDicts:()=>ot,_mergeLists:()=>pt,_mergeObj:()=>mt,_mergeStatus:()=>tt,coerceMessageLikeToMessage:()=>En,collapseToolCallChunks:()=>Pn,convertToChunk:()=>Nn,convertToOpenAIImageBlock:()=>we,convertToProviderContentBlock:()=>De,defaultTextSplitter:()=>eS,defaultToolCallParser:()=>Ct,filterMessages:()=>Ux,getBufferString:()=>On,iife:()=>Sn,isAIMessage:()=>en,isAIMessageChunk:()=>tn,isBase64ContentBlock:()=>xe,isBaseMessage:()=>_t,isBaseMessageChunk:()=>vt,isChatMessage:()=>on,isChatMessageChunk:()=>sn,isDataContentBlock:()=>ye,isDirectToolOutput:()=>bt,isFunctionMessage:()=>un,isFunctionMessageChunk:()=>dn,isHumanMessage:()=>mn,isHumanMessageChunk:()=>hn,isIDContentBlock:()=>Ce,isMessage:()=>Ye,isOpenAIToolCallArray:()=>it,isPlainTextContentBlock:()=>Se,isSystemMessage:()=>yn,isSystemMessageChunk:()=>bn,isToolMessage:()=>wt,isToolMessageChunk:()=>Tt,isURLContentBlock:()=>be,mapChatMessagesToStoredMessages:()=>Mn,mapStoredMessageToChatMessage:()=>An,mapStoredMessagesToChatMessages:()=>jn,mergeContent:()=>et,mergeMessageRuns:()=>Gx,mergeResponseMetadata:()=>Jt,mergeUsageMetadata:()=>Qt,parseBase64DataUrl:()=>Ee,parseMimeType:()=>Te,trimMessages:()=>qx}),aS=class extends wx{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=jx.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=zx.assign({[n]:t}).withConfig({runName:`insertHistory`}));let r=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:`RunnableWithMessageHistory`}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e==`object`&&!Array.isArray(e)&&!_t(e)){let n;n=this.inputMessagesKey?this.inputMessagesKey:Object.keys(e).length===1?Object.keys(e)[0]:`input`,t=Array.isArray(e[n])&&Array.isArray(e[n][0])?e[n][0]:e[n]}else t=e;if(typeof t==`string`)return[new fn(t)];if(Array.isArray(t))return t;if(_t(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!_t(e)&&typeof e!=`string`){let n;n=this.outputMessagesKey===void 0?Object.keys(e).length===1?Object.keys(e)[0]:`output`:this.outputMessagesKey,t=e.generations===void 0?e[n]:e.generations[0][0].message}else t=e;if(typeof t==`string`)return[new $t(t)];if(Array.isArray(t))return t;if(_t(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let n=t.configurable?.messageHistory,r;r=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){let e=await n.getMessages();i=i.slice(e.length)}let a=e.outputs;if(!a)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(a);await n.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let e={[this.inputMessagesKey??`input`]:`foo`};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify({configurable:{sessionId:`123`}})})`)}let{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},oS=s({RouterRunnable:()=>Bx,Runnable:()=>Cx,RunnableAssign:()=>Fx,RunnableBinding:()=>wx,RunnableBranch:()=>Vx,RunnableEach:()=>Tx,RunnableLambda:()=>jx,RunnableMap:()=>Ox,RunnableParallel:()=>Mx,RunnablePassthrough:()=>zx,RunnablePick:()=>Ix,RunnableRetry:()=>Ex,RunnableSequence:()=>Dx,RunnableToolLike:()=>Lx,RunnableWithFallbacks:()=>Nx,RunnableWithMessageHistory:()=>aS,_coerceToRunnable:()=>Px,ensureConfig:()=>Zl,getCallbackManagerForConfig:()=>Yl,mergeConfigs:()=>Xl,patchConfig:()=>Ql,pickRunnableConfigKeys:()=>$l,raceWithSignal:()=>eu});function sS(e,t){if(e!=null){if(typeof e!=`number`||Number.isNaN(e)||e<=0)throw Error(`${t} must be greater than 0`);return e}}function cS(e){if(e==null)return;let t=typeof e==`number`?{runTimeout:e}:e,n=t.refreshOn??`auto`;if(n!==`auto`&&n!==`heartbeat`)throw Error(`refreshOn must be "auto" or "heartbeat"`);let r=sS(t.runTimeout,`runTimeout`),i=sS(t.idleTimeout,`idleTimeout`);if(!(r===void 0&&i===void 0))return{runTimeout:r,idleTimeout:i,refreshOn:n}}var lS=`__start__`,uS=`__end__`,dS=`__input__`,fS=`__error__`,pS=`__error_source_node__`,mS=`__pregel_ns_writes`;function hS(){let e=typeof process<`u`?{}.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT:void 0;if(e!==void 0&&e!==``){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return 5e3}var gS=`__pregel_send`,_S=`__pregel_call`,vS=`__pregel_read`,yS=`__pregel_checkpointer`,bS=`__pregel_resuming`,xS=`__pregel_task_id`,SS=`__pregel_stream`,CS=`__pregel_resume_value`,wS=`__pregel_resume_map`,TS=`__pregel_scratchpad`,ES=`__pregel_previous`,DS=`__pregel_durability`,OS=`checkpoint_id`,kS=`checkpoint_ns`,AS=`__pregel_node_finished`,jS=`__pregel_node_error`,MS=`checkpoint_map`,NS=`__pregel_replay_state`,PS=`__pregel_abort_signals`,FS=`__interrupt__`,IS=`__resume__`,LS=`__no_writes__`,RS=`__return__`,zS=`__previous__`,BS=`langsmith:hidden`,VS=`__self__`,HS=`__pregel_tasks`,US=`__pregel_push`,WS=`__pregel_pull`,GS=`00000000-0000-0000-0000-000000000000`,KS=[BS,dS,FS,IS,fS,pS,LS,gS,vS,yS,DS,SS,bS,xS,_S,CS,TS,ES,MS,kS,OS,NS],qS=Symbol.for(`langgraph.command`),JS=class{[qS];constructor(e){this[qS]=e}};function YS(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var XS=class{lg_name=`Send`;node;args;timeout;constructor(e,t,n){this.node=e,this.args=aC(t),this.timeout=cS(n?.timeout)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args,timeout:this.timeout}}};function ZS(e){return e instanceof XS}var QS=`__overwrite__`;function $S(e){if(typeof e==`object`&&e){if(`__overwrite__`in e)return[!0,e[QS]];let t=e;if(t.type===`__overwrite__`&&`value`in t)return[!0,t.value]}return[!1,void 0]}function eC(e){return $S(e)[0]}function tC(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[FS])}var nC=class extends JS{lg_name=`Command`;lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT=`__parent__`;constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?aC(e.goto):[aC(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update==`object`&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`)?this.update:[[`__root__`,this.update]]}toJSON(){let e;return e=typeof this.goto==`string`?this.goto:ZS(this.goto)?this.goto.toJSON():this.goto?.map(e=>typeof e==`string`?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function rC(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function iC(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function aC(e,t=new Map){if(typeof e==`object`&&e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach((e,r)=>{n[r]=aC(e,t)});else if(e instanceof nC||e instanceof XS||!iC(e))n=e,t.set(e,n);else if(rC(e))n=new nC(e),t.set(e,n);else if(YS(e))n=new XS(e.node,e.args,e.timeout===void 0?void 0:{timeout:e.timeout}),t.set(e,n);else if(`lc_serializable`in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=aC(i,t)}return n}return e}var oC=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},sC=class extends oC{get is_bubble_up(){return!0}},cC=class extends oC{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},lC=class extends oC{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},uC=class extends sC{reason;constructor(e=`shutdown`,t){super(`Graph drained: ${e}`,t),this.name=`GraphDrained`,this.reason=e}static get unminifiable_name(){return`GraphDrained`}};function dC(e){return e!==void 0&&e.name===uC.unminifiable_name}var fC=class extends sC{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},pC=class extends fC{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},mC=class{node;error;constructor(e,t){this.node=e,this.error=t}static get unminifiable_name(){return`NodeError`}},hC=class extends sC{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function gC(e){return e!==void 0&&e.name===hC.unminifiable_name}function _C(e){return e!==void 0&&e.is_bubble_up===!0}function vC(e){return e!==void 0&&[fC.unminifiable_name,pC.unminifiable_name].includes(e.name)}var yC=class extends oC{node;kind;timeout;elapsed;runTimeout;idleTimeout;constructor(e,t){let{node:n,elapsed:r,kind:i,runTimeout:a,idleTimeout:o}=e,s,c;if(i===`idle`){if(o===void 0)throw Error(`idleTimeout is required when kind='idle'`);c=o,s=`Node "${n}" exceeded its idle timeout of ${o}ms without making progress (elapsed: ${r}ms).`}else{if(a===void 0)throw Error(`runTimeout is required when kind='run'`);c=a,s=`Node "${n}" exceeded its run timeout of ${a}ms (elapsed: ${r}ms).`}super(s,t),this.name=`NodeTimeoutError`,this.node=n,this.kind=i,this.timeout=c,this.elapsed=r,this.runTimeout=a,this.idleTimeout=o}static get unminifiable_name(){return`NodeTimeoutError`}},bC=class extends oC{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},xC=class extends oC{constructor(e,t){let n=Error.stackTraceLimit;Error.stackTraceLimit=0,super(e,t),Error.stackTraceLimit=n,this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},SC=class extends oC{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},CC=class extends oC{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},wC=class extends oC{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}},TC=0,EC=0;function DC(e){let t=Date.now();return t<=TC?(EC+=1,EC>=1e4&&(EC=0,t=TC+1)):EC=0,TC=t,xr({clockseq:e,msecs:t,nsecs:EC})}function OC(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return br(e,new Uint8Array(n))}var kC=`__error__`,AC=`__scheduled__`,jC=`__interrupt__`,MC=`__resume__`,NC=class{lg_name=`DeltaSnapshot`;value;constructor(e){this.value=e}};function PC(e){return typeof e==`object`&&!!e&&e.lg_name===`DeltaSnapshot`}var FC=`[...]`,IC=`[Circular]`,LC=[],RC=[];function zC(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function BC(e,t,n,r){r===void 0&&(r=zC()),HC(e,``,0,[],void 0,0,r);var i;try{i=RC.length===0?JSON.stringify(e,t,n):JSON.stringify(e,UC(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;LC.length!==0;){var a=LC.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function VC(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,LC.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),LC.push([r,n,t,i])):RC.push([t,n,e])}function HC(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){VC(IC,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){VC(FC,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){VC(FC,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)HC(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];HC(e[l],l,s,r,e,a,o)}}r.pop()}}function UC(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(RC.length>0)for(var r=0;r<RC.length;r++){var i=RC[r];if(i[1]===t&&i[0]===n){n=i[2],RC.splice(r,1);break}}return e.call(this,t,n)}}var WC=[],GC=s({}),KC=s({}),R=`0123456789abcdef`.split(``),qC=[-2147483648,8388608,32768,128],JC=[24,16,8,0],YC=[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],XC=[];function ZC(e,t){t?(XC[0]=XC[16]=XC[1]=XC[2]=XC[3]=XC[4]=XC[5]=XC[6]=XC[7]=XC[8]=XC[9]=XC[10]=XC[11]=XC[12]=XC[13]=XC[14]=XC[15]=0,this.blocks=XC):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}ZC.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!==`string`){if(n===`object`){if(e===null)throw Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw Error(ERROR)}else throw Error(ERROR);t=!0}for(var r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),t)for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<JC[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<JC[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<JC[a++&3],s[a>>>2]|=(128|r&63)<<JC[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<JC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<JC[a++&3],s[a>>>2]|=(128|r&63)<<JC[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<JC[a++&3],s[a>>>2]|=(128|r>>>12&63)<<JC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<JC[a++&3],s[a>>>2]|=(128|r&63)<<JC[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this}},ZC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=qC[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},ZC.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+YC[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=o&s^~o&i,p=a+d+h+YC[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=a&o^~a&s,p=i+d+h+YC[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+YC[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},ZC.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=R[e>>>28&15]+R[e>>>24&15]+R[e>>>20&15]+R[e>>>16&15]+R[e>>>12&15]+R[e>>>8&15]+R[e>>>4&15]+R[e&15]+R[t>>>28&15]+R[t>>>24&15]+R[t>>>20&15]+R[t>>>16&15]+R[t>>>12&15]+R[t>>>8&15]+R[t>>>4&15]+R[t&15]+R[n>>>28&15]+R[n>>>24&15]+R[n>>>20&15]+R[n>>>16&15]+R[n>>>12&15]+R[n>>>8&15]+R[n>>>4&15]+R[n&15]+R[r>>>28&15]+R[r>>>24&15]+R[r>>>20&15]+R[r>>>16&15]+R[r>>>12&15]+R[r>>>8&15]+R[r>>>4&15]+R[r&15]+R[i>>>28&15]+R[i>>>24&15]+R[i>>>20&15]+R[i>>>16&15]+R[i>>>12&15]+R[i>>>8&15]+R[i>>>4&15]+R[i&15]+R[a>>>28&15]+R[a>>>24&15]+R[a>>>20&15]+R[a>>>16&15]+R[a>>>12&15]+R[a>>>8&15]+R[a>>>4&15]+R[a&15]+R[o>>>28&15]+R[o>>>24&15]+R[o>>>20&15]+R[o>>>16&15]+R[o>>>12&15]+R[o>>>8&15]+R[o>>>4&15]+R[o&15];return this.is224||(c+=R[s>>>28&15]+R[s>>>24&15]+R[s>>>20&15]+R[s>>>16&15]+R[s>>>12&15]+R[s>>>8&15]+R[s>>>4&15]+R[s&15]),c},ZC.prototype.toString=ZC.prototype.hex,ZC.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},ZC.prototype.array=ZC.prototype.digest,ZC.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var QC=(...e)=>new ZC(!1,!0).update(e.join(``)).hex(),$C=s({sha256:()=>QC}),ew=s({BaseCache:()=>iw,InMemoryCache:()=>ow,defaultHashKeyEncoder:()=>tw,deserializeStoredGeneration:()=>nw,serializeGeneration:()=>rw}),tw=(...e)=>QC(e.join(`_`));function nw(e){return e.message===void 0?{text:e.text}:{text:e.text,message:An(e.message)}}function rw(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var iw=class{keyEncoder=tw;makeDefaultKeyEncoder(e){this.keyEncoder=e}},aw=new Map,ow=class e extends iw{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new e(aw)}},sw=s({BaseChatMessageHistory:()=>cw,BaseListChatMessageHistory:()=>lw,InMemoryChatMessageHistory:()=>uw}),cw=class extends ve{async addMessages(e){for(let t of e)await this.addMessage(t)}},lw=class extends ve{addUserMessage(e){return this.addMessage(new fn(e))}addAIMessage(e){return this.addMessage(new $t(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},uw=class extends lw{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},dw=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},fw=class extends Cx{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},pw=class extends fw{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},mw=s({BaseDocumentTransformer:()=>fw,Document:()=>dw,MappingDocumentTransformer:()=>pw}),hw=s({BaseDocumentLoader:()=>gw}),gw=class{},_w=s({LangSmithLoader:()=>vw}),vw=class extends gw{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new bc(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??yw,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function yw(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var bw=s({Embeddings:()=>xw}),xw=class{caller;constructor(e){this.caller=new bd(e??{})}},Sw=class extends ve{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Cw=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},ww=class extends Cw{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function Tw(e){return e._modelType()===`base_llm`}function Ew(e){return e._modelType()===`base_chat_model`}function Dw(e){return e.split(/\n| /).length}var Ow=class e extends Sw{examples=[];examplePrompt;getTextLength=Dw;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Dw}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function kw(e){return Object.keys(e).sort().map(t=>e[t])}var Aw=class e extends Sw{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=kw((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new dw({pageContent:t,metadata:e})])}async selectExamples(e){let t=kw((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>kw(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},jw=s({BaseExampleSelector:()=>Sw,BasePromptSelector:()=>Cw,ConditionalPromptSelector:()=>ww,LengthBasedExampleSelector:()=>Ow,SemanticSimilarityExampleSelector:()=>Aw,isChatModel:()=>Ew,isLLM:()=>Tw}),Mw=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,Nw=class extends ve{lc_namespace=[`langchain`,`recordmanagers`]},Pw=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=QC;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new dw({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return br(this.keyEncoder(e),Mw)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return br(this.keyEncoder(t),Mw)}};function Fw(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function Iw(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function Lw(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var Rw=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function zw(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=Rw(t)?await t.load():t,d=Lw(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=Fw(a??100,u);for(let e of _){let t=Iw(e.map(e=>Pw.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var Bw=s({RecordManager:()=>Nw,UUIDV5_NAMESPACE:()=>Mw,_HashedDocument:()=>Pw,_batch:()=>Fw,_deduplicateInOrder:()=>Iw,_getSourceIdAssigner:()=>Lw,_isBaseDocumentLoader:()=>Rw,index:()=>zw}),Vw=s({BasePromptValue:()=>Hw,ChatPromptValue:()=>Ww,ImagePromptValue:()=>Gw,StringPromptValue:()=>Uw}),Hw=class extends ve{},Uw=class extends Hw{static lc_name(){return`StringPromptValue`}lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new fn(this.value)]}},Ww=class extends Hw{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ChatPromptValue`}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return On(this.messages)}toChatMessages(){return this.messages}},Gw=class extends Hw{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ImagePromptValue`}imageUrl;value;constructor(e){`imageUrl`in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new fn({content:[{type:`image_url`,image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},Kw=n(r((e=>{e.toByteArray=l;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e,t,n){return(t+n)*3/4-n}function l(e){var t,i=s(e),a=i[0],o=i[1],l=new r(c(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,l[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,l[u++]=t>>8&255,l[u++]=t&255),l}}))(),1),qw=Object.defineProperty,Jw=(e,t,n)=>t in e?qw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Yw=(e,t,n)=>(Jw(e,typeof t==`symbol`?t:t+``,n),n);function Xw(e,t){let n=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){let a=e.slice(n[i].start,n[i+1].end),o=t.get(a.join(`,`));o!=null&&(r==null||o<r[0])&&(r=[o,i])}if(r!=null){let e=r[1];n[e]={start:n[e].start,end:n[e+1].end},n.splice(e+1,1)}else break}return n}function Zw(e,t){return e.length===1?[t.get(e.join(`,`))]:Xw(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function Qw(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var $w=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder(`utf-8`);rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let n=e.bpe_ranks.split(`
|
|
100
|
+
`);return Promise.resolve([...t.slice(0,-1).map(e=>`${e}\n`),t[t.length-1]])}var tS=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],nS=[`image`,`video`,`audio`,`text-plain`,`file`],rS=[`text`,`reasoning`,...tS,...nS],iS=s({AIMessage:()=>$t,AIMessageChunk:()=>nn,BaseMessage:()=>rt,BaseMessageChunk:()=>ht,ChatMessage:()=>rn,ChatMessageChunk:()=>an,DEFAULT_MERGE_IGNORE_KEYS:()=>at,FunctionMessage:()=>cn,FunctionMessageChunk:()=>ln,HumanMessage:()=>fn,HumanMessageChunk:()=>pn,KNOWN_BLOCK_TYPES:()=>rS,RemoveMessage:()=>gn,SystemMessage:()=>_n,SystemMessageChunk:()=>vn,ToolMessage:()=>xt,ToolMessageChunk:()=>St,_isMessageFieldWithRole:()=>gt,_mergeDicts:()=>ot,_mergeLists:()=>pt,_mergeObj:()=>mt,_mergeStatus:()=>tt,coerceMessageLikeToMessage:()=>En,collapseToolCallChunks:()=>Pn,convertToChunk:()=>Nn,convertToOpenAIImageBlock:()=>we,convertToProviderContentBlock:()=>De,defaultTextSplitter:()=>eS,defaultToolCallParser:()=>Ct,filterMessages:()=>Ux,getBufferString:()=>On,iife:()=>Sn,isAIMessage:()=>en,isAIMessageChunk:()=>tn,isBase64ContentBlock:()=>xe,isBaseMessage:()=>_t,isBaseMessageChunk:()=>vt,isChatMessage:()=>on,isChatMessageChunk:()=>sn,isDataContentBlock:()=>ye,isDirectToolOutput:()=>bt,isFunctionMessage:()=>un,isFunctionMessageChunk:()=>dn,isHumanMessage:()=>mn,isHumanMessageChunk:()=>hn,isIDContentBlock:()=>Ce,isMessage:()=>Ye,isOpenAIToolCallArray:()=>it,isPlainTextContentBlock:()=>Se,isSystemMessage:()=>yn,isSystemMessageChunk:()=>bn,isToolMessage:()=>wt,isToolMessageChunk:()=>Tt,isURLContentBlock:()=>be,mapChatMessagesToStoredMessages:()=>Mn,mapStoredMessageToChatMessage:()=>An,mapStoredMessagesToChatMessages:()=>jn,mergeContent:()=>et,mergeMessageRuns:()=>Gx,mergeResponseMetadata:()=>Jt,mergeUsageMetadata:()=>Qt,parseBase64DataUrl:()=>Ee,parseMimeType:()=>Te,trimMessages:()=>qx}),aS=class extends wx{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=jx.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=zx.assign({[n]:t}).withConfig({runName:`insertHistory`}));let r=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:`RunnableWithMessageHistory`}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e==`object`&&!Array.isArray(e)&&!_t(e)){let n;n=this.inputMessagesKey?this.inputMessagesKey:Object.keys(e).length===1?Object.keys(e)[0]:`input`,t=Array.isArray(e[n])&&Array.isArray(e[n][0])?e[n][0]:e[n]}else t=e;if(typeof t==`string`)return[new fn(t)];if(Array.isArray(t))return t;if(_t(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!_t(e)&&typeof e!=`string`){let n;n=this.outputMessagesKey===void 0?Object.keys(e).length===1?Object.keys(e)[0]:`output`:this.outputMessagesKey,t=e.generations===void 0?e[n]:e.generations[0][0].message}else t=e;if(typeof t==`string`)return[new $t(t)];if(Array.isArray(t))return t;if(_t(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let n=t.configurable?.messageHistory,r;r=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){let e=await n.getMessages();i=i.slice(e.length)}let a=e.outputs;if(!a)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(a);await n.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let e={[this.inputMessagesKey??`input`]:`foo`};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify({configurable:{sessionId:`123`}})})`)}let{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},oS=s({RouterRunnable:()=>Bx,Runnable:()=>Cx,RunnableAssign:()=>Fx,RunnableBinding:()=>wx,RunnableBranch:()=>Vx,RunnableEach:()=>Tx,RunnableLambda:()=>jx,RunnableMap:()=>Ox,RunnableParallel:()=>Mx,RunnablePassthrough:()=>zx,RunnablePick:()=>Ix,RunnableRetry:()=>Ex,RunnableSequence:()=>Dx,RunnableToolLike:()=>Lx,RunnableWithFallbacks:()=>Nx,RunnableWithMessageHistory:()=>aS,_coerceToRunnable:()=>Px,ensureConfig:()=>Zl,getCallbackManagerForConfig:()=>Yl,mergeConfigs:()=>Xl,patchConfig:()=>Ql,pickRunnableConfigKeys:()=>$l,raceWithSignal:()=>eu});function sS(e,t){if(e!=null){if(typeof e!=`number`||Number.isNaN(e)||e<=0)throw Error(`${t} must be greater than 0`);return e}}function cS(e){if(e==null)return;let t=typeof e==`number`?{runTimeout:e}:e,n=t.refreshOn??`auto`;if(n!==`auto`&&n!==`heartbeat`)throw Error(`refreshOn must be "auto" or "heartbeat"`);let r=sS(t.runTimeout,`runTimeout`),i=sS(t.idleTimeout,`idleTimeout`);if(!(r===void 0&&i===void 0))return{runTimeout:r,idleTimeout:i,refreshOn:n}}var lS=`__start__`,uS=`__end__`,dS=`__input__`,fS=`__error__`,pS=`__error_source_node__`,mS=`__pregel_ns_writes`;function hS(){let e=typeof process<`u`?{}.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT:void 0;if(e!==void 0&&e!==``){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return 5e3}var gS=`__pregel_send`,_S=`__pregel_call`,vS=`__pregel_read`,yS=`__pregel_checkpointer`,bS=`__pregel_resuming`,xS=`__pregel_task_id`,SS=`__pregel_stream`,CS=`__pregel_resume_value`,wS=`__pregel_resume_map`,TS=`__pregel_scratchpad`,ES=`__pregel_previous`,DS=`__pregel_durability`,OS=`checkpoint_id`,kS=`checkpoint_ns`,AS=`__pregel_node_finished`,jS=`__pregel_node_error`,MS=`checkpoint_map`,NS=`__pregel_replay_state`,PS=`__pregel_abort_signals`,FS=`__interrupt__`,IS=`__resume__`,LS=`__no_writes__`,RS=`__return__`,zS=`__previous__`,BS=`langsmith:hidden`,VS=`__self__`,HS=`__pregel_tasks`,US=`__pregel_push`,WS=`__pregel_pull`,GS=`00000000-0000-0000-0000-000000000000`,KS=[BS,dS,FS,IS,fS,pS,LS,gS,vS,yS,DS,SS,bS,xS,_S,CS,TS,ES,MS,kS,OS,NS],qS=Symbol.for(`langgraph.command`),JS=class{[qS];constructor(e){this[qS]=e}};function YS(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var XS=class{lg_name=`Send`;node;args;timeout;constructor(e,t,n){this.node=e,this.args=aC(t),this.timeout=cS(n?.timeout)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args,timeout:this.timeout}}};function ZS(e){return e instanceof XS}var QS=`__overwrite__`;function $S(e){if(typeof e==`object`&&e){if(`__overwrite__`in e)return[!0,e[QS]];let t=e;if(t.type===`__overwrite__`&&`value`in t)return[!0,t.value]}return[!1,void 0]}function eC(e){return $S(e)[0]}function tC(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[FS])}var nC=class extends JS{lg_name=`Command`;lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT=`__parent__`;constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?aC(e.goto):[aC(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update==`object`&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`)?this.update:[[`__root__`,this.update]]}toJSON(){let e;return e=typeof this.goto==`string`?this.goto:ZS(this.goto)?this.goto.toJSON():this.goto?.map(e=>typeof e==`string`?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function rC(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function iC(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function aC(e,t=new Map){if(typeof e==`object`&&e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach((e,r)=>{n[r]=aC(e,t)});else if(e instanceof nC||e instanceof XS||!iC(e))n=e,t.set(e,n);else if(rC(e))n=new nC(e),t.set(e,n);else if(YS(e))n=new XS(e.node,e.args,e.timeout===void 0?void 0:{timeout:e.timeout}),t.set(e,n);else if(`lc_serializable`in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=aC(i,t)}return n}return e}var oC=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},sC=class extends oC{get is_bubble_up(){return!0}},cC=class extends oC{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},lC=class extends oC{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},uC=class extends sC{reason;constructor(e=`shutdown`,t){super(`Graph drained: ${e}`,t),this.name=`GraphDrained`,this.reason=e}static get unminifiable_name(){return`GraphDrained`}};function dC(e){return e!==void 0&&e.name===uC.unminifiable_name}var fC=class extends sC{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},pC=class extends fC{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},mC=class{node;error;constructor(e,t){this.node=e,this.error=t}static get unminifiable_name(){return`NodeError`}},hC=class extends sC{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function gC(e){return e!==void 0&&e.name===hC.unminifiable_name}function _C(e){return e!==void 0&&e.is_bubble_up===!0}function vC(e){return e!==void 0&&[fC.unminifiable_name,pC.unminifiable_name].includes(e.name)}var yC=class extends oC{node;kind;timeout;elapsed;runTimeout;idleTimeout;constructor(e,t){let{node:n,elapsed:r,kind:i,runTimeout:a,idleTimeout:o}=e,s,c;if(i===`idle`){if(o===void 0)throw Error(`idleTimeout is required when kind='idle'`);c=o,s=`Node "${n}" exceeded its idle timeout of ${o}ms without making progress (elapsed: ${r}ms).`}else{if(a===void 0)throw Error(`runTimeout is required when kind='run'`);c=a,s=`Node "${n}" exceeded its run timeout of ${a}ms (elapsed: ${r}ms).`}super(s,t),this.name=`NodeTimeoutError`,this.node=n,this.kind=i,this.timeout=c,this.elapsed=r,this.runTimeout=a,this.idleTimeout=o}static get unminifiable_name(){return`NodeTimeoutError`}},bC=class extends oC{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},xC=class extends oC{constructor(e,t){let n=Error.stackTraceLimit;Error.stackTraceLimit=0,super(e,t),Error.stackTraceLimit=n,this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},SC=class extends oC{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},CC=class extends oC{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},wC=class extends oC{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}},TC=0,EC=0;function DC(e){let t=Date.now();return t<=TC?(EC+=1,EC>=1e4&&(EC=0,t=TC+1)):EC=0,TC=t,xr({clockseq:e,msecs:t,nsecs:EC})}function OC(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return br(e,new Uint8Array(n))}var kC=`__error__`,AC=`__scheduled__`,jC=`__interrupt__`,MC=`__resume__`,NC=class{lg_name=`DeltaSnapshot`;value;constructor(e){this.value=e}};function PC(e){return typeof e==`object`&&!!e&&e.lg_name===`DeltaSnapshot`}var FC=`[...]`,IC=`[Circular]`,LC=[],RC=[];function zC(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function BC(e,t,n,r){r===void 0&&(r=zC()),HC(e,``,0,[],void 0,0,r);var i;try{i=RC.length===0?JSON.stringify(e,t,n):JSON.stringify(e,UC(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;LC.length!==0;){var a=LC.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function VC(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,LC.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),LC.push([r,n,t,i])):RC.push([t,n,e])}function HC(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){VC(IC,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){VC(FC,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){VC(FC,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)HC(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];HC(e[l],l,s,r,e,a,o)}}r.pop()}}function UC(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(RC.length>0)for(var r=0;r<RC.length;r++){var i=RC[r];if(i[1]===t&&i[0]===n){n=i[2],RC.splice(r,1);break}}return e.call(this,t,n)}}var WC=[],GC=s({}),KC=s({}),R=`0123456789abcdef`.split(``),qC=[-2147483648,8388608,32768,128],JC=[24,16,8,0],YC=[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],XC=[];function ZC(e,t){t?(XC[0]=XC[16]=XC[1]=XC[2]=XC[3]=XC[4]=XC[5]=XC[6]=XC[7]=XC[8]=XC[9]=XC[10]=XC[11]=XC[12]=XC[13]=XC[14]=XC[15]=0,this.blocks=XC):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}ZC.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!==`string`){if(n===`object`){if(e===null)throw Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw Error(ERROR)}else throw Error(ERROR);t=!0}for(var r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),t)for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<JC[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<JC[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<JC[a++&3],s[a>>>2]|=(128|r&63)<<JC[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<JC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<JC[a++&3],s[a>>>2]|=(128|r&63)<<JC[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<JC[a++&3],s[a>>>2]|=(128|r>>>12&63)<<JC[a++&3],s[a>>>2]|=(128|r>>>6&63)<<JC[a++&3],s[a>>>2]|=(128|r&63)<<JC[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this}},ZC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=qC[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},ZC.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+YC[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=o&s^~o&i,p=a+d+h+YC[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=a&o^~a&s,p=i+d+h+YC[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+YC[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},ZC.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=R[e>>>28&15]+R[e>>>24&15]+R[e>>>20&15]+R[e>>>16&15]+R[e>>>12&15]+R[e>>>8&15]+R[e>>>4&15]+R[e&15]+R[t>>>28&15]+R[t>>>24&15]+R[t>>>20&15]+R[t>>>16&15]+R[t>>>12&15]+R[t>>>8&15]+R[t>>>4&15]+R[t&15]+R[n>>>28&15]+R[n>>>24&15]+R[n>>>20&15]+R[n>>>16&15]+R[n>>>12&15]+R[n>>>8&15]+R[n>>>4&15]+R[n&15]+R[r>>>28&15]+R[r>>>24&15]+R[r>>>20&15]+R[r>>>16&15]+R[r>>>12&15]+R[r>>>8&15]+R[r>>>4&15]+R[r&15]+R[i>>>28&15]+R[i>>>24&15]+R[i>>>20&15]+R[i>>>16&15]+R[i>>>12&15]+R[i>>>8&15]+R[i>>>4&15]+R[i&15]+R[a>>>28&15]+R[a>>>24&15]+R[a>>>20&15]+R[a>>>16&15]+R[a>>>12&15]+R[a>>>8&15]+R[a>>>4&15]+R[a&15]+R[o>>>28&15]+R[o>>>24&15]+R[o>>>20&15]+R[o>>>16&15]+R[o>>>12&15]+R[o>>>8&15]+R[o>>>4&15]+R[o&15];return this.is224||(c+=R[s>>>28&15]+R[s>>>24&15]+R[s>>>20&15]+R[s>>>16&15]+R[s>>>12&15]+R[s>>>8&15]+R[s>>>4&15]+R[s&15]),c},ZC.prototype.toString=ZC.prototype.hex,ZC.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},ZC.prototype.array=ZC.prototype.digest,ZC.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var QC=(...e)=>new ZC(!1,!0).update(e.join(``)).hex(),$C=s({sha256:()=>QC}),ew=s({BaseCache:()=>iw,InMemoryCache:()=>ow,defaultHashKeyEncoder:()=>tw,deserializeStoredGeneration:()=>nw,serializeGeneration:()=>rw}),tw=(...e)=>QC(e.join(`_`));function nw(e){return e.message===void 0?{text:e.text}:{text:e.text,message:An(e.message)}}function rw(e){let t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var iw=class{keyEncoder=tw;makeDefaultKeyEncoder(e){this.keyEncoder=e}},aw=new Map,ow=class e extends iw{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new e(aw)}},sw=s({BaseChatMessageHistory:()=>cw,BaseListChatMessageHistory:()=>lw,InMemoryChatMessageHistory:()=>uw}),cw=class extends ve{async addMessages(e){for(let t of e)await this.addMessage(t)}},lw=class extends ve{addUserMessage(e){return this.addMessage(new fn(e))}addAIMessage(e){return this.addMessage(new $t(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},uw=class extends lw{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},dw=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},fw=class extends Cx{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},pw=class extends fw{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},mw=s({BaseDocumentTransformer:()=>fw,Document:()=>dw,MappingDocumentTransformer:()=>pw}),hw=s({BaseDocumentLoader:()=>gw}),gw=class{},_w=s({LangSmithLoader:()=>vw}),vw=class extends gw{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new bc(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??yw,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function yw(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var bw=s({Embeddings:()=>xw}),xw=class{caller;constructor(e){this.caller=new bd(e??{})}},Sw=class extends ve{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Cw=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},ww=class extends Cw{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function Tw(e){return e._modelType()===`base_llm`}function Ew(e){return e._modelType()===`base_chat_model`}function Dw(e){return e.split(/\n| /).length}var Ow=class e extends Sw{examples=[];examplePrompt;getTextLength=Dw;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Dw}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function kw(e){return Object.keys(e).sort().map(t=>e[t])}var Aw=class e extends Sw{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=kw((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new dw({pageContent:t,metadata:e})])}async selectExamples(e){let t=kw((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>kw(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},jw=s({BaseExampleSelector:()=>Sw,BasePromptSelector:()=>Cw,ConditionalPromptSelector:()=>ww,LengthBasedExampleSelector:()=>Ow,SemanticSimilarityExampleSelector:()=>Aw,isChatModel:()=>Ew,isLLM:()=>Tw}),Mw=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,Nw=class extends ve{lc_namespace=[`langchain`,`recordmanagers`]},Pw=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=QC;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new dw({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return br(this.keyEncoder(e),Mw)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return br(this.keyEncoder(t),Mw)}};function Fw(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function Iw(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function Lw(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var Rw=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function zw(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=Rw(t)?await t.load():t,d=Lw(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=Fw(a??100,u);for(let e of _){let t=Iw(e.map(e=>Pw.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var Bw=s({RecordManager:()=>Nw,UUIDV5_NAMESPACE:()=>Mw,_HashedDocument:()=>Pw,_batch:()=>Fw,_deduplicateInOrder:()=>Iw,_getSourceIdAssigner:()=>Lw,_isBaseDocumentLoader:()=>Rw,index:()=>zw}),Vw=s({BasePromptValue:()=>Hw,ChatPromptValue:()=>Ww,ImagePromptValue:()=>Gw,StringPromptValue:()=>Uw}),Hw=class extends ve{},Uw=class extends Hw{static lc_name(){return`StringPromptValue`}lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new fn(this.value)]}},Ww=class extends Hw{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ChatPromptValue`}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return On(this.messages)}toChatMessages(){return this.messages}},Gw=class extends Hw{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ImagePromptValue`}imageUrl;value;constructor(e){`imageUrl`in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new fn({content:[{type:`image_url`,image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},Kw=e(t((e=>{e.toByteArray=l;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e,t,n){return(t+n)*3/4-n}function l(e){var t,i=s(e),a=i[0],o=i[1],l=new r(c(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,l[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,l[u++]=t>>8&255,l[u++]=t&255),l}}))(),1),qw=Object.defineProperty,Jw=(e,t,n)=>t in e?qw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Yw=(e,t,n)=>(Jw(e,typeof t==`symbol`?t:t+``,n),n);function Xw(e,t){let n=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){let a=e.slice(n[i].start,n[i+1].end),o=t.get(a.join(`,`));o!=null&&(r==null||o<r[0])&&(r=[o,i])}if(r!=null){let e=r[1];n[e]={start:n[e].start,end:n[e+1].end},n.splice(e+1,1)}else break}return n}function Zw(e,t){return e.length===1?[t.get(e.join(`,`))]:Xw(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function Qw(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var $w=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder(`utf-8`);rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;let n=e.bpe_ranks.split(`
|
|
101
101
|
`).filter(Boolean).reduce((e,t)=>{let[n,r,...i]=t.split(` `),a=Number.parseInt(r,10);return i.forEach((t,n)=>e[t]=a+n),e},{});for(let[e,t]of Object.entries(n)){let n=Kw.toByteArray(e);this.rankMap.set(n.join(`,`),t),this.textMap.set(t,n)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,n])=>(e[n]=this.textEncoder.encode(t),e),{})}encode(e,t=[],n=`all`){let r=new RegExp(this.patStr,`ug`),i=$w.specialTokenRegex(Object.keys(this.specialTokens)),a=[],o=new Set(t===`all`?Object.keys(this.specialTokens):t),s=new Set(n===`all`?Object.keys(this.specialTokens).filter(e=>!o.has(e)):n);if(s.size>0){let t=$w.specialTokenRegex([...s]),n=e.match(t);if(n!=null)throw Error(`The text contains a special token that is not allowed: ${n[0]}`)}let c=0;for(;;){let t=null,n=c;for(;i.lastIndex=n,t=i.exec(e),!(t==null||o.has(t[0]));)n=t.index+1;let s=t?.index??e.length;for(let t of e.substring(c,s).matchAll(r)){let e=this.textEncoder.encode(t[0]),n=this.rankMap.get(e.join(`,`));if(n!=null){a.push(n);continue}a.push(...Zw(e,this.rankMap))}if(t==null)break;let l=this.specialTokens[t[0]];a.push(l),c=t.index+t[0].length}return a}decode(e){let t=[],n=0;for(let r=0;r<e.length;++r){let i=e[r],a=this.textMap.get(i)??this.inverseSpecialTokens[i];a!=null&&(t.push(a),n+=a.length)}let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return this.textDecoder.decode(r)}},eT=$w;Yw(eT,`specialTokenRegex`,e=>new RegExp(e.map(e=>Qw(e)).join(`|`),`g`));function tT(e){switch(e){case`gpt2`:return`gpt2`;case`code-cushman-001`:case`code-cushman-002`:case`code-davinci-001`:case`code-davinci-002`:case`cushman-codex`:case`davinci-codex`:case`davinci-002`:case`text-davinci-002`:case`text-davinci-003`:return`p50k_base`;case`code-davinci-edit-001`:case`text-davinci-edit-001`:return`p50k_edit`;case`ada`:case`babbage`:case`babbage-002`:case`code-search-ada-code-001`:case`code-search-babbage-code-001`:case`curie`:case`davinci`:case`text-ada-001`:case`text-babbage-001`:case`text-curie-001`:case`text-davinci-001`:case`text-search-ada-doc-001`:case`text-search-babbage-doc-001`:case`text-search-curie-doc-001`:case`text-search-davinci-doc-001`:case`text-similarity-ada-001`:case`text-similarity-babbage-001`:case`text-similarity-curie-001`:case`text-similarity-davinci-001`:return`r50k_base`;case`gpt-3.5-turbo-instruct-0914`:case`gpt-3.5-turbo-instruct`:case`gpt-3.5-turbo-16k-0613`:case`gpt-3.5-turbo-16k`:case`gpt-3.5-turbo-0613`:case`gpt-3.5-turbo-0301`:case`gpt-3.5-turbo`:case`gpt-4-32k-0613`:case`gpt-4-32k-0314`:case`gpt-4-32k`:case`gpt-4-0613`:case`gpt-4-0314`:case`gpt-4`:case`gpt-3.5-turbo-1106`:case`gpt-35-turbo`:case`gpt-4-1106-preview`:case`gpt-4-vision-preview`:case`gpt-3.5-turbo-0125`:case`gpt-4-turbo`:case`gpt-4-turbo-2024-04-09`:case`gpt-4-turbo-preview`:case`gpt-4-0125-preview`:case`text-embedding-ada-002`:case`text-embedding-3-small`:case`text-embedding-3-large`:return`cl100k_base`;case`gpt-4o`:case`gpt-4o-2024-05-13`:case`gpt-4o-2024-08-06`:case`gpt-4o-2024-11-20`:case`gpt-4o-mini-2024-07-18`:case`gpt-4o-mini`:case`gpt-4o-search-preview`:case`gpt-4o-search-preview-2025-03-11`:case`gpt-4o-mini-search-preview`:case`gpt-4o-mini-search-preview-2025-03-11`:case`gpt-4o-audio-preview`:case`gpt-4o-audio-preview-2024-12-17`:case`gpt-4o-audio-preview-2024-10-01`:case`gpt-4o-mini-audio-preview`:case`gpt-4o-mini-audio-preview-2024-12-17`:case`o1`:case`o1-2024-12-17`:case`o1-mini`:case`o1-mini-2024-09-12`:case`o1-preview`:case`o1-preview-2024-09-12`:case`o1-pro`:case`o1-pro-2025-03-19`:case`o3`:case`o3-2025-04-16`:case`o3-mini`:case`o3-mini-2025-01-31`:case`o4-mini`:case`o4-mini-2025-04-16`:case`chatgpt-4o-latest`:case`gpt-4o-realtime`:case`gpt-4o-realtime-preview-2024-10-01`:case`gpt-4o-realtime-preview-2024-12-17`:case`gpt-4o-mini-realtime-preview`:case`gpt-4o-mini-realtime-preview-2024-12-17`:case`gpt-4.1`:case`gpt-4.1-2025-04-14`:case`gpt-4.1-mini`:case`gpt-4.1-mini-2025-04-14`:case`gpt-4.1-nano`:case`gpt-4.1-nano-2025-04-14`:case`gpt-4.5-preview`:case`gpt-4.5-preview-2025-02-27`:case`gpt-5`:case`gpt-5-2025-08-07`:case`gpt-5-nano`:case`gpt-5-nano-2025-08-07`:case`gpt-5-mini`:case`gpt-5-mini-2025-08-07`:case`gpt-5-chat-latest`:return`o200k_base`;default:throw Error(`Unknown model`)}}var nT=s({encodingForModel:()=>oT,getEncoding:()=>aT}),rT={},iT=new bd({});async function aT(e){return e in rT||(rT[e]=iT.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new eT(e)).catch(t=>{throw delete rT[e],t})),await rT[e]}async function oT(e){return aT(tT(e))}var sT=s({BaseLangChain:()=>mT,BaseLanguageModel:()=>hT,calculateMaxTokens:()=>fT,getEmbeddingContextSize:()=>lT,getModelContextSize:()=>uT,getModelNameForTiktoken:()=>cT,isOpenAITool:()=>dT}),cT=e=>e.startsWith(`gpt-5`)?`gpt-5`:e.startsWith(`gpt-3.5-turbo-16k`)?`gpt-3.5-turbo-16k`:e.startsWith(`gpt-3.5-turbo-`)?`gpt-3.5-turbo`:e.startsWith(`gpt-4-32k`)?`gpt-4-32k`:e.startsWith(`gpt-4-`)?`gpt-4`:e.startsWith(`gpt-4o`)?`gpt-4o`:e,lT=e=>{switch(e){case`text-embedding-ada-002`:return 8191;default:return 2046}},uT=e=>{switch(cT(e)){case`gpt-5`:case`gpt-5-turbo`:case`gpt-5-turbo-preview`:return 4e5;case`gpt-4o`:case`gpt-4o-mini`:case`gpt-4o-2024-05-13`:case`gpt-4o-2024-08-06`:return 128e3;case`gpt-4-turbo`:case`gpt-4-turbo-preview`:case`gpt-4-turbo-2024-04-09`:case`gpt-4-0125-preview`:case`gpt-4-1106-preview`:return 128e3;case`gpt-4-32k`:case`gpt-4-32k-0314`:case`gpt-4-32k-0613`:return 32768;case`gpt-4`:case`gpt-4-0314`:case`gpt-4-0613`:return 8192;case`gpt-3.5-turbo-16k`:case`gpt-3.5-turbo-16k-0613`:return 16384;case`gpt-3.5-turbo`:case`gpt-3.5-turbo-0301`:case`gpt-3.5-turbo-0613`:case`gpt-3.5-turbo-1106`:case`gpt-3.5-turbo-0125`:return 4096;case`text-davinci-003`:case`text-davinci-002`:return 4097;case`text-davinci-001`:return 2049;case`text-curie-001`:case`text-babbage-001`:case`text-ada-001`:return 2048;case`code-davinci-002`:case`code-davinci-001`:return 8e3;case`code-cushman-001`:return 2048;case`claude-3-5-sonnet-20241022`:case`claude-3-5-sonnet-20240620`:case`claude-3-opus-20240229`:case`claude-3-sonnet-20240229`:case`claude-3-haiku-20240307`:case`claude-2.1`:return 2e5;case`claude-2.0`:case`claude-instant-1.2`:return 1e5;case`gemini-1.5-pro`:case`gemini-1.5-pro-latest`:case`gemini-1.5-flash`:case`gemini-1.5-flash-latest`:return 1e6;case`gemini-pro`:case`gemini-pro-vision`:return 32768;default:return 4097}};function dT(e){return typeof e!=`object`||!e?!1:!!(`type`in e&&e.type===`function`&&`function`in e&&typeof e.function==`object`&&e.function&&`name`in e.function&&`parameters`in e.function)}var fT=async({prompt:e,modelName:t})=>{let n;try{n=(await oT(cT(t))).encode(e).length}catch{console.warn(`Failed to calculate number of tokens, falling back to approximate count`),n=Math.ceil(e.length/4)}return uT(t)-n},pT=()=>!1,mT=class extends Cx{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??pT(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion(`@langchain/core`,`1.2.1`)}_addVersion(e,t){let n=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof n==`object`&&n?n:{},[e]:t}}}},hT=class extends mT{get callKeys(){return[`stop`,`timeout`,`signal`,`tags`,`metadata`,`callbacks`]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){let{cache:r,...i}=n;super({callbacks:e??t,...i}),typeof r==`object`?this.cache=r:r?this.cache=ow.global():this.cache=void 0,this.caller=new bd(n??{})}_encoding;async getNumTokens(e){let t;t=typeof e==`string`?e:e.map(e=>typeof e==`string`?e:e.type===`text`&&`text`in e?e.text:``).join(``);let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await oT(`modelName`in this?cT(this.modelName):`gpt2`)}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}return n}static _convertInputToPromptValue(e){return typeof e==`string`?new Uw(e):Array.isArray(e)?new Ww(e.map(En)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(`,`)}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw Error(`Use .toJSON() instead`)}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:n,messages:r,response_format:i,...a}=e;return a}},gT=s({applyPatch:()=>Tu,compare:()=>ju}),_T=class extends Cx{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content==`string`?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e==`string`?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:`parser`}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:`parser`})}},vT=class extends _T{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw Error(`_type not implemented`)}},yT=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw Error(`Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true`);d(this,`OUTPUT_PARSING_FAILURE`)}},bT=class extends vT{async*_transform(e){for await(let t of e)typeof t==`string`?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:`parser`})}},xT=class extends bT{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let r of e){if(typeof r!=`string`&&typeof r.content!=`string`)throw Error(`Cannot handle non-string output.`);let e;if(vt(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Uu({message:r,text:r.content})}else if(_t(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Uu({message:Nn(r),text:r.content})}else e=new Hu({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!bb(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},ST=class extends bT{static lc_name(){return`BytesOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`bytes`];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return``}},CT=class extends bT{re;async*_transform(e){let t=``;for await(let n of e)if(typeof n==`string`?t+=n:t+=n.content,this.re){let e=[...t.matchAll(this.re)];if(e.length>1){let n=0;for(let t of e.slice(0,-1))yield[t[1]],n+=(t.index??0)+t[0].length;t=t.slice(n)}}else{let e=await this.parse(t);if(e.length>1){for(let t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(let e of await this.parse(t))yield[e]}},wT=class extends CT{static lc_name(){return`CommaSeparatedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;async parse(e){try{return e.trim().split(`,`).map(e=>e.trim())}catch{throw new yT(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},TT=class extends CT{lc_namespace=[`langchain_core`,`output_parsers`,`list`];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||`,`}async parse(e){try{let t=e.trim().split(this.separator).map(e=>e.trim());if(this.length!==void 0&&t.length!==this.length)throw new yT(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===yT.prototype?t:new yT(`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\`)`}},ET=class extends CT{static lc_name(){return`NumberedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
102
102
|
|
|
103
103
|
1. foo
|
|
@@ -131,7 +131,7 @@ Line: `+e.line+`
|
|
|
131
131
|
Column: `+e.column+`
|
|
132
132
|
Char: `+e.c),t=Error(t),e.error=t,re(e,`onerror`,t),e}function ce(e){return e.sawRoot&&!e.closedRoot&&C(e,`Unclosed root tag`),e.state!==S.BEGIN&&e.state!==S.BEGIN_WHITESPACE&&e.state!==S.TEXT&&se(e,`Unexpected end`),ae(e),e.c=``,e.closed=!0,re(e,`onend`),n.call(e,e.strict,e.opt),e}function C(e,t){if(typeof e!=`object`||!(e instanceof n))throw Error(`bad call to strictFail`);e.strict&&se(e,t)}function le(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,n=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(n.ns=t.ns),e.attribList.length=0,ie(e,`onopentagstart`,n)}function ue(e,t){var n=e.indexOf(`:`)<0?[``,e]:e.split(`:`),r=n[0],i=n[1];return t&&e===`xmlns`&&(r=`xmlns`,i=``),{prefix:r,local:i}}function de(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),e.attribList.indexOf(e.attribName)!==-1||e.tag.attributes.hasOwnProperty(e.attribName)){e.attribName=e.attribValue=``;return}if(e.opt.xmlns){var t=ue(e.attribName,!0),n=t.prefix,r=t.local;if(n===`xmlns`)if(r===`xml`&&e.attribValue!==f)C(e,`xml: prefix must be bound to `+f+`
|
|
133
133
|
Actual: `+e.attribValue);else if(r===`xmlns`&&e.attribValue!==p)C(e,`xmlns: prefix must be bound to `+p+`
|
|
134
|
-
Actual: `+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[r]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,ie(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function fe(e,t){if(e.opt.xmlns){var n=e.tag,r=ue(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(C(e,`Unbound namespace prefix: `+JSON.stringify(e.tagName)),n.uri=r.prefix);var i=e.tags[e.tags.length-1]||e;n.ns&&i.ns!==n.ns&&Object.keys(n.ns).forEach(function(t){ie(e,`onopennamespace`,{prefix:t,uri:n.ns[t]})});for(var a=0,o=e.attribList.length;a<o;a++){var s=e.attribList[a],c=s[0],l=s[1],u=ue(c,!0),d=u.prefix,f=u.local,p=d===``?``:n.ns[d]||``,m={name:c,value:l,prefix:d,local:f,uri:p};d&&d!==`xmlns`&&!p&&(C(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,ie(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),ie(e,`onopentag`,e.tag),t||(!e.noscript&&e.tagName.toLowerCase()===`script`?e.state=S.SCRIPT:e.state=S.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function pe(e){if(!e.tagName){C(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=S.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=S.SCRIPT;return}ie(e,`onscript`,e.script),e.script=``}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--&&e.tags[t].name!==r;)C(e,`Unexpected close tag`);if(t<0){C(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=S.TEXT;return}e.tagName=n;for(var i=e.tags.length;i
|
|
134
|
+
Actual: `+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[r]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,ie(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function fe(e,t){if(e.opt.xmlns){var n=e.tag,r=ue(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(C(e,`Unbound namespace prefix: `+JSON.stringify(e.tagName)),n.uri=r.prefix);var i=e.tags[e.tags.length-1]||e;n.ns&&i.ns!==n.ns&&Object.keys(n.ns).forEach(function(t){ie(e,`onopennamespace`,{prefix:t,uri:n.ns[t]})});for(var a=0,o=e.attribList.length;a<o;a++){var s=e.attribList[a],c=s[0],l=s[1],u=ue(c,!0),d=u.prefix,f=u.local,p=d===``?``:n.ns[d]||``,m={name:c,value:l,prefix:d,local:f,uri:p};d&&d!==`xmlns`&&!p&&(C(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,ie(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),ie(e,`onopentag`,e.tag),t||(!e.noscript&&e.tagName.toLowerCase()===`script`?e.state=S.SCRIPT:e.state=S.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function pe(e){if(!e.tagName){C(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=S.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=S.SCRIPT;return}ie(e,`onscript`,e.script),e.script=``}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--&&e.tags[t].name!==r;)C(e,`Unexpected close tag`);if(t<0){C(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=S.TEXT;return}e.tagName=n;for(var i=e.tags.length;i-->t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,ie(e,`onclosetag`,e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var n=a.ns[t];ie(e,`onclosenamespace`,{prefix:t,uri:n})})}t===0&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName=``,e.attribList.length=0,e.state=S.TEXT}function me(e){var t=e.entity,n=t.toLowerCase(),r,i=``;return e.ENTITIES[t]?e.ENTITIES[t]:e.ENTITIES[n]?e.ENTITIES[n]:(t=n,t.charAt(0)===`#`&&(t.charAt(1)===`x`?(t=t.slice(2),r=parseInt(t,16),i=r.toString(16)):(t=t.slice(1),r=parseInt(t,10),i=r.toString(10))),t=t.replace(/^0+/,``),isNaN(r)||i.toLowerCase()!==t?(C(e,`Invalid character entity`),`&`+e.entity+`;`):String.fromCodePoint(r))}function he(e,t){t===`<`?(e.state=S.OPEN_WAKA,e.startTagPosition=e.position):y(t)||(C(e,`Non-whitespace before first tag.`),e.textNode=t,e.state=S.TEXT)}function ge(e,t){var n=``;return t<e.length&&(n=e.charAt(t)),n}function _e(e){var t=this;if(this.error)throw this.error;if(t.closed)return se(t,`Cannot write after close. Assign an onready handler.`);if(e===null)return ce(t);typeof e==`object`&&(e=e.toString());for(var n=0,i=``;i=ge(e,n++),t.c=i,i;)switch(t.trackPosition&&(t.position++,i===`
|
|
135
135
|
`?(t.line++,t.column=0):t.column++),t.state){case S.BEGIN:if(t.state=S.BEGIN_WHITESPACE,i===``)continue;he(t,i);continue;case S.BEGIN_WHITESPACE:he(t,i);continue;case S.TEXT:if(t.sawRoot&&!t.closedRoot){for(var a=n-1;i&&i!==`<`&&i!==`&`;)i=ge(e,n++),i&&t.trackPosition&&(t.position++,i===`
|
|
136
136
|
`?(t.line++,t.column=0):t.column++);t.textNode+=e.substring(a,n-1)}i===`<`&&!(t.sawRoot&&t.closedRoot&&!t.strict)?(t.state=S.OPEN_WAKA,t.startTagPosition=t.position):(!y(i)&&(!t.sawRoot||t.closedRoot)&&C(t,`Text data outside of root node.`),i===`&`?t.state=S.TEXT_ENTITY:t.textNode+=i);continue;case S.SCRIPT:i===`<`?t.state=S.SCRIPT_ENDING:t.script+=i;continue;case S.SCRIPT_ENDING:i===`/`?t.state=S.CLOSE_TAG:(t.script+=`<`+i,t.state=S.SCRIPT);continue;case S.OPEN_WAKA:if(i===`!`)t.state=S.SGML_DECL,t.sgmlDecl=``;else if(!y(i))if(ee(h,i))t.state=S.OPEN_TAG,t.tagName=i;else if(i===`/`)t.state=S.CLOSE_TAG,t.tagName=``;else if(i===`?`)t.state=S.PROC_INST,t.procInstName=t.procInstBody=``;else{if(C(t,`Unencoded <`),t.startTagPosition+1<t.position){var o=t.position-t.startTagPosition;i=Array(o).join(` `)+i}t.textNode+=`<`+i,t.state=S.TEXT}continue;case S.SGML_DECL:(t.sgmlDecl+i).toUpperCase()===u?(ie(t,`onopencdata`),t.state=S.CDATA,t.sgmlDecl=``,t.cdata=``):t.sgmlDecl+i===`--`?(t.state=S.COMMENT,t.comment=``,t.sgmlDecl=``):(t.sgmlDecl+i).toUpperCase()===d?(t.state=S.DOCTYPE,(t.doctype||t.sawRoot)&&C(t,`Inappropriately located doctype declaration`),t.doctype=``,t.sgmlDecl=``):i===`>`?(ie(t,`onsgmldeclaration`,t.sgmlDecl),t.sgmlDecl=``,t.state=S.TEXT):(b(i)&&(t.state=S.SGML_DECL_QUOTED),t.sgmlDecl+=i);continue;case S.SGML_DECL_QUOTED:i===t.q&&(t.state=S.SGML_DECL,t.q=``),t.sgmlDecl+=i;continue;case S.DOCTYPE:i===`>`?(t.state=S.TEXT,ie(t,`ondoctype`,t.doctype),t.doctype=!0):(t.doctype+=i,i===`[`?t.state=S.DOCTYPE_DTD:b(i)&&(t.state=S.DOCTYPE_QUOTED,t.q=i));continue;case S.DOCTYPE_QUOTED:t.doctype+=i,i===t.q&&(t.q=``,t.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:t.doctype+=i,i===`]`?t.state=S.DOCTYPE:b(i)&&(t.state=S.DOCTYPE_DTD_QUOTED,t.q=i);continue;case S.DOCTYPE_DTD_QUOTED:t.doctype+=i,i===t.q&&(t.state=S.DOCTYPE_DTD,t.q=``);continue;case S.COMMENT:i===`-`?t.state=S.COMMENT_ENDING:t.comment+=i;continue;case S.COMMENT_ENDING:i===`-`?(t.state=S.COMMENT_ENDED,t.comment=oe(t.opt,t.comment),t.comment&&ie(t,`oncomment`,t.comment),t.comment=``):(t.comment+=`-`+i,t.state=S.COMMENT);continue;case S.COMMENT_ENDED:i===`>`?t.state=S.TEXT:(C(t,`Malformed comment`),t.comment+=`--`+i,t.state=S.COMMENT);continue;case S.CDATA:i===`]`?t.state=S.CDATA_ENDING:t.cdata+=i;continue;case S.CDATA_ENDING:i===`]`?t.state=S.CDATA_ENDING_2:(t.cdata+=`]`+i,t.state=S.CDATA);continue;case S.CDATA_ENDING_2:i===`>`?(t.cdata&&ie(t,`oncdata`,t.cdata),ie(t,`onclosecdata`),t.cdata=``,t.state=S.TEXT):i===`]`?t.cdata+=`]`:(t.cdata+=`]]`+i,t.state=S.CDATA);continue;case S.PROC_INST:i===`?`?t.state=S.PROC_INST_ENDING:y(i)?t.state=S.PROC_INST_BODY:t.procInstName+=i;continue;case S.PROC_INST_BODY:if(!t.procInstBody&&y(i))continue;i===`?`?t.state=S.PROC_INST_ENDING:t.procInstBody+=i;continue;case S.PROC_INST_ENDING:i===`>`?(ie(t,`onprocessinginstruction`,{name:t.procInstName,body:t.procInstBody}),t.procInstName=t.procInstBody=``,t.state=S.TEXT):(t.procInstBody+=`?`+i,t.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:ee(g,i)?t.tagName+=i:(le(t),i===`>`?fe(t):i===`/`?t.state=S.OPEN_TAG_SLASH:(y(i)||C(t,`Invalid character in tag name`),t.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:i===`>`?(fe(t,!0),pe(t)):(C(t,`Forward-slash in opening tag not followed by >`),t.state=S.ATTRIB);continue;case S.ATTRIB:if(y(i))continue;i===`>`?fe(t):i===`/`?t.state=S.OPEN_TAG_SLASH:ee(h,i)?(t.attribName=i,t.attribValue=``,t.state=S.ATTRIB_NAME):C(t,`Invalid attribute name`);continue;case S.ATTRIB_NAME:i===`=`?t.state=S.ATTRIB_VALUE:i===`>`?(C(t,`Attribute without value`),t.attribValue=t.attribName,de(t),fe(t)):y(i)?t.state=S.ATTRIB_NAME_SAW_WHITE:ee(g,i)?t.attribName+=i:C(t,`Invalid attribute name`);continue;case S.ATTRIB_NAME_SAW_WHITE:if(i===`=`)t.state=S.ATTRIB_VALUE;else if(y(i))continue;else C(t,`Attribute without value`),t.tag.attributes[t.attribName]=``,t.attribValue=``,ie(t,`onattribute`,{name:t.attribName,value:``}),t.attribName=``,i===`>`?fe(t):ee(h,i)?(t.attribName=i,t.state=S.ATTRIB_NAME):(C(t,`Invalid attribute name`),t.state=S.ATTRIB);continue;case S.ATTRIB_VALUE:if(y(i))continue;b(i)?(t.q=i,t.state=S.ATTRIB_VALUE_QUOTED):(C(t,`Unquoted attribute value`),t.state=S.ATTRIB_VALUE_UNQUOTED,t.attribValue=i);continue;case S.ATTRIB_VALUE_QUOTED:if(i!==t.q){i===`&`?t.state=S.ATTRIB_VALUE_ENTITY_Q:t.attribValue+=i;continue}de(t),t.q=``,t.state=S.ATTRIB_VALUE_CLOSED;continue;case S.ATTRIB_VALUE_CLOSED:y(i)?t.state=S.ATTRIB:i===`>`?fe(t):i===`/`?t.state=S.OPEN_TAG_SLASH:ee(h,i)?(C(t,`No whitespace between attributes`),t.attribName=i,t.attribValue=``,t.state=S.ATTRIB_NAME):C(t,`Invalid attribute name`);continue;case S.ATTRIB_VALUE_UNQUOTED:if(!x(i)){i===`&`?t.state=S.ATTRIB_VALUE_ENTITY_U:t.attribValue+=i;continue}de(t),i===`>`?fe(t):t.state=S.ATTRIB;continue;case S.CLOSE_TAG:if(t.tagName)i===`>`?pe(t):ee(g,i)?t.tagName+=i:t.script?(t.script+=`</`+t.tagName,t.tagName=``,t.state=S.SCRIPT):(y(i)||C(t,`Invalid tagname in closing tag`),t.state=S.CLOSE_TAG_SAW_WHITE);else{if(y(i))continue;te(h,i)?t.script?(t.script+=`</`+i,t.state=S.SCRIPT):C(t,`Invalid tagname in closing tag.`):t.tagName=i}continue;case S.CLOSE_TAG_SAW_WHITE:if(y(i))continue;i===`>`?pe(t):C(t,`Invalid characters in closing tag`);continue;case S.TEXT_ENTITY:case S.ATTRIB_VALUE_ENTITY_Q:case S.ATTRIB_VALUE_ENTITY_U:var s,c;switch(t.state){case S.TEXT_ENTITY:s=S.TEXT,c=`textNode`;break;case S.ATTRIB_VALUE_ENTITY_Q:s=S.ATTRIB_VALUE_QUOTED,c=`attribValue`;break;case S.ATTRIB_VALUE_ENTITY_U:s=S.ATTRIB_VALUE_UNQUOTED,c=`attribValue`;break}if(i===`;`)if(t.opt.unparsedEntities){var l=me(t);t.entity=``,t.state=s,t.write(l)}else t[c]+=me(t),t.entity=``,t.state=s;else ee(t.entity.length?v:_,i)?t.entity+=i:(C(t,`Invalid character in entity name`),t[c]+=`&`+t.entity+i,t.entity=``,t.state=s);continue;default:throw Error(t,`Unknown state: `+t.state)}return t.position>=t.bufferCheckPosition&&r(t),t}return String.fromCodePoint||(function(){var e=String.fromCharCode,t=Math.floor,n=function(){var n=16384,r=[],i,a,o=-1,s=arguments.length;if(!s)return``;for(var c=``;++o<s;){var l=Number(arguments[o]);if(!isFinite(l)||l<0||l>1114111||t(l)!==l)throw RangeError(`Invalid code point: `+l);l<=65535?r.push(l):(l-=65536,i=(l>>10)+55296,a=l%1024+56320,r.push(i,a)),(o+1===s||r.length>n)&&(c+=e.apply(null,r),r.length=0)}return c};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:n,configurable:!0,writable:!0}):String.fromCodePoint=n})(),e}(),FT=`The output should be formatted as a XML file.
|
|
137
137
|
1. Output should conform to the tags below.
|
|
@@ -172,7 +172,7 @@ Here are the output tags:
|
|
|
172
172
|
|
|
173
173
|
`;prefix=``;templateFormat=`f-string`;validateTemplate=!0;_getPromptType(){return`few_shot_chat`}static lc_name(){return`FewShotChatMessagePromptTemplate`}constructor(e){if(super(e),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
|
|
174
174
|
|
|
175
|
-
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??``,this.suffix=e.suffix??``,this.templateFormat=e.templateFormat??`f-string`,this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),FD(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t);n=n.map(e=>{let t={};return this.examplePrompt.inputVariables.forEach(n=>{t[n]=e[n]}),t});let r=[];for(let e of n){let t=await this.examplePrompt.formatMessages(e);r.push(...t)}return r}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=(await Promise.all(n.map(e=>this.examplePrompt.formatMessages(e)))).flat().map(e=>e.content);return ND([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}},iO=class e extends ZE{static lc_name(){return`PipelinePromptTemplate`}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name),t=this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}async formatPipelinePrompts(t){let n=await this.mergePartialAndUserVariables(t);for(let{name:t,prompt:r}of this.pipelinePrompts){let i=e.extractRequiredInputValues(n,r.inputVariables);r instanceof tO?n[t]=await r.formatMessages(i):n[t]=await r.format(i)}return e.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(t){let n={...this};return n.inputVariables=this.inputVariables.filter(e=>!(e in t)),n.partialVariables={...this.partialVariables??{},...t},new e(n)}serialize(){throw Error(`Not implemented.`)}_getPromptType(){return`pipeline`}};function aO(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function oO(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var sO=class e extends tO{schema;method;lc_namespace=[`langchain_core`,`prompts`,`structured`];get lc_aliases(){return{...super.lc_aliases,schema:`schema_`}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(aO(e))return super.pipe(e.withStructuredOutput(this.schema));if(oO(e)&&aO(e.bound))return super.pipe(new wx({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`)}static fromMessagesAndSchema(t,n,r){return e.fromMessages(t,{schema:n,method:r})}},cO=s({AIMessagePromptTemplate:()=>XD,BaseChatPromptTemplate:()=>WD,BaseMessagePromptTemplate:()=>VD,BaseMessageStringPromptTemplate:()=>UD,BasePromptTemplate:()=>ZE,BaseStringPromptTemplate:()=>QE,ChatMessagePromptTemplate:()=>GD,ChatPromptTemplate:()=>tO,DEFAULT_FORMATTER_MAPPING:()=>jD,DEFAULT_PARSER_MAPPING:()=>MD,DictPromptTemplate:()=>RD,FewShotChatMessagePromptTemplate:()=>rO,FewShotPromptTemplate:()=>nO,HumanMessagePromptTemplate:()=>YD,ImagePromptTemplate:()=>LD,MessagesPlaceholder:()=>HD,PipelinePromptTemplate:()=>iO,PromptTemplate:()=>ID,StructuredPrompt:()=>sO,SystemMessagePromptTemplate:()=>ZD,checkValidTemplate:()=>FD,interpolateFString:()=>kD,interpolateMustache:()=>AD,parseFString:()=>ED,parseMustache:()=>OD,parseTemplate:()=>PD,renderTemplate:()=>ND}),lO=s({BaseDocumentCompressor:()=>uO}),uO=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},dO=s({BaseRetriever:()=>fO}),fO=class extends Cx{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=Zl(Ml(t)),r=await(await zl.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},pO=s({BaseStore:()=>mO,InMemoryStore:()=>hO}),mO=class extends ve{},hO=class extends mO{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},gO={and:`and`,or:`or`,not:`not`},_O={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},vO=class{},yO=class{accept(e){if(this.exprName===`Operation`)return e.visitOperation(this);if(this.exprName===`Comparison`)return e.visitComparison(this);if(this.exprName===`StructuredQuery`)return e.visitStructuredQuery(this);throw Error(`Unknown Expression type`)}},bO=class extends yO{},xO=class extends bO{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},SO=class extends bO{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},CO=class extends yO{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function wO(e){return e&&typeof e==`object`&&!Array.isArray(e)}function TO(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:wO(e)&&Object.keys(e).length===0:!0}function EO(e){if(typeof e==`number`)return e%1==0;if(typeof e==`string`){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1==0&&t.toString()===e}return!1}function DO(e){if(typeof e==`number`)return e%1!=0;if(typeof e==`string`){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!=0&&t.toString()===e}return!1}function OO(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function kO(e){return typeof e==`boolean`}function AO(e){let t;if(OO(e))t=e;else if(EO(e))t=parseInt(e,10);else if(DO(e))t=parseFloat(e);else if(kO(e))t=!!e;else throw Error(`Unsupported value type`);return t}var jO=class extends vO{},MO=class extends jO{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[gO.and,gO.or],this.allowedComparators=e?.allowedComparators??[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte]}formatFunction(e){if(e in _O){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(`, `)}`)}else if(e in gO){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(`, `)}`)}else throw Error(`Unknown comparator or operator`);return`$${e}`}visitOperation(e){let t=e.args?.map(e=>e.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:AO(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!(TO(e)&&TO(t))){if(TO(e)||n===`replace`)return TO(t)?void 0:t;if(TO(t))return r?e:n===`and`?void 0:e;if(n===`and`)return{$and:[e,t]};if(n===`or`)return{$or:[e,t]};throw Error(`Unknown merge type`)}}},NO=class extends jO{allowedOperators=[gO.and,gO.or];allowedComparators=[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte];case`number`:return[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte];case`boolean`:return[_O.eq,_O.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case _O.eq:return(e,t)=>e===t;case _O.ne:return(e,t)=>e!==t;case _O.gt:return(e,t)=>e>t;case _O.gte:return(e,t)=>e>=t;case _O.lt:return(e,t)=>e<t;case _O.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case gO.and:return(e,t)=>e&&t;case gO.or:return(e,t)=>e||t;default:throw Error(`Unknown operator`)}}visitOperation(e){let{operator:t,args:n}=e;if(this.allowedOperators.includes(t)){let e=this.getOperatorFunction(t);return t=>n?n.reduce((n,r)=>{let i=r.accept(this);if(typeof i==`function`)return e(n,i(t));throw Error(`Filter is not a function`)},!0):!0}else throw Error(`Operator not allowed`)}visitComparison(e){let{comparator:t,attribute:n,value:r}=e,i=[_O.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof r).includes(t))throw Error(`'${t}' comparator not allowed to be used with ${typeof r}`);let e=this.getComparatorFunction(t);return a=>{let o=a.metadata[n];return o===void 0?!!i.includes(t):e(o,AO(r))}}else throw Error(`Comparator not allowed`)}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!=`function`)throw Error(`Structured query filter is not a function`);return{filter:t}}mergeFilters(e,t,n=`and`){if(!(TO(e)&&TO(t))){if(TO(e)||n===`replace`)return TO(t)?void 0:t;if(TO(t))return n===`and`?void 0:e;if(n===`and`)return n=>e(n)&&t(n);if(n===`or`)return n=>e(n)||t(n);throw Error(`Unknown merge type`)}}},PO=s({BaseTranslator:()=>jO,BasicTranslator:()=>MO,Comparators:()=>_O,Comparison:()=>xO,Expression:()=>yO,FilterDirective:()=>bO,FunctionalTranslator:()=>NO,Operation:()=>SO,Operators:()=>gO,StructuredQuery:()=>CO,Visitor:()=>vO,castValue:()=>AO,isBoolean:()=>kO,isFilterEmpty:()=>TO,isFloat:()=>DO,isInt:()=>EO,isObject:()=>wO,isString:()=>OO});function FO(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.text!==void 0&&t.toolCalls!==void 0&&t.reasoning!==void 0&&t.usage!==void 0&&t.output!==void 0&&typeof t[Symbol.asyncIterator]==`function`}function IO(e,t,n){return e==null?!1:Object.entries(t).every(([t,r])=>n(e[t],r))}function LO(e,t,n){return e==null?!1:IO(e,t,n)}function RO(e){return e.content.find(e=>e.type===`text`)?.text}function zO(e,t,n){if(t.id!==void 0&&e.id!==t.id||t.text!==void 0&&RO(e)!==t.text)return!1;if(t.toolCalls!==void 0){let r=e.tool_calls??[];if(r.length!==t.toolCalls.length)return!1;for(let e=0;e<t.toolCalls.length;e++){let i=r[e],a=t.toolCalls[e];if(i?.name!==a.name||!n(i.args,a.args))return!1}}return!(t.usage!==void 0&&!LO(e.usage_metadata,t.usage,n)||t.responseMetadata!==void 0&&!IO(e.response_metadata,t.responseMetadata,n))}function BO(e,t,n){return{pass:!1,message:()=>`${n.matcherHint(t)}\n\nExpected: ChatModelStream (return value of model.streamEvents("Hello"))\nReceived: ${n.printReceived(e)}`,actual:e,expected:`ChatModelStream`}}function VO(e,t){return t?!e:e}async function HO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamText`;if(!FO(e))return BO(e,i,r);let a=await e.text;return{pass:VO(a===t,n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream text: ${n?`not `:``}${r.printExpected(t)}\nReceived stream text: ${r.printReceived(a)}`,actual:a,expected:t}}async function UO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamReasoning`;if(!FO(e))return BO(e,i,r);let a=await e.reasoning;return{pass:VO(a===t,n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream reasoning: ${n?`not `:``}${r.printExpected(t)}\nReceived stream reasoning: ${r.printReceived(a)}`,actual:a,expected:t}}async function WO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamToolCalls`;if(!FO(e))return BO(e,i,r);let a=await e.toolCalls,o=a.length===t.length&&t.every((e,t)=>{let n=a[t];return n?.name===e.name&&this.equals(n.args,e.args)});return o=VO(o,n),{pass:o,message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream tool calls: ${r.printExpected(t)}\nReceived stream tool calls: ${r.printReceived(a.map(e=>({name:e.name,args:e.args})))}`,actual:a.map(e=>({name:e.name,args:e.args})),expected:t}}async function GO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamUsage`;if(!FO(e))return BO(e,i,r);let a=await e.usage;return{pass:VO(LO(a,t,this.equals),n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream usage: ${r.printExpected(t)}\nReceived stream usage: ${r.printReceived(a)}`,actual:a,expected:t}}async function KO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamOutput`;if(!FO(e))return BO(e,i,r);let a=await e.output;return{pass:VO(zO(a,t,this.equals),n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream output: ${r.printExpected(t)}\nReceived stream output: ${r.printReceived({id:a.id,text:RO(a),tool_calls:a.tool_calls?.map(e=>({name:e.name,args:e.args})),usage_metadata:a.usage_metadata,response_metadata:a.response_metadata})}`,actual:a,expected:t}}var qO={toHaveStreamText:HO,toHaveStreamReasoning:UO,toHaveStreamToolCalls:WO,toHaveStreamUsage:GO,toHaveStreamOutput:KO};function JO(e){return rt.isInstance(e)?e.constructor.name||e.type:typeof e}function YO(e,t){return function(n,r){let{isNot:i,utils:a}=this;if(!t(n))return{pass:!1,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${i?`not `:``}${e}\nReceived: ${JO(n)}`,actual:JO(n),expected:e};if(r===void 0)return{pass:!0,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: not ${e}\nReceived: ${e}`};let o=n;return typeof r==`string`?{pass:o.content===r,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${e} with content ${a.printExpected(r)}\nReceived: ${e} with content ${a.printReceived(o.content)}`,actual:o.content,expected:r}:{pass:Object.entries(r).every(([e,t])=>this.equals(o[e],t)),message:()=>{let t={};for(let e of Object.keys(r))t[e]=o[e];return`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${e} matching ${a.printExpected(r)}\nReceived: ${e} with ${a.printReceived(t)}`},actual:(()=>{let e={};for(let t of Object.keys(r))e[t]=o[t];return e})(),expected:r}}}var XO=YO(`HumanMessage`,fn.isInstance),ZO=YO(`AIMessage`,$t.isInstance),QO=YO(`SystemMessage`,_n.isInstance),$O=YO(`ToolMessage`,xt.isInstance);function ek(e,t){let{isNot:n,utils:r}=this;if(!$t.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected: AIMessage\nReceived: ${JO(e)}`};let i=e.tool_calls??[];if(i.length!==t.length)return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected ${n?`not `:``}${t.length} tool call(s), received ${i.length}`,actual:i.length,expected:t.length};let a=t.filter(e=>!i.some(t=>Object.entries(e).every(([e,n])=>this.equals(t[e],n))));return a.length>0?{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nCould not find matching tool call(s) for:\n${r.printExpected(a)}\nReceived tool calls: ${r.printReceived(i.map(e=>({name:e.name,id:e.id,args:e.args})))}`,actual:i.map(e=>({name:e.name,id:e.id,args:e.args})),expected:t}:{pass:!0,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected AIMessage not to have matching tool calls`}}function tk(e,t){let{isNot:n,utils:r}=this;if(!$t.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected: AIMessage\nReceived: ${JO(e)}`};let i=e.tool_calls?.length??0;return{pass:i===t,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected ${n?`not `:``}${t} tool call(s)\nReceived: ${i}`,actual:i,expected:t}}function nk(e,t){let{isNot:n,utils:r}=this;if(!$t.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected: AIMessage\nReceived: ${JO(e)}`};let i=e.tool_calls??[];return{pass:i.some(e=>Object.entries(t).every(([t,n])=>this.equals(e[t],n))),message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected AIMessage ${n?`not `:``}to contain a tool call matching ${r.printExpected(t)}\nReceived tool calls: ${r.printReceived(i.map(e=>({name:e.name,id:e.id})))}`,actual:i.map(e=>({name:e.name,id:e.id})),expected:t}}function rk(e,t){let{isNot:n,utils:r}=this;if(!Array.isArray(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected an array of messages\nReceived: ${typeof e}`};let i=e.filter(xt.isInstance);if(i.length!==t.length)return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected ${n?`not `:``}${t.length} tool message(s), found ${i.length}`,actual:i.length,expected:t.length};for(let e=0;e<t.length;e++)if(!Object.entries(t[e]).every(([t,n])=>this.equals(i[e][t],n)))return{pass:!1,message:()=>{let n={};for(let r of Object.keys(t[e]))n[r]=i[e][r];return`${r.matcherHint(`toHaveToolMessages`)}\n\nTool message at index ${e} did not match:\nExpected: ${r.printExpected(t[e])}\nReceived: ${r.printReceived(n)}`},actual:i[e],expected:t[e]};return{pass:!0,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected messages not to contain matching tool messages`}}function ik(e,t){let{isNot:n,utils:r}=this,i=e?.__interrupt__;if(!(Array.isArray(i)&&i.length>0))return{pass:!1,message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected result ${n?`not `:``}to have been interrupted\nReceived __interrupt__: ${r.printReceived(i)}`};if(t===void 0)return{pass:!0,message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected result not to have been interrupted\nReceived ${i.length} interrupt(s)`};let a=i[0]?.value;return{pass:this.equals(a,t),message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected interrupt value: ${r.printExpected(t)}\nReceived interrupt value: ${r.printReceived(a)}`,actual:a,expected:t}}function ak(e,t){let{isNot:n,utils:r}=this,i=e?.structuredResponse;return i===void 0?{pass:!1,message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected result ${n?`not `:``}to have a structured response\nReceived structuredResponse: undefined`}:t===void 0?{pass:!0,message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected result not to have a structured response`}:{pass:Object.entries(t).every(([e,t])=>this.equals(i[e],t)),message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected structured response: ${r.printExpected(t)}\nReceived structured response: ${r.printReceived(i)}`,actual:i,expected:t}}var ok={toBeHumanMessage:XO,toBeAIMessage:ZO,toBeSystemMessage:QO,toBeToolMessage:$O,toHaveToolCalls:ek,toHaveToolCallCount:tk,toContainToolCall:nk,toHaveToolMessages:rk,toHaveBeenInterrupted:ik,toHaveStructuredResponse:ak,...qO};function sk(e){return e.map(e=>e.text).filter(Boolean).join(`-`)}var ck=0;function lk(){return ck+=1,`fake_tc_${ck}`}var uk=class e extends EE{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_state={callIndex:0,calls:[]};get calls(){return this._state.calls}get callCount(){return this._state.calls.length}constructor(){super({})}_llmType(){return`fake-model-builder`}_combineLLMOutput(){return[]}respond(e){return typeof e==`function`?this.queue.push({kind:`factory`,factory:e}):rt.isInstance(e)?this.queue.push({kind:`message`,message:e}):this.queue.push({kind:`error`,error:e}),this}respondWithTools(e){return this.queue.push({kind:`toolCalls`,toolCalls:e.map(e=>({name:e.name,args:e.args,id:e.id??lk(),type:`tool_call`}))}),this}alwaysThrow(e){return this._alwaysThrowError=e,this}structuredResponse(e){return this._structuredResponseValue=e,this}bindTools(t){let n=[...this._tools,...t],r=new e;return r.queue=this.queue,r._alwaysThrowError=this._alwaysThrowError,r._structuredResponseValue=this._structuredResponseValue,r._tools=n,r._state=this._state,r.withConfig({})}withStructuredOutput(e,t){let{_structuredResponseValue:n}=this;return jx.from(async()=>n)}async _generate(e,t,n){this._state.calls.push({messages:[...e],options:t});let r=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let i=this.queue[r];if(!i)throw Error(`FakeModel: no response queued for invocation ${r} (${this.queue.length} total queued).`);if(i.kind===`error`)throw i.error;if(i.kind===`factory`){let t=i.factory(e);if(!rt.isInstance(t))throw t;return{generations:[{text:``,message:t}]}}if(i.kind===`message`)return{generations:[{text:``,message:i.message}]};let a=sk(e);return{generations:[{text:a,message:new $t({content:a,id:r.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(e=>({...e,type:`tool_call`})):void 0})}],llmOutput:{}}}};function dk(){return new uk}function fk(e){return{async*[Symbol.asyncIterator](){for(let t of e)yield t}}}function pk(e=`test-model`){let t=mk(e),n=t[t.length-1];return t[t.length-1]={...n,usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}},t}function mk(e=`test-model`){return[{id:`chatcmpl-text`,model:e,choices:[{index:0,delta:{role:`assistant`,content:`Hello`},finish_reason:null}]},{id:`chatcmpl-text`,model:e,choices:[{index:0,delta:{content:` world`},finish_reason:null}]},{id:`chatcmpl-text`,model:e,choices:[{index:0,delta:{},finish_reason:`stop`}]}]}function hk(e=`test-model`){return[{id:`chatcmpl-reason`,model:e,choices:[{index:0,delta:{role:`assistant`,reasoning_content:`Let me reason...`},finish_reason:null}]},{id:`chatcmpl-reason`,model:e,choices:[{index:0,delta:{content:`Answer.`},finish_reason:null}]},{id:`chatcmpl-reason`,model:e,choices:[{index:0,delta:{},finish_reason:`stop`}]}]}function gk(e=`test-model`){return[{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{role:`assistant`,content:`Let me search.`},finish_reason:null}]},{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{tool_calls:[{index:0,id:`call_abc`,type:`function`,function:{name:`web_search`,arguments:`{"query"`}}]},finish_reason:null}]},{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{tool_calls:[{index:0,function:{arguments:`:"weather"}`}}]},finish_reason:null}]},{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{},finish_reason:`tool_calls`}]}]}function _k(e){let t=new TextEncoder;return new Response(new ReadableStream({start(n){for(let r of e)n.enqueue(t.encode(`data: ${JSON.stringify(r)}\n\n`));n.close()}}),{status:200,headers:{"Content-Type":`text/event-stream`}})}var vk=s({FakeBuiltModel:()=>uk,asAsyncIterable:()=>fk,fakeModel:()=>dk,langchainMatchers:()=>ok,openAIReasoningTextChunks:()=>hk,openAITextOnlyChunks:()=>mk,openAITextOnlyChunksWithUsage:()=>pk,openAIToolCallChunks:()=>gk,sseResponseFromOpenAIChunks:()=>_k,streamMatchers:()=>qO,toBeAIMessage:()=>ZO,toBeHumanMessage:()=>XO,toBeSystemMessage:()=>QO,toBeToolMessage:()=>$O,toContainToolCall:()=>nk,toHaveBeenInterrupted:()=>ik,toHaveStructuredResponse:()=>ak,toHaveToolCallCount:()=>tk,toHaveToolCalls:()=>ek,toHaveToolMessages:()=>rk});function yk(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function bk(e){return e!==void 0&&Cx.isRunnable(e)&&`lc_name`in e.constructor&&typeof e.constructor.lc_name==`function`&&e.constructor.lc_name()===`RunnableToolLike`}function xk(e){return!!e&&typeof e==`object`&&`name`in e&&`schema`in e&&(t_(e.schema)||e.schema!=null&&typeof e.schema==`object`&&`type`in e.schema&&typeof e.schema.type==`string`&&[`null`,`boolean`,`object`,`array`,`number`,`string`].includes(e.schema.type))}function Sk(e){return xk(e)||bk(e)||yk(e)}var Ck=A(`ZodISODateTime`,(e,t)=>{Kp.init(e,t),Yk.init(e,t)});function wk(e){return Ch(Ck,e)}var Tk=A(`ZodISODate`,(e,t)=>{qp.init(e,t),Yk.init(e,t)});function Ek(e){return wh(Tk,e)}var Dk=A(`ZodISOTime`,(e,t)=>{Jp.init(e,t),Yk.init(e,t)});function Ok(e){return Th(Dk,e)}var kk=A(`ZodISODuration`,(e,t)=>{Yp.init(e,t),Yk.init(e,t)});function Ak(e){return Eh(kk,e)}var jk=A(`ZodError`,(e,t)=>{mf.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>_f(e,t)},flatten:{value:t=>gf(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jd,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jd,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Mk=bf(jk),Nk=Sf(jk),Pk=wf(jk),Fk=Ef(jk),Ik=Of(jk),Lk=kf(jk),Rk=Af(jk),zk=jf(jk),Bk=Mf(jk),Vk=Nf(jk),Hk=Pf(jk),Uk=Ff(jk),Wk=new WeakMap;function Gk(e,t,n){let r=Object.getPrototypeOf(e),i=Wk.get(r);if(i||(i=new Set,Wk.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Kk=A(`ZodType`,(e,t)=>(Mp.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ug(e,`input`),output:ug(e,`output`)}}),e.toJSONSchema=lg(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Mk(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Pk(e,t,n),e.parseAsync=async(t,n)=>Nk(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Fk(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ik(e,t,n),e.decode=(t,n)=>Lk(e,t,n),e.encodeAsync=async(t,n)=>Rk(e,t,n),e.decodeAsync=async(t,n)=>zk(e,t,n),e.safeEncode=(t,n)=>Bk(e,t,n),e.safeDecode=(t,n)=>Vk(e,t,n),e.safeEncodeAsync=async(t,n)=>Hk(e,t,n),e.safeDecodeAsync=async(t,n)=>Uk(e,t,n),Gk(e,`ZodType`,{check(...e){let t=this.def;return this.clone(zd(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Yd(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(fj(e,t))},superRefine(e,t){return this.check(pj(e,t))},overwrite(e){return this.check(qh(e))},optional(){return qA(this)},exactOptional(){return YA(this)},nullable(){return ZA(this)},nullish(){return qA(ZA(this))},nonoptional(e){return rj(this,e)},array(){return OA(this)},or(e){return jA([this,e])},and(e){return FA(this,e)},transform(e){return sj(this,GA(e))},default(e){return $A(this,e)},prefault(e){return tj(this,e)},catch(e){return aj(this,e)},pipe(e){return sj(this,e)},readonly(){return lj(this)},describe(e){let t=this.clone();return $m.add(t,{description:e}),t},meta(...e){if(e.length===0)return $m.get(this);let t=this.clone();return $m.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return $m.get(e)?.description},configurable:!0}),e)),qk=A(`_ZodString`,(e,t)=>{Np.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fg(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Gk(e,`_ZodString`,{regex(...e){return this.check(Vh(...e))},includes(...e){return this.check(Wh(...e))},startsWith(...e){return this.check(Gh(...e))},endsWith(...e){return this.check(Kh(...e))},min(...e){return this.check(zh(...e))},max(...e){return this.check(Rh(...e))},length(...e){return this.check(Bh(...e))},nonempty(...e){return this.check(zh(1,...e))},lowercase(e){return this.check(Hh(e))},uppercase(e){return this.check(Uh(e))},trim(){return this.check(Yh())},normalize(...e){return this.check(Jh(...e))},toLowerCase(){return this.check(Xh())},toUpperCase(){return this.check(Zh())},slugify(){return this.check(Qh())}})}),Jk=A(`ZodString`,(e,t)=>{Np.init(e,t),qk.init(e,t),e.email=t=>e.check(th(Xk,t)),e.url=t=>e.check(sh($k,t)),e.jwt=t=>e.check(Sh(mA,t)),e.emoji=t=>e.check(ch(eA,t)),e.guid=t=>e.check(nh(Zk,t)),e.uuid=t=>e.check(rh(Qk,t)),e.uuidv4=t=>e.check(ih(Qk,t)),e.uuidv6=t=>e.check(ah(Qk,t)),e.uuidv7=t=>e.check(oh(Qk,t)),e.nanoid=t=>e.check(lh(tA,t)),e.guid=t=>e.check(nh(Zk,t)),e.cuid=t=>e.check(uh(nA,t)),e.cuid2=t=>e.check(dh(rA,t)),e.ulid=t=>e.check(fh(iA,t)),e.base64=t=>e.check(yh(dA,t)),e.base64url=t=>e.check(bh(fA,t)),e.xid=t=>e.check(ph(aA,t)),e.ksuid=t=>e.check(mh(oA,t)),e.ipv4=t=>e.check(hh(sA,t)),e.ipv6=t=>e.check(gh(cA,t)),e.cidrv4=t=>e.check(_h(lA,t)),e.cidrv6=t=>e.check(vh(uA,t)),e.e164=t=>e.check(xh(pA,t)),e.datetime=t=>e.check(wk(t)),e.date=t=>e.check(Ek(t)),e.time=t=>e.check(Ok(t)),e.duration=t=>e.check(Ak(t))});function z(e){return eh(Jk,e)}var Yk=A(`ZodStringFormat`,(e,t)=>{Pp.init(e,t),qk.init(e,t)}),Xk=A(`ZodEmail`,(e,t)=>{Lp.init(e,t),Yk.init(e,t)}),Zk=A(`ZodGUID`,(e,t)=>{Fp.init(e,t),Yk.init(e,t)}),Qk=A(`ZodUUID`,(e,t)=>{Ip.init(e,t),Yk.init(e,t)}),$k=A(`ZodURL`,(e,t)=>{Rp.init(e,t),Yk.init(e,t)}),eA=A(`ZodEmoji`,(e,t)=>{zp.init(e,t),Yk.init(e,t)}),tA=A(`ZodNanoID`,(e,t)=>{Bp.init(e,t),Yk.init(e,t)}),nA=A(`ZodCUID`,(e,t)=>{Vp.init(e,t),Yk.init(e,t)}),rA=A(`ZodCUID2`,(e,t)=>{Hp.init(e,t),Yk.init(e,t)}),iA=A(`ZodULID`,(e,t)=>{Up.init(e,t),Yk.init(e,t)}),aA=A(`ZodXID`,(e,t)=>{Wp.init(e,t),Yk.init(e,t)}),oA=A(`ZodKSUID`,(e,t)=>{Gp.init(e,t),Yk.init(e,t)}),sA=A(`ZodIPv4`,(e,t)=>{Xp.init(e,t),Yk.init(e,t)}),cA=A(`ZodIPv6`,(e,t)=>{Zp.init(e,t),Yk.init(e,t)}),lA=A(`ZodCIDRv4`,(e,t)=>{Qp.init(e,t),Yk.init(e,t)}),uA=A(`ZodCIDRv6`,(e,t)=>{$p.init(e,t),Yk.init(e,t)}),dA=A(`ZodBase64`,(e,t)=>{tm.init(e,t),Yk.init(e,t)}),fA=A(`ZodBase64URL`,(e,t)=>{rm.init(e,t),Yk.init(e,t)}),pA=A(`ZodE164`,(e,t)=>{im.init(e,t),Yk.init(e,t)}),mA=A(`ZodJWT`,(e,t)=>{om.init(e,t),Yk.init(e,t)}),hA=A(`ZodNumber`,(e,t)=>{sm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pg(e,t,n,r),Gk(e,`ZodNumber`,{gt(e,t){return this.check(Fh(e,t))},gte(e,t){return this.check(Ih(e,t))},min(e,t){return this.check(Ih(e,t))},lt(e,t){return this.check(Nh(e,t))},lte(e,t){return this.check(Ph(e,t))},max(e,t){return this.check(Ph(e,t))},int(e){return this.check(vA(e))},safe(e){return this.check(vA(e))},positive(e){return this.check(Fh(0,e))},nonnegative(e){return this.check(Ih(0,e))},negative(e){return this.check(Nh(0,e))},nonpositive(e){return this.check(Ph(0,e))},multipleOf(e,t){return this.check(Lh(e,t))},step(e,t){return this.check(Lh(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function gA(e){return Dh(hA,e)}var _A=A(`ZodNumberFormat`,(e,t)=>{cm.init(e,t),hA.init(e,t)});function vA(e){return Oh(_A,e)}var yA=A(`ZodBoolean`,(e,t)=>{lm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mg(e,t,n,r)});function bA(e){return kh(yA,e)}var xA=A(`ZodAny`,(e,t)=>{um.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function SA(){return Ah(xA)}var CA=A(`ZodUnknown`,(e,t)=>{dm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function wA(){return jh(CA)}var TA=A(`ZodNever`,(e,t)=>{fm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bg(e,t,n,r)});function EA(e){return Mh(TA,e)}var DA=A(`ZodArray`,(e,t)=>{mm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fg(e,t,n,r),e.element=t.element,Gk(e,`ZodArray`,{min(e,t){return this.check(zh(e,t))},nonempty(e){return this.check(zh(1,e))},max(e,t){return this.check(Rh(e,t))},length(e,t){return this.check(Bh(e,t))},unwrap(){return this.element}})});function OA(e,t){return $h(DA,e,t)}var kA=A(`ZodObject`,(e,t)=>{ym.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ig(e,t,n,r),Ld(e,`shape`,()=>t.shape),Gk(e,`ZodObject`,{keyof(){return VA(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:wA()})},loose(){return this.clone({...this._zod.def,catchall:wA()})},strict(){return this.clone({...this._zod.def,catchall:EA()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return ef(this,e)},safeExtend(e){return tf(this,e)},merge(e){return nf(this,e)},pick(e){return Qd(this,e)},omit(e){return $d(this,e)},partial(...e){return rf(KA,this,e[0])},required(...e){return af(nj,this,e[0])}})});function B(e,t){return new kA({type:`object`,shape:e??{},...j(t)})}var AA=A(`ZodUnion`,(e,t)=>{xm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lg(e,t,n,r),e.options=t.options});function jA(e,t){return new AA({type:`union`,options:e,...j(t)})}var MA=A(`ZodDiscriminatedUnion`,(e,t)=>{AA.init(e,t),Sm.init(e,t)});function NA(e,t,n){return new MA({type:`union`,options:t,discriminator:e,...j(n)})}var PA=A(`ZodIntersection`,(e,t)=>{Cm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rg(e,t,n,r)});function FA(e,t){return new PA({type:`intersection`,left:e,right:t})}var IA=A(`ZodTuple`,(e,t)=>{Em.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zg(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function LA(e,t,n){let r=t instanceof Mp;return new IA({type:`tuple`,items:e,rest:r?t:null,...j(r?n:t)})}var RA=A(`ZodRecord`,(e,t)=>{Am.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bg(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function zA(e,t,n){return!t||!t._zod?new RA({type:`record`,keyType:z(),valueType:e,...j(t)}):new RA({type:`record`,keyType:e,valueType:t,...j(n)})}var BA=A(`ZodEnum`,(e,t)=>{jm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wg(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new BA({...t,checks:[],...j(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new BA({...t,checks:[],...j(r),entries:i})}});function VA(e,t){return new BA({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...j(t)})}var HA=A(`ZodLiteral`,(e,t)=>{Mm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tg(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function UA(e,t){return new HA({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}var WA=A(`ZodTransform`,(e,t)=>{Nm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mg(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Dd(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ff(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(ff(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function GA(e){return new WA({type:`transform`,transform:e})}var KA=A(`ZodOptional`,(e,t)=>{Fm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qA(e){return new KA({type:`optional`,innerType:e})}var JA=A(`ZodExactOptional`,(e,t)=>{Im.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function YA(e){return new JA({type:`optional`,innerType:e})}var XA=A(`ZodNullable`,(e,t)=>{Lm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ZA(e){return new XA({type:`nullable`,innerType:e})}var QA=A(`ZodDefault`,(e,t)=>{Rm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $A(e,t){return new QA({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kd(t)}})}var ej=A(`ZodPrefault`,(e,t)=>{Bm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tj(e,t){return new ej({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kd(t)}})}var nj=A(`ZodNonOptional`,(e,t)=>{Vm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rj(e,t){return new nj({type:`nonoptional`,innerType:e,...j(t)})}var ij=A(`ZodCatch`,(e,t)=>{Um.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function aj(e,t){return new ij({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var oj=A(`ZodPipe`,(e,t)=>{Wm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kg(e,t,n,r),e.in=t.in,e.out=t.out});function sj(e,t){return new oj({type:`pipe`,in:e,out:t})}var cj=A(`ZodReadonly`,(e,t)=>{Km.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function lj(e){return new cj({type:`readonly`,innerType:e})}var uj=A(`ZodCustom`,(e,t)=>{Jm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ag(e,t,n,r)});function dj(e,t){return eg(uj,e??(()=>!0),t)}function fj(e,t={}){return tg(uj,e,t)}function pj(e,t){return ng(e,t)}var mj=s({BaseToolkit:()=>yj,DynamicStructuredTool:()=>vj,DynamicTool:()=>_j,StructuredTool:()=>hj,Tool:()=>gj,ToolInputParsingException:()=>v,isLangChainTool:()=>Sk,isRunnableToolLike:()=>bk,isStructuredTool:()=>yk,isStructuredToolParams:()=>xk,tool:()=>bj}),hj=class extends mT{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return[`langchain`,`tools`]}responseFormat=`content`;defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let n,r=Zl(Xl(this.defaultConfig,t));return g(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){let r=g(e)?e.args:e,i;if(t_(this.schema))try{i=await o_(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),k_(t)&&(n=`${n}\n\n${yf(t)}`),new v(n,JSON.stringify(e))}else{let t=nx(r,this.schema);if(!t.valid){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.errors.map(e=>`${e.keywordLocation}: ${e.error}`).join(`
|
|
175
|
+
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??``,this.suffix=e.suffix??``,this.templateFormat=e.templateFormat??`f-string`,this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),FD(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t);n=n.map(e=>{let t={};return this.examplePrompt.inputVariables.forEach(n=>{t[n]=e[n]}),t});let r=[];for(let e of n){let t=await this.examplePrompt.formatMessages(e);r.push(...t)}return r}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=(await Promise.all(n.map(e=>this.examplePrompt.formatMessages(e)))).flat().map(e=>e.content);return ND([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}},iO=class e extends ZE{static lc_name(){return`PipelinePromptTemplate`}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name),t=this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}async formatPipelinePrompts(t){let n=await this.mergePartialAndUserVariables(t);for(let{name:t,prompt:r}of this.pipelinePrompts){let i=e.extractRequiredInputValues(n,r.inputVariables);r instanceof tO?n[t]=await r.formatMessages(i):n[t]=await r.format(i)}return e.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(t){let n={...this};return n.inputVariables=this.inputVariables.filter(e=>!(e in t)),n.partialVariables={...this.partialVariables??{},...t},new e(n)}serialize(){throw Error(`Not implemented.`)}_getPromptType(){return`pipeline`}};function aO(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function oO(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var sO=class e extends tO{schema;method;lc_namespace=[`langchain_core`,`prompts`,`structured`];get lc_aliases(){return{...super.lc_aliases,schema:`schema_`}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(aO(e))return super.pipe(e.withStructuredOutput(this.schema));if(oO(e)&&aO(e.bound))return super.pipe(new wx({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`)}static fromMessagesAndSchema(t,n,r){return e.fromMessages(t,{schema:n,method:r})}},cO=s({AIMessagePromptTemplate:()=>XD,BaseChatPromptTemplate:()=>WD,BaseMessagePromptTemplate:()=>VD,BaseMessageStringPromptTemplate:()=>UD,BasePromptTemplate:()=>ZE,BaseStringPromptTemplate:()=>QE,ChatMessagePromptTemplate:()=>GD,ChatPromptTemplate:()=>tO,DEFAULT_FORMATTER_MAPPING:()=>jD,DEFAULT_PARSER_MAPPING:()=>MD,DictPromptTemplate:()=>RD,FewShotChatMessagePromptTemplate:()=>rO,FewShotPromptTemplate:()=>nO,HumanMessagePromptTemplate:()=>YD,ImagePromptTemplate:()=>LD,MessagesPlaceholder:()=>HD,PipelinePromptTemplate:()=>iO,PromptTemplate:()=>ID,StructuredPrompt:()=>sO,SystemMessagePromptTemplate:()=>ZD,checkValidTemplate:()=>FD,interpolateFString:()=>kD,interpolateMustache:()=>AD,parseFString:()=>ED,parseMustache:()=>OD,parseTemplate:()=>PD,renderTemplate:()=>ND}),lO=s({BaseDocumentCompressor:()=>uO}),uO=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},dO=s({BaseRetriever:()=>fO}),fO=class extends Cx{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=Zl(Ml(t)),r=await(await zl.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},pO=s({BaseStore:()=>mO,InMemoryStore:()=>hO}),mO=class extends ve{},hO=class extends mO{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},gO={and:`and`,or:`or`,not:`not`},_O={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},vO=class{},yO=class{accept(e){if(this.exprName===`Operation`)return e.visitOperation(this);if(this.exprName===`Comparison`)return e.visitComparison(this);if(this.exprName===`StructuredQuery`)return e.visitStructuredQuery(this);throw Error(`Unknown Expression type`)}},bO=class extends yO{},xO=class extends bO{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},SO=class extends bO{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},CO=class extends yO{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function wO(e){return e&&typeof e==`object`&&!Array.isArray(e)}function TO(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:wO(e)&&Object.keys(e).length===0:!0}function EO(e){if(typeof e==`number`)return e%1==0;if(typeof e==`string`){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1==0&&t.toString()===e}return!1}function DO(e){if(typeof e==`number`)return e%1!=0;if(typeof e==`string`){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!=0&&t.toString()===e}return!1}function OO(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function kO(e){return typeof e==`boolean`}function AO(e){let t;if(OO(e))t=e;else if(EO(e))t=parseInt(e,10);else if(DO(e))t=parseFloat(e);else if(kO(e))t=!!e;else throw Error(`Unsupported value type`);return t}var jO=class extends vO{},MO=class extends jO{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[gO.and,gO.or],this.allowedComparators=e?.allowedComparators??[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte]}formatFunction(e){if(e in _O){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(`, `)}`)}else if(e in gO){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(`, `)}`)}else throw Error(`Unknown comparator or operator`);return`$${e}`}visitOperation(e){let t=e.args?.map(e=>e.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:AO(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!(TO(e)&&TO(t))){if(TO(e)||n===`replace`)return TO(t)?void 0:t;if(TO(t))return r?e:n===`and`?void 0:e;if(n===`and`)return{$and:[e,t]};if(n===`or`)return{$or:[e,t]};throw Error(`Unknown merge type`)}}},NO=class extends jO{allowedOperators=[gO.and,gO.or];allowedComparators=[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte];case`number`:return[_O.eq,_O.ne,_O.gt,_O.gte,_O.lt,_O.lte];case`boolean`:return[_O.eq,_O.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case _O.eq:return(e,t)=>e===t;case _O.ne:return(e,t)=>e!==t;case _O.gt:return(e,t)=>e>t;case _O.gte:return(e,t)=>e>=t;case _O.lt:return(e,t)=>e<t;case _O.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case gO.and:return(e,t)=>e&&t;case gO.or:return(e,t)=>e||t;default:throw Error(`Unknown operator`)}}visitOperation(e){let{operator:t,args:n}=e;if(this.allowedOperators.includes(t)){let e=this.getOperatorFunction(t);return t=>!n||n.reduce((n,r)=>{let i=r.accept(this);if(typeof i==`function`)return e(n,i(t));throw Error(`Filter is not a function`)},!0)}else throw Error(`Operator not allowed`)}visitComparison(e){let{comparator:t,attribute:n,value:r}=e,i=[_O.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof r).includes(t))throw Error(`'${t}' comparator not allowed to be used with ${typeof r}`);let e=this.getComparatorFunction(t);return a=>{let o=a.metadata[n];return o===void 0?!!i.includes(t):e(o,AO(r))}}else throw Error(`Comparator not allowed`)}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!=`function`)throw Error(`Structured query filter is not a function`);return{filter:t}}mergeFilters(e,t,n=`and`){if(!(TO(e)&&TO(t))){if(TO(e)||n===`replace`)return TO(t)?void 0:t;if(TO(t))return n===`and`?void 0:e;if(n===`and`)return n=>e(n)&&t(n);if(n===`or`)return n=>e(n)||t(n);throw Error(`Unknown merge type`)}}},PO=s({BaseTranslator:()=>jO,BasicTranslator:()=>MO,Comparators:()=>_O,Comparison:()=>xO,Expression:()=>yO,FilterDirective:()=>bO,FunctionalTranslator:()=>NO,Operation:()=>SO,Operators:()=>gO,StructuredQuery:()=>CO,Visitor:()=>vO,castValue:()=>AO,isBoolean:()=>kO,isFilterEmpty:()=>TO,isFloat:()=>DO,isInt:()=>EO,isObject:()=>wO,isString:()=>OO});function FO(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.text!==void 0&&t.toolCalls!==void 0&&t.reasoning!==void 0&&t.usage!==void 0&&t.output!==void 0&&typeof t[Symbol.asyncIterator]==`function`}function IO(e,t,n){return e!=null&&Object.entries(t).every(([t,r])=>n(e[t],r))}function LO(e,t,n){return e!=null&&IO(e,t,n)}function RO(e){return e.content.find(e=>e.type===`text`)?.text}function zO(e,t,n){if(t.id!==void 0&&e.id!==t.id||t.text!==void 0&&RO(e)!==t.text)return!1;if(t.toolCalls!==void 0){let r=e.tool_calls??[];if(r.length!==t.toolCalls.length)return!1;for(let e=0;e<t.toolCalls.length;e++){let i=r[e],a=t.toolCalls[e];if(i?.name!==a.name||!n(i.args,a.args))return!1}}return!(t.usage!==void 0&&!LO(e.usage_metadata,t.usage,n)||t.responseMetadata!==void 0&&!IO(e.response_metadata,t.responseMetadata,n))}function BO(e,t,n){return{pass:!1,message:()=>`${n.matcherHint(t)}\n\nExpected: ChatModelStream (return value of model.streamEvents("Hello"))\nReceived: ${n.printReceived(e)}`,actual:e,expected:`ChatModelStream`}}function VO(e,t){return t?!e:e}async function HO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamText`;if(!FO(e))return BO(e,i,r);let a=await e.text;return{pass:VO(a===t,n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream text: ${n?`not `:``}${r.printExpected(t)}\nReceived stream text: ${r.printReceived(a)}`,actual:a,expected:t}}async function UO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamReasoning`;if(!FO(e))return BO(e,i,r);let a=await e.reasoning;return{pass:VO(a===t,n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream reasoning: ${n?`not `:``}${r.printExpected(t)}\nReceived stream reasoning: ${r.printReceived(a)}`,actual:a,expected:t}}async function WO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamToolCalls`;if(!FO(e))return BO(e,i,r);let a=await e.toolCalls,o=a.length===t.length&&t.every((e,t)=>{let n=a[t];return n?.name===e.name&&this.equals(n.args,e.args)});return o=VO(o,n),{pass:o,message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream tool calls: ${r.printExpected(t)}\nReceived stream tool calls: ${r.printReceived(a.map(e=>({name:e.name,args:e.args})))}`,actual:a.map(e=>({name:e.name,args:e.args})),expected:t}}async function GO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamUsage`;if(!FO(e))return BO(e,i,r);let a=await e.usage;return{pass:VO(LO(a,t,this.equals),n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream usage: ${r.printExpected(t)}\nReceived stream usage: ${r.printReceived(a)}`,actual:a,expected:t}}async function KO(e,t){let{isNot:n,utils:r}=this,i=`toHaveStreamOutput`;if(!FO(e))return BO(e,i,r);let a=await e.output;return{pass:VO(zO(a,t,this.equals),n),message:()=>`${r.matcherHint(i,void 0,void 0,{isNot:n})}\n\nExpected stream output: ${r.printExpected(t)}\nReceived stream output: ${r.printReceived({id:a.id,text:RO(a),tool_calls:a.tool_calls?.map(e=>({name:e.name,args:e.args})),usage_metadata:a.usage_metadata,response_metadata:a.response_metadata})}`,actual:a,expected:t}}var qO={toHaveStreamText:HO,toHaveStreamReasoning:UO,toHaveStreamToolCalls:WO,toHaveStreamUsage:GO,toHaveStreamOutput:KO};function JO(e){return rt.isInstance(e)?e.constructor.name||e.type:typeof e}function YO(e,t){return function(n,r){let{isNot:i,utils:a}=this;if(!t(n))return{pass:!1,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${i?`not `:``}${e}\nReceived: ${JO(n)}`,actual:JO(n),expected:e};if(r===void 0)return{pass:!0,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: not ${e}\nReceived: ${e}`};let o=n;return typeof r==`string`?{pass:o.content===r,message:()=>`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${e} with content ${a.printExpected(r)}\nReceived: ${e} with content ${a.printReceived(o.content)}`,actual:o.content,expected:r}:{pass:Object.entries(r).every(([e,t])=>this.equals(o[e],t)),message:()=>{let t={};for(let e of Object.keys(r))t[e]=o[e];return`${a.matcherHint(`toBe${e}`,void 0,void 0)}\n\nExpected: ${e} matching ${a.printExpected(r)}\nReceived: ${e} with ${a.printReceived(t)}`},actual:(()=>{let e={};for(let t of Object.keys(r))e[t]=o[t];return e})(),expected:r}}}var XO=YO(`HumanMessage`,fn.isInstance),ZO=YO(`AIMessage`,$t.isInstance),QO=YO(`SystemMessage`,_n.isInstance),$O=YO(`ToolMessage`,xt.isInstance);function ek(e,t){let{isNot:n,utils:r}=this;if(!$t.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected: AIMessage\nReceived: ${JO(e)}`};let i=e.tool_calls??[];if(i.length!==t.length)return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected ${n?`not `:``}${t.length} tool call(s), received ${i.length}`,actual:i.length,expected:t.length};let a=t.filter(e=>!i.some(t=>Object.entries(e).every(([e,n])=>this.equals(t[e],n))));return a.length>0?{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nCould not find matching tool call(s) for:\n${r.printExpected(a)}\nReceived tool calls: ${r.printReceived(i.map(e=>({name:e.name,id:e.id,args:e.args})))}`,actual:i.map(e=>({name:e.name,id:e.id,args:e.args})),expected:t}:{pass:!0,message:()=>`${r.matcherHint(`toHaveToolCalls`)}\n\nExpected AIMessage not to have matching tool calls`}}function tk(e,t){let{isNot:n,utils:r}=this;if(!$t.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected: AIMessage\nReceived: ${JO(e)}`};let i=e.tool_calls?.length??0;return{pass:i===t,message:()=>`${r.matcherHint(`toHaveToolCallCount`)}\n\nExpected ${n?`not `:``}${t} tool call(s)\nReceived: ${i}`,actual:i,expected:t}}function nk(e,t){let{isNot:n,utils:r}=this;if(!$t.isInstance(e))return{pass:!1,message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected: AIMessage\nReceived: ${JO(e)}`};let i=e.tool_calls??[];return{pass:i.some(e=>Object.entries(t).every(([t,n])=>this.equals(e[t],n))),message:()=>`${r.matcherHint(`toContainToolCall`)}\n\nExpected AIMessage ${n?`not `:``}to contain a tool call matching ${r.printExpected(t)}\nReceived tool calls: ${r.printReceived(i.map(e=>({name:e.name,id:e.id})))}`,actual:i.map(e=>({name:e.name,id:e.id})),expected:t}}function rk(e,t){let{isNot:n,utils:r}=this;if(!Array.isArray(e))return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected an array of messages\nReceived: ${typeof e}`};let i=e.filter(xt.isInstance);if(i.length!==t.length)return{pass:!1,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected ${n?`not `:``}${t.length} tool message(s), found ${i.length}`,actual:i.length,expected:t.length};for(let e=0;e<t.length;e++)if(!Object.entries(t[e]).every(([t,n])=>this.equals(i[e][t],n)))return{pass:!1,message:()=>{let n={};for(let r of Object.keys(t[e]))n[r]=i[e][r];return`${r.matcherHint(`toHaveToolMessages`)}\n\nTool message at index ${e} did not match:\nExpected: ${r.printExpected(t[e])}\nReceived: ${r.printReceived(n)}`},actual:i[e],expected:t[e]};return{pass:!0,message:()=>`${r.matcherHint(`toHaveToolMessages`)}\n\nExpected messages not to contain matching tool messages`}}function ik(e,t){let{isNot:n,utils:r}=this,i=e?.__interrupt__;if(!(Array.isArray(i)&&i.length>0))return{pass:!1,message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected result ${n?`not `:``}to have been interrupted\nReceived __interrupt__: ${r.printReceived(i)}`};if(t===void 0)return{pass:!0,message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected result not to have been interrupted\nReceived ${i.length} interrupt(s)`};let a=i[0]?.value;return{pass:this.equals(a,t),message:()=>`${r.matcherHint(`toHaveBeenInterrupted`)}\n\nExpected interrupt value: ${r.printExpected(t)}\nReceived interrupt value: ${r.printReceived(a)}`,actual:a,expected:t}}function ak(e,t){let{isNot:n,utils:r}=this,i=e?.structuredResponse;return i===void 0?{pass:!1,message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected result ${n?`not `:``}to have a structured response\nReceived structuredResponse: undefined`}:t===void 0?{pass:!0,message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected result not to have a structured response`}:{pass:Object.entries(t).every(([e,t])=>this.equals(i[e],t)),message:()=>`${r.matcherHint(`toHaveStructuredResponse`)}\n\nExpected structured response: ${r.printExpected(t)}\nReceived structured response: ${r.printReceived(i)}`,actual:i,expected:t}}var ok={toBeHumanMessage:XO,toBeAIMessage:ZO,toBeSystemMessage:QO,toBeToolMessage:$O,toHaveToolCalls:ek,toHaveToolCallCount:tk,toContainToolCall:nk,toHaveToolMessages:rk,toHaveBeenInterrupted:ik,toHaveStructuredResponse:ak,...qO};function sk(e){return e.map(e=>e.text).filter(Boolean).join(`-`)}var ck=0;function lk(){return ck+=1,`fake_tc_${ck}`}var uk=class e extends EE{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_state={callIndex:0,calls:[]};get calls(){return this._state.calls}get callCount(){return this._state.calls.length}constructor(){super({})}_llmType(){return`fake-model-builder`}_combineLLMOutput(){return[]}respond(e){return typeof e==`function`?this.queue.push({kind:`factory`,factory:e}):rt.isInstance(e)?this.queue.push({kind:`message`,message:e}):this.queue.push({kind:`error`,error:e}),this}respondWithTools(e){return this.queue.push({kind:`toolCalls`,toolCalls:e.map(e=>({name:e.name,args:e.args,id:e.id??lk(),type:`tool_call`}))}),this}alwaysThrow(e){return this._alwaysThrowError=e,this}structuredResponse(e){return this._structuredResponseValue=e,this}bindTools(t){let n=[...this._tools,...t],r=new e;return r.queue=this.queue,r._alwaysThrowError=this._alwaysThrowError,r._structuredResponseValue=this._structuredResponseValue,r._tools=n,r._state=this._state,r.withConfig({})}withStructuredOutput(e,t){let{_structuredResponseValue:n}=this;return jx.from(async()=>n)}async _generate(e,t,n){this._state.calls.push({messages:[...e],options:t});let r=this._state.callIndex;if(this._state.callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let i=this.queue[r];if(!i)throw Error(`FakeModel: no response queued for invocation ${r} (${this.queue.length} total queued).`);if(i.kind===`error`)throw i.error;if(i.kind===`factory`){let t=i.factory(e);if(!rt.isInstance(t))throw t;return{generations:[{text:``,message:t}]}}if(i.kind===`message`)return{generations:[{text:``,message:i.message}]};let a=sk(e);return{generations:[{text:a,message:new $t({content:a,id:r.toString(),tool_calls:i.toolCalls.length>0?i.toolCalls.map(e=>({...e,type:`tool_call`})):void 0})}],llmOutput:{}}}};function dk(){return new uk}function fk(e){return{async*[Symbol.asyncIterator](){for(let t of e)yield t}}}function pk(e=`test-model`){let t=mk(e),n=t[t.length-1];return t[t.length-1]={...n,usage:{prompt_tokens:10,completion_tokens:2,total_tokens:12}},t}function mk(e=`test-model`){return[{id:`chatcmpl-text`,model:e,choices:[{index:0,delta:{role:`assistant`,content:`Hello`},finish_reason:null}]},{id:`chatcmpl-text`,model:e,choices:[{index:0,delta:{content:` world`},finish_reason:null}]},{id:`chatcmpl-text`,model:e,choices:[{index:0,delta:{},finish_reason:`stop`}]}]}function hk(e=`test-model`){return[{id:`chatcmpl-reason`,model:e,choices:[{index:0,delta:{role:`assistant`,reasoning_content:`Let me reason...`},finish_reason:null}]},{id:`chatcmpl-reason`,model:e,choices:[{index:0,delta:{content:`Answer.`},finish_reason:null}]},{id:`chatcmpl-reason`,model:e,choices:[{index:0,delta:{},finish_reason:`stop`}]}]}function gk(e=`test-model`){return[{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{role:`assistant`,content:`Let me search.`},finish_reason:null}]},{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{tool_calls:[{index:0,id:`call_abc`,type:`function`,function:{name:`web_search`,arguments:`{"query"`}}]},finish_reason:null}]},{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{tool_calls:[{index:0,function:{arguments:`:"weather"}`}}]},finish_reason:null}]},{id:`chatcmpl-tools`,model:e,choices:[{index:0,delta:{},finish_reason:`tool_calls`}]}]}function _k(e){let t=new TextEncoder;return new Response(new ReadableStream({start(n){for(let r of e)n.enqueue(t.encode(`data: ${JSON.stringify(r)}\n\n`));n.close()}}),{status:200,headers:{"Content-Type":`text/event-stream`}})}var vk=s({FakeBuiltModel:()=>uk,asAsyncIterable:()=>fk,fakeModel:()=>dk,langchainMatchers:()=>ok,openAIReasoningTextChunks:()=>hk,openAITextOnlyChunks:()=>mk,openAITextOnlyChunksWithUsage:()=>pk,openAIToolCallChunks:()=>gk,sseResponseFromOpenAIChunks:()=>_k,streamMatchers:()=>qO,toBeAIMessage:()=>ZO,toBeHumanMessage:()=>XO,toBeSystemMessage:()=>QO,toBeToolMessage:()=>$O,toContainToolCall:()=>nk,toHaveBeenInterrupted:()=>ik,toHaveStructuredResponse:()=>ak,toHaveToolCallCount:()=>tk,toHaveToolCalls:()=>ek,toHaveToolMessages:()=>rk});function yk(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function bk(e){return e!==void 0&&Cx.isRunnable(e)&&`lc_name`in e.constructor&&typeof e.constructor.lc_name==`function`&&e.constructor.lc_name()===`RunnableToolLike`}function xk(e){return!!e&&typeof e==`object`&&`name`in e&&`schema`in e&&(t_(e.schema)||e.schema!=null&&typeof e.schema==`object`&&`type`in e.schema&&typeof e.schema.type==`string`&&[`null`,`boolean`,`object`,`array`,`number`,`string`].includes(e.schema.type))}function Sk(e){return xk(e)||bk(e)||yk(e)}var Ck=A(`ZodISODateTime`,(e,t)=>{Kp.init(e,t),Yk.init(e,t)});function wk(e){return Ch(Ck,e)}var Tk=A(`ZodISODate`,(e,t)=>{qp.init(e,t),Yk.init(e,t)});function Ek(e){return wh(Tk,e)}var Dk=A(`ZodISOTime`,(e,t)=>{Jp.init(e,t),Yk.init(e,t)});function Ok(e){return Th(Dk,e)}var kk=A(`ZodISODuration`,(e,t)=>{Yp.init(e,t),Yk.init(e,t)});function Ak(e){return Eh(kk,e)}var jk=A(`ZodError`,(e,t)=>{mf.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>_f(e,t)},flatten:{value:t=>gf(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jd,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jd,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Mk=bf(jk),Nk=Sf(jk),Pk=wf(jk),Fk=Ef(jk),Ik=Of(jk),Lk=kf(jk),Rk=Af(jk),zk=jf(jk),Bk=Mf(jk),Vk=Nf(jk),Hk=Pf(jk),Uk=Ff(jk),Wk=new WeakMap;function Gk(e,t,n){let r=Object.getPrototypeOf(e),i=Wk.get(r);if(i||(i=new Set,Wk.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Kk=A(`ZodType`,(e,t)=>(Mp.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ug(e,`input`),output:ug(e,`output`)}}),e.toJSONSchema=lg(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Mk(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Pk(e,t,n),e.parseAsync=async(t,n)=>Nk(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Fk(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ik(e,t,n),e.decode=(t,n)=>Lk(e,t,n),e.encodeAsync=async(t,n)=>Rk(e,t,n),e.decodeAsync=async(t,n)=>zk(e,t,n),e.safeEncode=(t,n)=>Bk(e,t,n),e.safeDecode=(t,n)=>Vk(e,t,n),e.safeEncodeAsync=async(t,n)=>Hk(e,t,n),e.safeDecodeAsync=async(t,n)=>Uk(e,t,n),Gk(e,`ZodType`,{check(...e){let t=this.def;return this.clone(zd(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Yd(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(fj(e,t))},superRefine(e,t){return this.check(pj(e,t))},overwrite(e){return this.check(qh(e))},optional(){return qA(this)},exactOptional(){return YA(this)},nullable(){return ZA(this)},nullish(){return qA(ZA(this))},nonoptional(e){return rj(this,e)},array(){return OA(this)},or(e){return jA([this,e])},and(e){return FA(this,e)},transform(e){return sj(this,GA(e))},default(e){return $A(this,e)},prefault(e){return tj(this,e)},catch(e){return aj(this,e)},pipe(e){return sj(this,e)},readonly(){return lj(this)},describe(e){let t=this.clone();return $m.add(t,{description:e}),t},meta(...e){if(e.length===0)return $m.get(this);let t=this.clone();return $m.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return $m.get(e)?.description},configurable:!0}),e)),qk=A(`_ZodString`,(e,t)=>{Np.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fg(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Gk(e,`_ZodString`,{regex(...e){return this.check(Vh(...e))},includes(...e){return this.check(Wh(...e))},startsWith(...e){return this.check(Gh(...e))},endsWith(...e){return this.check(Kh(...e))},min(...e){return this.check(zh(...e))},max(...e){return this.check(Rh(...e))},length(...e){return this.check(Bh(...e))},nonempty(...e){return this.check(zh(1,...e))},lowercase(e){return this.check(Hh(e))},uppercase(e){return this.check(Uh(e))},trim(){return this.check(Yh())},normalize(...e){return this.check(Jh(...e))},toLowerCase(){return this.check(Xh())},toUpperCase(){return this.check(Zh())},slugify(){return this.check(Qh())}})}),Jk=A(`ZodString`,(e,t)=>{Np.init(e,t),qk.init(e,t),e.email=t=>e.check(th(Xk,t)),e.url=t=>e.check(sh($k,t)),e.jwt=t=>e.check(Sh(mA,t)),e.emoji=t=>e.check(ch(eA,t)),e.guid=t=>e.check(nh(Zk,t)),e.uuid=t=>e.check(rh(Qk,t)),e.uuidv4=t=>e.check(ih(Qk,t)),e.uuidv6=t=>e.check(ah(Qk,t)),e.uuidv7=t=>e.check(oh(Qk,t)),e.nanoid=t=>e.check(lh(tA,t)),e.guid=t=>e.check(nh(Zk,t)),e.cuid=t=>e.check(uh(nA,t)),e.cuid2=t=>e.check(dh(rA,t)),e.ulid=t=>e.check(fh(iA,t)),e.base64=t=>e.check(yh(dA,t)),e.base64url=t=>e.check(bh(fA,t)),e.xid=t=>e.check(ph(aA,t)),e.ksuid=t=>e.check(mh(oA,t)),e.ipv4=t=>e.check(hh(sA,t)),e.ipv6=t=>e.check(gh(cA,t)),e.cidrv4=t=>e.check(_h(lA,t)),e.cidrv6=t=>e.check(vh(uA,t)),e.e164=t=>e.check(xh(pA,t)),e.datetime=t=>e.check(wk(t)),e.date=t=>e.check(Ek(t)),e.time=t=>e.check(Ok(t)),e.duration=t=>e.check(Ak(t))});function z(e){return eh(Jk,e)}var Yk=A(`ZodStringFormat`,(e,t)=>{Pp.init(e,t),qk.init(e,t)}),Xk=A(`ZodEmail`,(e,t)=>{Lp.init(e,t),Yk.init(e,t)}),Zk=A(`ZodGUID`,(e,t)=>{Fp.init(e,t),Yk.init(e,t)}),Qk=A(`ZodUUID`,(e,t)=>{Ip.init(e,t),Yk.init(e,t)}),$k=A(`ZodURL`,(e,t)=>{Rp.init(e,t),Yk.init(e,t)}),eA=A(`ZodEmoji`,(e,t)=>{zp.init(e,t),Yk.init(e,t)}),tA=A(`ZodNanoID`,(e,t)=>{Bp.init(e,t),Yk.init(e,t)}),nA=A(`ZodCUID`,(e,t)=>{Vp.init(e,t),Yk.init(e,t)}),rA=A(`ZodCUID2`,(e,t)=>{Hp.init(e,t),Yk.init(e,t)}),iA=A(`ZodULID`,(e,t)=>{Up.init(e,t),Yk.init(e,t)}),aA=A(`ZodXID`,(e,t)=>{Wp.init(e,t),Yk.init(e,t)}),oA=A(`ZodKSUID`,(e,t)=>{Gp.init(e,t),Yk.init(e,t)}),sA=A(`ZodIPv4`,(e,t)=>{Xp.init(e,t),Yk.init(e,t)}),cA=A(`ZodIPv6`,(e,t)=>{Zp.init(e,t),Yk.init(e,t)}),lA=A(`ZodCIDRv4`,(e,t)=>{Qp.init(e,t),Yk.init(e,t)}),uA=A(`ZodCIDRv6`,(e,t)=>{$p.init(e,t),Yk.init(e,t)}),dA=A(`ZodBase64`,(e,t)=>{tm.init(e,t),Yk.init(e,t)}),fA=A(`ZodBase64URL`,(e,t)=>{rm.init(e,t),Yk.init(e,t)}),pA=A(`ZodE164`,(e,t)=>{im.init(e,t),Yk.init(e,t)}),mA=A(`ZodJWT`,(e,t)=>{om.init(e,t),Yk.init(e,t)}),hA=A(`ZodNumber`,(e,t)=>{sm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pg(e,t,n,r),Gk(e,`ZodNumber`,{gt(e,t){return this.check(Fh(e,t))},gte(e,t){return this.check(Ih(e,t))},min(e,t){return this.check(Ih(e,t))},lt(e,t){return this.check(Nh(e,t))},lte(e,t){return this.check(Ph(e,t))},max(e,t){return this.check(Ph(e,t))},int(e){return this.check(vA(e))},safe(e){return this.check(vA(e))},positive(e){return this.check(Fh(0,e))},nonnegative(e){return this.check(Ih(0,e))},negative(e){return this.check(Nh(0,e))},nonpositive(e){return this.check(Ph(0,e))},multipleOf(e,t){return this.check(Lh(e,t))},step(e,t){return this.check(Lh(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function gA(e){return Dh(hA,e)}var _A=A(`ZodNumberFormat`,(e,t)=>{cm.init(e,t),hA.init(e,t)});function vA(e){return Oh(_A,e)}var yA=A(`ZodBoolean`,(e,t)=>{lm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mg(e,t,n,r)});function bA(e){return kh(yA,e)}var xA=A(`ZodAny`,(e,t)=>{um.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function SA(){return Ah(xA)}var CA=A(`ZodUnknown`,(e,t)=>{dm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function wA(){return jh(CA)}var TA=A(`ZodNever`,(e,t)=>{fm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bg(e,t,n,r)});function EA(e){return Mh(TA,e)}var DA=A(`ZodArray`,(e,t)=>{mm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fg(e,t,n,r),e.element=t.element,Gk(e,`ZodArray`,{min(e,t){return this.check(zh(e,t))},nonempty(e){return this.check(zh(1,e))},max(e,t){return this.check(Rh(e,t))},length(e,t){return this.check(Bh(e,t))},unwrap(){return this.element}})});function OA(e,t){return $h(DA,e,t)}var kA=A(`ZodObject`,(e,t)=>{ym.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ig(e,t,n,r),Ld(e,`shape`,()=>t.shape),Gk(e,`ZodObject`,{keyof(){return VA(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:wA()})},loose(){return this.clone({...this._zod.def,catchall:wA()})},strict(){return this.clone({...this._zod.def,catchall:EA()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return ef(this,e)},safeExtend(e){return tf(this,e)},merge(e){return nf(this,e)},pick(e){return Qd(this,e)},omit(e){return $d(this,e)},partial(...e){return rf(KA,this,e[0])},required(...e){return af(nj,this,e[0])}})});function B(e,t){return new kA({type:`object`,shape:e??{},...j(t)})}var AA=A(`ZodUnion`,(e,t)=>{xm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lg(e,t,n,r),e.options=t.options});function jA(e,t){return new AA({type:`union`,options:e,...j(t)})}var MA=A(`ZodDiscriminatedUnion`,(e,t)=>{AA.init(e,t),Sm.init(e,t)});function NA(e,t,n){return new MA({type:`union`,options:t,discriminator:e,...j(n)})}var PA=A(`ZodIntersection`,(e,t)=>{Cm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rg(e,t,n,r)});function FA(e,t){return new PA({type:`intersection`,left:e,right:t})}var IA=A(`ZodTuple`,(e,t)=>{Em.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zg(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function LA(e,t,n){let r=t instanceof Mp;return new IA({type:`tuple`,items:e,rest:r?t:null,...j(r?n:t)})}var RA=A(`ZodRecord`,(e,t)=>{Am.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bg(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function zA(e,t,n){return!t||!t._zod?new RA({type:`record`,keyType:z(),valueType:e,...j(t)}):new RA({type:`record`,keyType:e,valueType:t,...j(n)})}var BA=A(`ZodEnum`,(e,t)=>{jm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wg(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new BA({...t,checks:[],...j(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new BA({...t,checks:[],...j(r),entries:i})}});function VA(e,t){return new BA({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...j(t)})}var HA=A(`ZodLiteral`,(e,t)=>{Mm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tg(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function UA(e,t){return new HA({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}var WA=A(`ZodTransform`,(e,t)=>{Nm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mg(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Dd(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ff(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(ff(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function GA(e){return new WA({type:`transform`,transform:e})}var KA=A(`ZodOptional`,(e,t)=>{Fm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qA(e){return new KA({type:`optional`,innerType:e})}var JA=A(`ZodExactOptional`,(e,t)=>{Im.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function YA(e){return new JA({type:`optional`,innerType:e})}var XA=A(`ZodNullable`,(e,t)=>{Lm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ZA(e){return new XA({type:`nullable`,innerType:e})}var QA=A(`ZodDefault`,(e,t)=>{Rm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $A(e,t){return new QA({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kd(t)}})}var ej=A(`ZodPrefault`,(e,t)=>{Bm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tj(e,t){return new ej({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Kd(t)}})}var nj=A(`ZodNonOptional`,(e,t)=>{Vm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rj(e,t){return new nj({type:`nonoptional`,innerType:e,...j(t)})}var ij=A(`ZodCatch`,(e,t)=>{Um.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function aj(e,t){return new ij({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var oj=A(`ZodPipe`,(e,t)=>{Wm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kg(e,t,n,r),e.in=t.in,e.out=t.out});function sj(e,t){return new oj({type:`pipe`,in:e,out:t})}var cj=A(`ZodReadonly`,(e,t)=>{Km.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function lj(e){return new cj({type:`readonly`,innerType:e})}var uj=A(`ZodCustom`,(e,t)=>{Jm.init(e,t),Kk.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ag(e,t,n,r)});function dj(e,t){return eg(uj,e??(()=>!0),t)}function fj(e,t={}){return tg(uj,e,t)}function pj(e,t){return ng(e,t)}var mj=s({BaseToolkit:()=>yj,DynamicStructuredTool:()=>vj,DynamicTool:()=>_j,StructuredTool:()=>hj,Tool:()=>gj,ToolInputParsingException:()=>v,isLangChainTool:()=>Sk,isRunnableToolLike:()=>bk,isStructuredTool:()=>yk,isStructuredToolParams:()=>xk,tool:()=>bj}),hj=class extends mT{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return[`langchain`,`tools`]}responseFormat=`content`;defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let n,r=Zl(Xl(this.defaultConfig,t));return g(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){let r=g(e)?e.args:e,i;if(t_(this.schema))try{i=await o_(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),k_(t)&&(n=`${n}\n\n${yf(t)}`),new v(n,JSON.stringify(e))}else{let t=nx(r,this.schema);if(!t.valid){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.errors.map(e=>`${e.keywordLocation}: ${e.error}`).join(`
|
|
176
176
|
`)}`),new v(n,JSON.stringify(e))}i=r}let a=Ml(t),o=zl.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),s;g(e)&&(s=e.id),!s&&_(a)&&(s=a.toolCall.id);let c=await o?.handleToolStart(this.toJSON(),typeof e==`string`?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,s);delete a.runId;let l;try{let e=await this._call(i,c,a);l=vx(e)?await yx(e,async e=>{try{await c?.handleToolEvent(e)}catch(e){await c?.handleToolError(e)}}):e}catch(e){throw await c?.handleToolError(e),e}let u,d;if(this.responseFormat===`content_and_artifact`)if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(l)}`);else u=l;let f=Sj({content:u,artifact:d,toolCallId:s,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},gj=class extends hj{schema=xy({input:yy().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let n=typeof e==`string`||e==null?{input:e}:e;return super.call(n,t)}},_j=class extends gj{static lc_name(){return`DynamicTool`}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let n=Ml(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,t,n){return this.func(e,t,n)}},vj=class extends hj{static lc_name(){return`DynamicStructuredTool`}description;func;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,t,n){let r=Ml(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}},yj=class{getTools(){return this.tools}};function bj(e,t){let n=d_(t.schema),r=sx(t.schema);if(!t.schema||n||r)return new _j({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise((i,a)=>{let o=Ql(r,{callbacks:n?.getChild()});Wl.runWithConfig($l(o),async()=>{try{i(e(t,o))}catch(e){a(e)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new vj({...t,description:a,schema:i,func:async(t,n,r)=>new Promise((i,a)=>{let o,s=()=>{r?.signal&&o&&r.signal.removeEventListener(`abort`,o)};r?.signal&&(o=()=>{s(),a(tu(r.signal))},r.signal.addEventListener(`abort`,o,{once:!0}));let c=Ql(r,{callbacks:n?.getChild()});Wl.runWithConfig($l(c),async()=>{try{let n=await e(t,c);if(vx(n)){i(n);return}if(r?.signal?.aborted){s();return}s(),i(n)}catch(e){s(),a(e)}})})})}function xj(e){return typeof e==`object`&&!!e&&`type`in e}function Sj(e){let{content:t,artifact:n,toolCallId:r,metadata:i}=e;return r&&!bt(t)?typeof t==`string`||Array.isArray(t)&&t.every(xj)?new xt({status:`success`,content:t,artifact:n,tool_call_id:r,name:e.name,metadata:i}):new xt({status:`success`,content:Cj(t),artifact:n,tool_call_id:r,name:e.name,metadata:i}):t}function Cj(e){try{return JSON.stringify(e)??``}catch{return`${e}`}}var wj=s({RunCollectorCallbackHandler:()=>Tj}),Tj=class extends Yc{name=`run_collector`;exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},Ej=s({}),Dj=s({chunkArray:()=>Oj}),Oj=(e,t)=>e.reduce((e,n,r)=>{let i=Math.floor(r/t);return e[i]=(e[i]||[]).concat([n]),e},[]),kj=s({context:()=>Aj});function Aj(e,...t){let n=e.raw,r=``;for(let e=0;e<n.length;e++){let i=n[e].replace(/\\\n[ \t]*/g,``).replace(/\\`/g,"`").replace(/\\\$/g,`$`).replace(/\\\{/g,`{`);if(r+=i,e<t.length){let n=jj(t[e],r);r+=typeof n==`string`?n:JSON.stringify(n)}}return r=Mj(r),r=r.trim(),r=r.replace(/\\n/g,`
|
|
177
177
|
`),r}function jj(e,t){if(typeof e!=`string`||!e.includes(`
|
|
178
178
|
`))return e;let n=t.slice(t.lastIndexOf(`
|
|
@@ -181,17 +181,17 @@ Here are the output tags:
|
|
|
181
181
|
`)}var Nj=s({EventStreamContentType:()=>Pj,convertEventStreamToIterableReadableDataStream:()=>Bj,getBytes:()=>Fj,getLines:()=>Ij,getMessages:()=>Lj}),Pj=`text/event-stream`;async function Fj(e,t){if(e instanceof ReadableStream){let n=e.getReader();for(;;){let e=await n.read();if(e.done){t(new Uint8Array,!0);break}t(e.value)}}else try{for await(let n of e)t(new Uint8Array(n));t(new Uint8Array,!0)}catch(e){throw Error([`Parsing event source stream failed.`,`Ensure your implementation of fetch returns a web or Node readable stream.`,`Error: ${e.message}`].join(`
|
|
182
182
|
`))}}function Ij(e){let t,n,r,i=!1;return function(a,o){if(o){e(a,0,!0);return}t===void 0?(t=a,n=0,r=-1):t=Rj(t,a);let s=t.length,c=0;for(;n<s;){i&&=(t[n]===10&&(c=++n),!1);let a=-1;for(;n<s&&a===-1;++n)switch(t[n]){case 58:r===-1&&(r=n-c);break;case 13:i=!0;case 10:a=n;break}if(a===-1)break;e(t.subarray(c,a),r),c=n,r=-1}c===s?t=void 0:c!==0&&(t=t.subarray(c),n-=c)}}function Lj(e,t,n){let r=zj(),i=new TextDecoder;return function(a,o,s){if(s){Vj(r)||(e?.(r),r=zj());return}if(a.length===0)e?.(r),r=zj();else if(o>0){let e=i.decode(a.subarray(0,o)),s=o+(a[o+1]===32?2:1),c=i.decode(a.subarray(s));switch(e){case`data`:r.data=r.data?r.data+`
|
|
183
183
|
`+c:c;break;case`event`:r.event=c;break;case`id`:t?.(r.id=c);break;case`retry`:{let e=parseInt(c,10);Number.isNaN(e)||n?.(r.retry=e);break}}}}}function Rj(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function zj(){return{data:``,event:``,id:``,retry:void 0}}function Bj(e,t){let n=new ReadableStream({async start(n){let r=Lj(e=>{if(e.event===`error`)throw Error(e.data??`Unspecified event streaming error.`);e.event===`metadata`?t?.(e):e.data&&n.enqueue(e.data)});await Fj(e,Ij((e,t,i)=>{r(e,t,i),i&&n.close()}))}});return ru.fromReadableStream(n)}function Vj(e){return e.data===``&&e.event===``&&e.id===``&&e.retry===void 0}var Hj=s({}),Uj=s({convertToOpenAIFunction:()=>Wj,convertToOpenAITool:()=>Gj,isLangChainTool:()=>Sk,isRunnableToolLike:()=>bk,isStructuredTool:()=>yk,isStructuredToolParams:()=>xk});function Wj(e,t){let n=typeof t==`number`?void 0:t;return{name:e.name,description:e.description,parameters:ox(e.schema),...n?.strict===void 0?{}:{strict:n.strict}}}function Gj(e,t){let n=typeof t==`number`?void 0:t,r;return r=Sk(e)?{type:`function`,function:Wj(e)}:e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function Kj(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(i))}function qj(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function Jj(e,t){let n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t[r])*(e[r]-t[r]);return n}function Yj(e,t){return Math.sqrt(Jj(e,t))}var Xj=s({cosineSimilarity:()=>$j,euclideanDistance:()=>tM,innerProduct:()=>eM,matrixFunc:()=>Zj,maximalMarginalRelevance:()=>nM,normalize:()=>Qj});function Zj(e,t,n){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(e=>t.map(t=>n(e,t)).map(e=>Number.isNaN(e)?0:e))}function Qj(e,t=!1){let n=iM(e);return e.map(e=>e.map(e=>t?1-e/n:e/n))}function $j(e,t){return Zj(e,t,Kj)}function eM(e,t){return Zj(e,t,qj)}function tM(e,t){return Zj(e,t,Yj)}function nM(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let i=$j(Array.isArray(e[0])?e:[e],t)[0],a=rM(i).maxIndex,o=[t[a]],s=[a];for(;s.length<Math.min(r,t.length);){let e=-1/0,r=-1,a=$j(t,o);i.forEach((t,i)=>{if(s.includes(i))return;let o=Math.max(...a[i]),c=n*t-(1-n)*o;c>e&&(e=c,r=i)}),o.push(t[r]),s.push(r)}return s}function rM(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r<e.length;r+=1)e[r]>t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}function iM(e){return e.reduce((e,t)=>Math.max(e,rM(t).maxValue),0)}var aM=s({isCloudMetadata:()=>yM,isLocalhost:()=>bM,isPrivateIp:()=>vM,isSafeUrl:()=>SM,isSameOrigin:()=>CM,validateSafeUrl:()=>xM}),oM=[`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`],sM=[`169.254.169.254`,`169.254.170.2`,`100.100.100.200`],cM=[`metadata.google.internal`,`metadata`,`instance-data`],lM=[`localhost`,`localhost.localdomain`],uM=/^(?:(?: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 dM(e){return uM.test(e)}function fM(e){return hM(e)!==null}function pM(e){return dM(e)||fM(e)}function mM(e){if(dM(e))return e.split(`.`).map(e=>parseInt(e,10));if(fM(e)){let t=hM(e);if(!t)return null;let n=t.split(`:`),r=[];for(let e of n)r.push(parseInt(e,16));return r}return null}function hM(e){if(!e||typeof e!=`string`||!e.includes(`:`)||!/^[0-9a-fA-F:]+$/.test(e))return null;let t=e;if(t.includes(`::`)){let e=t.split(`::`);if(e.length>2)return null;let[n,r]=e,i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=8-(i.length+a.length);if(o<0)return null;let s=Array(o).fill(`0`);t=[...i,...s,...a].filter(e=>e!==``).join(`:`)}let n=t.split(`:`);if(n.length!==8)return null;for(let e of n)if(e.length===0||e.length>4||!/^[0-9a-fA-F]+$/.test(e))return null;return n.map(e=>e.padStart(4,`0`).toLowerCase()).join(`:`)}function gM(e){let[t,n]=e.split(`/`);if(!t||!n)return null;let r=mM(t);if(!r)return null;let i=parseInt(n,10);if(isNaN(i))return null;let a=fM(t);return a&&i>128||!a&&i>32?null:{addr:r,prefixLen:i,isIpv6:a}}function _M(e,t){let n=mM(e);if(!n)return!1;let r=gM(t);if(!r)return!1;let i=fM(e);if(i!==r.isIpv6)return!1;let{addr:a,prefixLen:o}=r;if(i)for(let e=0;e<Math.ceil(o/16);e++){let t=65535<<16-Math.min(16,o-e*16)&65535;if((n[e]&t)!==(a[e]&t))return!1}else for(let e=0;e<Math.ceil(o/8);e++){let t=255<<8-Math.min(8,o-e*8)&255;if((n[e]&t)!==(a[e]&t))return!1}return!0}function vM(e){if(!pM(e))return!1;for(let t of oM)if(_M(e,t))return!0;return!1}function yM(e,t){if(sM.includes(t||``))return!0;let n=e.toLowerCase();return!!cM.includes(n)}function bM(e,t){if(t&&(t===`127.0.0.1`||t===`::1`||t===`0.0.0.0`||t.startsWith(`127.`)))return!0;let n=e.toLowerCase();return!!lM.includes(n)}function xM(e,t){let n=t?.allowPrivate??!1,r=t?.allowHttp??!1;try{let t;try{t=new URL(e)}catch{throw Error(`Invalid URL: ${e}`)}let i=t.hostname;if(!i)throw Error(`URL missing hostname.`);if(yM(i))throw Error(`URL points to cloud metadata endpoint: ${i}`);if(bM(i)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}let a=t.protocol;if(a!==`http:`&&a!==`https:`)throw Error(`Invalid URL scheme: ${a}. Only http and https are allowed.`);if(a===`http:`&&!r)throw Error(`HTTP scheme not allowed. Use HTTPS or set allowHttp: true.`);if(pM(i)){let t=i;if(bM(i,t)){if(!n)throw Error(`URL points to localhost: ${i}`);return e}if(yM(i,t))throw Error(`URL resolves to cloud metadata IP: ${t} (${i})`);if(vM(t)&&!n)throw Error(`URL resolves to private IP: ${t} (${i}). Set allowPrivate: true to allow.`);return e}return e}catch(e){throw e&&typeof e==`object`&&`message`in e?e:Error(`URL validation failed: ${e}`)}}function SM(e,t){try{return xM(e,t),!0}catch{return!1}}function CM(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}var wM=s({SaveableVectorStore:()=>DM,VectorStore:()=>EM,VectorStoreRetriever:()=>TM}),TM=class extends fO{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},EM=class extends ve{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new TM({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new TM({...t,searchKwargs:e.searchKwargs}):new TM({...t})}}},DM=class extends EM{static load(e,t){throw Error(`Not implemented`)}},OM=class extends EE{_combineLLMOutput(){return[]}_llmType(){return`fake`}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new $t(t.stop[0]),text:t.stop[0]}]};let r=e.map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content,null,2)).join(`
|
|
184
|
-
`);return await n?.handleLLMNewToken(r),{generations:[{message:new $t(r),text:r}],llmOutput:{}}}},kM=class e extends EE{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:ox(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:ox(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:ox(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:ox(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new $t({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new Uu({message:new nn({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new $t(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new Uu({message:new nn({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},AM=class e extends EE{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new $t(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new Uu({message:new nn({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:ox(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:ox(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:ox(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:ox(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return jx.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},jM=class extends xw{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},MM=class extends xw{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},NM=class extends RE{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},PM=class extends RE{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},FM=class extends cw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new fn(e))}async addAIMessage(e){this.messages.push(new $t(e))}async clear(){this.messages=[]}},IM=class extends lw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},LM=class extends Yc{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},RM=class extends vT{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},zM=class extends fO{lc_namespace=[`test`,`fake`];output=[new dw({pageContent:`foo`}),new dw({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},BM=class extends Cx{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},VM=class extends hj{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},HM=class extends Yc{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},UM=class e extends EM{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??Kj}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>n?n(new dw({metadata:e.metadata,pageContent:e.content})):!0);return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new dw({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new dw({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},WM=s({FakeChatMessageHistory:()=>FM,FakeChatModel:()=>OM,FakeEmbeddings:()=>MM,FakeLLM:()=>NM,FakeListChatMessageHistory:()=>IM,FakeListChatModel:()=>AM,FakeRetriever:()=>zM,FakeRunnable:()=>BM,FakeSplitIntoListParser:()=>RM,FakeStreamingChatModel:()=>kM,FakeStreamingLLM:()=>PM,FakeTool:()=>VM,FakeTracer:()=>LM,FakeVectorStore:()=>UM,SingleRunExtractor:()=>HM,SyntheticEmbeddings:()=>jM,asAsyncIterable:()=>fk,openAIReasoningTextChunks:()=>hk,openAITextOnlyChunks:()=>mk,openAITextOnlyChunksWithUsage:()=>pk,openAIToolCallChunks:()=>gk,sseResponseFromOpenAIChunks:()=>_k,streamMatchers:()=>qO}),GM=s({agents:()=>KC,caches:()=>ew,callbacks__base:()=>Fr,callbacks__manager:()=>jl,callbacks__promises:()=>El,chat_history:()=>sw,document_loaders__base:()=>hw,document_loaders__langsmith:()=>_w,documents:()=>mw,embeddings:()=>bw,errors:()=>u,example_selectors:()=>jw,index:()=>GC,indexing:()=>Bw,language_models__base:()=>sT,language_models__chat_models:()=>wE,language_models__compat:()=>dE,language_models__event:()=>FE,language_models__llms:()=>IE,language_models__openai_completions_stream:()=>OE,language_models__profile:()=>zE,language_models__stream:()=>ZT,language_models__structured_output:()=>qT,load__serializable:()=>me,memory:()=>BE,messages:()=>iS,messages__tool:()=>yt,output_parsers:()=>BT,output_parsers__openai_functions:()=>YE,output_parsers__openai_tools:()=>XE,outputs:()=>Bu,prompt_values:()=>Vw,prompts:()=>cO,retrievers:()=>dO,retrievers__document_compressors:()=>lO,runnables:()=>oS,runnables__graph:()=>cx,singletons:()=>Gl,stores:()=>pO,structured_query:()=>PO,testing:()=>vk,tools:()=>mj,tracers__base:()=>Wc,tracers__console:()=>Xc,tracers__log_stream:()=>Mu,tracers__run_collector:()=>wj,tracers__tracer_langchain:()=>fl,types__stream:()=>Ej,utils__async_caller:()=>id,utils__chunk_array:()=>Dj,utils__context:()=>kj,utils__env:()=>Tr,utils__event_source_parse:()=>Nj,utils__format:()=>Hj,utils__function_calling:()=>Uj,utils__hash:()=>$C,utils__json_patch:()=>gT,utils__json_schema:()=>ix,utils__math:()=>Xj,utils__ssrf:()=>aM,utils__standard_schema:()=>gb,utils__stream:()=>nu,utils__testing:()=>WM,utils__tiktoken:()=>nT,utils__types:()=>VT,utils__uuid:()=>pr,vectorstores:()=>wM}),KM=50;function qM(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function JM(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:i,secretsFromEnv:a,path:o,depth:s,maxDepth:c}=this,l=o.join(`.`);if(s>c)throw Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>JM.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(le(u))return pe(u);if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`secret`){let[e]=u.id;if(e in i)return i[e];if(a){let t=Pr(e);if(t)return t}throw Error(`Missing secret "${e}" at ${l}`)}if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`not_implemented`){let e=JSON.stringify(u);throw Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${e}`)}if(`lc`in u&&`type`in u&&`id`in u&&`kwargs`in u&&u.lc===1&&u.type===`constructor`){let e=u,i=JSON.stringify(e),[a,...c]=e.id.slice().reverse(),d=c.reverse(),f={langchain_core:GM,langchain:r},p=null,m=[d.join(`/`)];d[0]===`langchain_community`&&m.push([`langchain`,...d.slice(1)].join(`/`));let h=m.find(e=>e in t);if(WC.concat(n).includes(d.join(`/`))||h)if(h!==void 0)p=await t[h];else throw Error(`Missing key "${d.join(`/`)}" for ${l} in load(optionalImportsMap={})`);else{let e;if(d[0]===`langchain`||d[0]===`langchain_core`)e=f[d[0]],d.shift();else throw Error(`Invalid namespace: ${l} -> ${i}`);if(d.length===0)throw Error(`Invalid namespace: ${l} -> ${i}`);let t;do{if(t=d.join(`__`),t in e)break;d.pop()}while(d.length>0);t in e&&(p=e[t])}if(typeof p!=`object`||!p)throw Error(`Invalid namespace: ${l} -> ${i}`);let g=p[a]??Object.values(p).find(e=>typeof e==`function`&&_e(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(oe(await JM.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),ae,qM(g)));return Object.defineProperty(_.constructor,"name",{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await JM.call({...this,path:[...o,e],depth:s+1},t);return d}async function YM(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??KM};return JM.call(r,n)}function XM(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function ZM(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>ZM(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await ZM(r);if(t.lc===2&&t.type===`undefined`)return;if(t.lc===2&&t.type===`delta_snapshot`)return new NC(t.value);if(t.lc===2&&t.type===`constructor`&&Array.isArray(t.id))try{let e=t.id[t.id.length-1],n;switch(e){case`Set`:n=Set;break;case`Map`:n=Map;break;case`RegExp`:n=RegExp;break;case`Error`:n=Error;break;case`Uint8Array`:n=Uint8Array;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(XM(t))return YM(JSON.stringify(t));return t}}return e}function QM(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function $M(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof NC?{lc:2,type:`delta_snapshot`,value:e.value}:e instanceof Set||e instanceof Map?QM(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?QM(RegExp,void 0,[e.source,e.flags]):e instanceof Error?QM(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args,...e.timeout===void 0?{}:{timeout:e.timeout}}:e instanceof Uint8Array?QM(Uint8Array,`from`,[Array.from(e)]):e}var eN=class{_dumps(e){return new TextEncoder().encode(BC(e,(e,t)=>$M(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return ZM(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function tN(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=tN(e[n]));return t}function nN(){return{v:4,id:DC(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function rN(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values??{}},channel_versions:{...e.channel_versions??{}},versions_seen:tN(e.versions_seen??{})}}function iN(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function aN(...e){return e.reduce((e,t,n)=>n===0?t:iN(e,t)>=0?e:t)}var oN={[kC]:-1,[AC]:-2,[jC]:-3,[MC]:-4},sN=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`checkpoint_map`,`langgraph_step`,`langgraph_node`,`langgraph_triggers`,`langgraph_path`,`langgraph_checkpoint_ns`]),cN=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function lN(e){if(e.length===0)throw new cN(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new cN(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new cN(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new cN(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new cN(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var uN=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){lN(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},dN=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,fN=class extends uN{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=dN(e)}get isRunning(){return this.running}async batch(e){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},pN=class{serde=new eN;constructor(e){this.serde=e||this.serde}},mN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function hN(e){return e!=null&&e.lc_graph_name===`DeltaChannel`}function gN(e){return e!=null&&e.lg_is_channel===!0}var _N=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===xC.unminifiable_name)return!1;throw e}}equals(e){return this===e}},vN=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function yN(e){if(e[vN]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];gN(r)&&(t[n]=r)}return Object.assign(t,{[vN]:!0}),t}function bN(e,t){let n=yN(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[vN]:!0}),r}function xN(e,t){if(!mN.test(t))throw TypeError(`Invalid task id for exit delta: ${t}`);let n=t.toLowerCase().split(`-`);return`${String(e).padStart(8,`0`)}-${n[1]}-${n[2]}-${n[3]}-${n[4]}`}function SN(e,t){let n=new Set,r=hS();for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=e[i];if(!hN(a)||!a.isAvailable())continue;let[o,s]=t[i]??[0,0];(o>=a.snapshotFrequency||s>=r)&&n.add(i)}return n}function CN(e,t,n,r){let i=r?.channelsToSnapshot??new Set,{updatedChannels:a,getNextVersion:o}=r??{},s,c=e.channel_versions;if(t===void 0)s=e.channel_values;else{s={},c={...e.channel_versions};for(let e in t){if(!Object.prototype.hasOwnProperty.call(t,e))continue;let n=t[e];if(i.has(e)){o!==void 0&&(a===void 0||!a.has(e))&&(c[e]=o(c[e])),s[e]=new NC(n.get());continue}if(!hN(n))try{s[e]=n.checkpoint()}catch(e){if(e.name!==xC.unminifiable_name)throw e}}}return{v:4,id:r?.id??DC(n),ts:new Date().toISOString(),channel_values:s,channel_versions:c,versions_seen:e.versions_seen}}async function wN(e,t,n){let r=bN(e,t),{saver:i,config:a}=n??{},o=yN(e),s=[];for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&hN(o[e])&&!Object.prototype.hasOwnProperty.call(t.channel_values,e)&&s.push(e);if(s.length===0||i===void 0||a===void 0)return r;let c=await i.getDeltaChannelHistory({config:a,channels:s});for(let e of s){let t=c[e];if(t===void 0)continue;let n=o[e].fromCheckpoint(t.seed);n.replayWrites(t.writes),r[e]=n}return r}var TN=class e extends _N{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new SC(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new xC;return this.value[0]}checkpoint(){if(this.value.length===0)throw new xC;return this.value[0]}isAvailable(){return this.value.length!==0}},EN=class e extends _N{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new xC;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}},DN=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,ON=class e extends _N{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;if(this.value===void 0){let e=t[0],[n,r]=$S(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(eC(e)){if(n)throw new SC(`Can receive only one Overwrite value per step.`);let[,t]=$S(e);this.value=t,n=!0;continue}else !n&&this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new xC;return this.value}checkpoint(){if(this.value===void 0)throw new xC;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:DN(e)?this.operator===e.operator:!1}},kN=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},AN=function(e){return e?jN(e):new TN};AN.Root=e=>new kN(e);function jN(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new ON(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new ON(e.value,e.default):new TN}var MN=[`tags`,`metadata`,`callbacks`,`configurable`],NN=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`heartbeat`,`executionInfo`,`serverInfo`,`control`],PN=25,FN=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function IN(e,t){if(!e)return t;let n=t??{};for(let t of FN){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function LN(e){if(e==null||e.length===0)return;let t=e.filter(e=>!e.startsWith(`seq:step`));return t.length>0?t:void 0}function RN(e,t){if(t===void 0)return e;if(e===void 0)return Array.isArray(t)?[...t]:t.copy();if(Array.isArray(t)){if(Array.isArray(e))return e.concat(t);let n=e.copy();for(let e of t)n.addHandler(Bl(e),!0);return n}if(Array.isArray(e)){let n=t.copy();for(let t of e)n.addHandler(Bl(t),!0);return n}return new zl(t._parentRunId,{handlers:e.handlers.concat(t.handlers),inheritableHandlers:e.inheritableHandlers.concat(t.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(t.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(t.inheritableTags))),metadata:{...e.metadata,...t.metadata},inheritableMetadata:{...e.inheritableMetadata,...t.inheritableMetadata}})}function zN(e){let t;for(let n=e.length-1;n>=0;--n)if(e[n]!==void 0){t=e[n];break}let n=t?.configurable?.thread_id!==void 0,r=e.some(e=>e?.configurable?.[vS]!==void 0),i=Wl.getRunnableConfig()?.configurable?.[vS]!==void 0;return n&&!r&&!i}function BN(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:PN,configurable:{}},n=zN(e),r=Wl.getRunnableConfig();if(r!==void 0){for(let[e,i]of Object.entries(r))if(i!==void 0){if(e===`configurable`&&n)continue;if(MN.includes(e)){let n;n=Array.isArray(i)?[...i]:typeof i==`object`?e===`callbacks`&&`copy`in i&&typeof i.copy==`function`?i.copy():{...i}:i,t[e]=n}else t[e]=i}}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r===void 0||!NN.includes(e)||(e===`configurable`?t.configurable={...t.configurable,...r}:e===`metadata`?t.metadata={...t.metadata,...r}:e===`tags`?t.tags=[...t.tags??[],...r]:e===`callbacks`?t.callbacks=RN(t.callbacks,r):t[e]=r);return t.metadata=IN(t.configurable,t.metadata)??{},t}function VN(){return Wl.getRunnableConfig()}function HN(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function UN(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var WN=class extends Cx{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,i)=>{let a=Ql(t,{callbacks:n?.getChild()});Wl.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=BN(t),i=Xl(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await Wl.runWithConfig(i,async()=>this.func(e,i)),Cx.isRunnable(n)&&this.recurse?await Wl.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*GN(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function KN(e){let t=[];for await(let n of await e)t.push(n);return t}function qN(e){let t=[];for(let n of e)t.push(n);return t}function JN(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function YN(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var XN={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function ZN(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var QN=Symbol(`IS_WRITER`),$N=class e extends WN{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>ZS(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,trace:!1,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>tP(e)&&ZN(e.value)?{mapper:e.mapper,value:t}:eP(e)&&ZN(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(eP(e)){if(e.channel===`__pregel_tasks`)throw new SC(`Cannot write to the reserved channel TASKS`);if(ZN(e.value))throw new SC(`PASSTHROUGH value must be replaced`)}if(tP(e)&&ZN(e.value))throw new SC(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(ZS(r))n.push([HS,r]);else if(tP(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(eP(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(YN(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[gS];r(n)}static isWriter(t){return t instanceof e||QN in t&&!!t[QN]}static registerWriter(e){return Object.defineProperty(e,QN,{value:!0})}};function eP(e){return e!==void 0&&typeof e.channel==`string`}function tP(e){return e!==void 0&&!eP(e)&&Cx.isRunnable(e.mapper)}var nP=class e extends WN{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[vS];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},rP=new zx,iP=class e extends wx{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=rP;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;timeout;subgraphs;ends;isErrorHandler;errorHandlerNode;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,timeout:u,tags:d,subgraphs:f,ends:p,isErrorHandler:m,errorHandlerNode:h}=e,g=[...e.config?.tags?e.config.tags:[],...d??[]];super({...e,bound:e.bound??rP,config:{...e.config?e.config:{},tags:g}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=g,this.retryPolicy=c,this.cachePolicy=l,this.timeout=u,this.subgraphs=f,this.ends=p,this.isErrorHandler=m,this.errorHandlerNode=h}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof $N&&e[e.length-2]instanceof $N;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new $N(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===rP&&e.length===0))return this.bound===rP&&e.length===1?e[0]:this.bound===rP?new Dx({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Dx({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}pipe(t){return $N.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===rP?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Px(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function aP(e){let t=typeof e[lS];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function oP(e,t){if(Object.keys(e).length>0){let n=aP(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function sP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function cP(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function lP(e,t){let n=t?.parents??{};return Object.keys(n).length>0?cP(e,{[MS]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function uP(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}function dP(e){return`steps`in e&&Array.isArray(e.steps)}function fP(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function pP(e){let t=[e];for(let e of t)if(fP(e))return e;else dP(e)&&t.push(...e.steps)}var mP=class e extends _N{lc_graph_name=`EphemeralValue`;guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(t){let n=new e(this.guard);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0){let e=this.value.length>0;return this.value=[],e}if(e.length!==1&&this.guard)throw new SC(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new xC;return this.value[0]}checkpoint(){if(this.value.length===0)throw new xC;return this.value[0]}isAvailable(){return this.value.length!==0}},hP=class{#e=void 0;requestDrain(e=`shutdown`){this.#e=e}get drainRequested(){return this.#e!==void 0}get drainReason(){return this.#e}},V=e=>BigInt(e),gP=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),_P=V(`0x9E3779B1`),vP=V(`0x85EBCA77`),yP=V(`0xC2B2AE3D`),bP=V(`0x9E3779B185EBCA87`),xP=V(`0xC2B2AE3D27D4EB4F`),SP=V(`0x165667B19E3779F9`),CP=V(`0x85EBCA77C2B2AE63`),wP=V(`0x27D4EB2F165667C5`),TP=V(`0x165667919E3779F9`),EP=V(`0x9FB21C651E98DF25`),DP=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return gP(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),OP=(V(1)<<V(128))-V(1),kP=(V(1)<<V(64))-V(1),AP=(V(1)<<V(32))-V(1),jP=64,MP=jP/8,NP=8,PP=4;function FP(e){if(!e)throw Error(`Assert failed`)}function IP(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function LP(e){let t=e;return t=(t&V(65535))<<V(16)|(t&V(4294901760))>>V(16),t=(t&V(16711935))<<V(8)|(t&V(4278255360))>>V(8),t}function RP(e,t){return(e&AP)*(t&AP)&kP}function zP(e,t){return(e<<t|e>>V(32)-t)&AP}function BP(e,t,n){for(let r=0;r<MP;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=RP(a,a>>V(32))}return e}function VP(e,t,n,r){for(let i=0;i<r;i+=1)BP(e,gP(t,i*jP),gP(n,i*8));return e}function HP(e,t){for(let n=0;n<MP;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=$P(i,V(47)),i^=r,i*=_P,e[n]=i&kP}return e}function UP(e,t){return qP(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(NP,!0))}function WP(e,t,n){let r=n;return r+=UP(e.slice(0),gP(t,0*PP)),r+=UP(e.slice(2),gP(t,4*PP)),r+=UP(e.slice(4),gP(t,8*PP)),r+=UP(e.slice(6),gP(t,12*PP)),XP(r&kP)}function GP(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-jP)/8),s=jP*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=VP(a,gP(t,e*s),n,o),a=i(a,gP(n,n.byteLength-jP));{let e=Math.floor((t.byteLength-1-s*c)/jP);a=VP(a,gP(t,c*s),n,e),a=r(a,gP(t,t.byteLength-jP),gP(n,n.byteLength-jP-7))}return a}function KP(e,t){let n=new BigUint64Array([yP,bP,xP,SP,CP,vP,wP,_P]);FP(e.byteLength>128),n=GP(n,e,t,BP,HP),FP(n.length*8==64);{let r=WP(n,gP(t,11),V(e.byteLength)*bP&kP);return WP(n,gP(t,t.byteLength-jP-11),~(V(e.byteLength)*xP)&kP)<<V(64)|r}}function qP(e,t){let n=e*t&OP;return n&kP^n>>V(64)}function JP(e,t,n){return qP((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&kP,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&kP)}function YP(e,t,n,r,i){let a=e&kP,o=e>>V(64)&kP;return a+=JP(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=kP,o+=JP(n,gP(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=kP,o<<V(64)|a}function XP(e){let t=e;return t^=t>>V(37),t*=TP,t&=kP,t^=t>>V(32),t}function ZP(e){let t=e;return t^=t>>V(33),t*=xP,t&=kP,t^=t>>V(29),t*=SP,t&=kP,t^=t>>V(32),t}function QP(e,t,n){let r=e.byteLength;FP(r>0&&r<=3);let i=V(e.getUint8(r-1))|V(r<<8)|V(e.getUint8(0)<<16)|V(e.getUint8(r>>1)<<24),a=(i^(V(t.getUint32(0,!0))^V(t.getUint32(4,!0)))+n)&kP,o=(V(t.getUint32(8,!0))^V(t.getUint32(12,!0)))-n;return(ZP((zP(LP(i),V(13))^o)&kP)&kP)<<V(64)|ZP(a)}function $P(e,t){return e^e>>t}function eF(e,t,n){let r=e.byteLength;FP(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((V(i)|V(a)<<V(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&kP)*(bP+(V(r)<<V(2)))&OP;return o+=(o&kP)<<V(65),o&=OP,o^=o>>V(67),$P($P(o&kP,V(35))*EP&kP,V(28))|XP(o>>V(64))<<V(64)}}function tF(e,t,n){let r=e.byteLength;FP(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&kP,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&kP,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*bP,l=(c&kP)+(V(r-1)<<V(54));c=c&(OP^kP)|l,s^=a,c+=s+(s&AP)*(vP-V(1))<<V(64),c&=OP,c^=IP(c>>V(64));let u=(c&kP)*xP;return u+=(c>>V(64))*xP<<V(64),u&=OP,XP(u&kP)|XP(u>>V(64))<<V(64)}}function nF(e,t){let n=e.byteLength;return FP(n<=16),n>8?tF(e,DP,t):n>=4?eF(e,DP,t):n>0?QP(e,DP,t):ZP(t^DP.getBigUint64(64,!0)^DP.getBigUint64(72,!0))|ZP(t^DP.getBigUint64(80,!0)^DP.getBigUint64(88,!0))<<V(64)}function rF(e){return~e+V(1)&kP}function iF(e,t,n){let r=V(e.byteLength)*bP&kP,i=V(e.byteLength-1)/V(32);for(;i>=0;){let a=Number(i);r=YP(r,gP(e,16*a),gP(e,e.byteLength-16*(a+1)),gP(t,32*a),n),i-=V(1)}let a=r+(r>>V(64))&kP;a=XP(a);let o=(r&kP)*bP+(r>>V(64))*CP+(V(e.byteLength)-n&kP)*xP;return o&=kP,o=rF(XP(o)),a|o<<V(64)}function aF(e,t,n){let r=V(e.byteLength)*bP&kP;for(let i=32;i<160;i+=32)r=YP(r,gP(e,i-32),gP(e,i-16),gP(t,i-32),n);r=XP(r&kP)|XP(r>>V(64))<<V(64);for(let i=160;i<=e.byteLength;i+=32)r=YP(r,gP(e,i-32),gP(e,i-16),gP(t,3+i-160),n);r=YP(r,gP(e,e.byteLength-16),gP(e,e.byteLength-32),gP(t,103),rF(n));let i=r+(r>>V(64))&kP;i=XP(i);let a=(r&kP)*bP+(r>>V(64))*CP+(V(e.byteLength)-n&kP)*xP;return a&=kP,a=rF(XP(a)),i|a<<V(64)}function oF(e,t=V(0)){let n=new TextEncoder,r=gP(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?nF(r,t):i<=128?iF(r,DP,t):i<=240?aF(r,DP,t):KP(r,DP))}function sF(e){return/^[0-9a-f]{32}$/.test(e)}function cF(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===xC.unminifiable_name){if(r)return e;if(n)return null}throw e}}function lF(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=cF(e,i,!n)}catch(e){if(e.name===xC.unminifiable_name)continue}return r}else return cF(e,t)}function*uF(e,t){if(e.graph===nC.PARENT)throw new SC(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(ZS(e))yield[GS,HS,e];else if(typeof e==`string`)yield[GS,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(sF))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,IS,e]}else yield[GS,IS,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[GS,t,n];else for(let[t,n]of Object.entries(e.update))yield[GS,t,n]}}function*dF(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*fF(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield lF(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield cF(n,e))}function*pF(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===RS).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}var mF=class{func;name;input;retry;cache;timeout;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,timeout:a,callbacks:o}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.timeout=a,this.callbacks=o}};function hF(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function gF(e,t){return new Dx({name:e,first:new WN({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new $N([{channel:RS,value:XN}],[BS])})}var _F=e=>e===void 0?1:e+1;function vF(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function yF(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:aN(t,e[n]));return t}function bF(e,t,n){let r=aP(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(BS):t.includes(e.name));return a&&o}function xF(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=new Set;for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let t=i[e];hN(t)&&t.isAvailable()&&s.add(e)}let c=CN(e,i,-1,{channelsToSnapshot:s}),l=bN(i,c);TF(rN(c),l,[n],void 0,void 0),o=lF({...t,...l},r)}else o=lF(t,r);return o}function SF(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!ZS(r))throw new SC(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new SC(`Invalid node name "${r.node}" in Send packet`)}e(n)}var CF=new Set([LS,US,IS,FS,RS,fS,pS]),wF=new Set(KS);function TF(e,t,n,r,i){let a=new Map;for(let e of n)a.set(e,e.path?.slice(0,3)||[]);n.sort((e,t)=>{let n=a.get(e),r=a.get(t);for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let o=yN(t),s=!1,c=new Set;for(let t of n){t.triggers.length>0&&(s=!0),e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n]),wF.has(n)||c.add(n)}let l=yF(e.channel_versions),u=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(l),u=!0);let d={},f={};for(let e of n){let t=e.id??``;for(let[n,r]of e.writes)CF.has(n)||n in o&&(d[n]??=[],d[n].push(r),f[n]??=[],f[n].push(t))}for(let[e,t]of Object.entries(d)){if(t.length<2||o[e]?.lc_graph_name!==`DeltaChannel`)continue;let n=f[e],r=t.map((e,t)=>({val:e,taskId:n[t]}));r.sort((e,t)=>e.taskId<t.taskId?-1:+(e.taskId>t.taskId)),d[e]=r.map(e=>e.val)}l!=null&&r!=null&&(l=u?r(l):l);let p=new Set;for(let[t,n]of Object.entries(d))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===SC.unminifiable_name){let r=new SC(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(l),i.isAvailable()&&p.add(t))}if(s)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!p.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}if(s&&!vF(p,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}return p}function*EF(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function DF(e){let t,n=new Map,r=new Set;if(e)for(let[i,a,o]of e){if(i===`00000000-0000-0000-0000-000000000000`&&a===`__resume__`&&t===void 0&&(t=o),a===`__resume__`&&i!==`00000000-0000-0000-0000-000000000000`){let e=n.get(i);e||(e=[],n.set(i,e)),e.push(o)}a!==`__error__`&&r.add(i)}return{nullResume:t,resumeByTaskId:n,successfulWriteTaskIds:r}}function OF(e,t,n,r,i,a,o){let s={},c=o.pendingWritesIndex?o:{...o,pendingWritesIndex:DF(t)},l=r[HS];if(l?.isAvailable()){let o=l.get().length;for(let l=0;l<o;l+=1){let o=kF([US,l],e,t,n,r,i,a,c);o!==void 0&&(s[o.id]=o)}}for(let o of EF(e,n,c)){let l=kF([WS,o],e,t,n,r,i,a,c);l!==void 0&&(s[l.id]=l)}return s}function kF(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&hF(e[e.length-1])){let p=e[e.length-1],m=gF(p.name,p.func),h=[US],g=f===``?p.name:`${f}|${p.name}`,_=OC(JSON.stringify([g,c.toString(),p.name,US,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v,checkpoint_ns:v};if(o){let e=[],o={checkpointId:t.id,checkpointNs:v,taskId:_,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p.name,input:p.input,proc:m,writes:e,config:{...Ql(Xl(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xS]:_,[gS]:t=>SF(t=>e.push(...t),r,t),[vS]:(n,r=!1)=>xF(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[yS]:l??d.__pregel_checkpointer,[MS]:{...d[MS],[f]:t.id},[TS]:NF({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[wS],namespaceHash:oF(v),pendingWritesIndex:s.pendingWritesIndex}),[ES]:t.channel_values[zS],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:oF((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[mS,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[],timeout:p.timeout}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[HS].get();if(p<0||p>=m.length)return;let h=YS(m[p])&&!ZS(m[p])?new XS(m[p].node,m[p].args,m[p].timeout===void 0?void 0:{timeout:m[p].timeout}):m[p];if(!YS(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[US],_=f===``?h.node:`${f}|${h.node}`,v=OC(JSON.stringify([_,c.toString(),h.node,US,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[],_={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:{...Ql(Xl(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xS]:v,[gS]:e=>SF(e=>m.push(...e),r,e),[vS]:(n,r=!1)=>xF(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[yS]:l??d.__pregel_checkpointer,[MS]:{...d[MS],[f]:t.id},[TS]:NF({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[wS],namespaceHash:oF(y),pendingWritesIndex:s.pendingWritesIndex}),[ES]:t.channel_values[zS],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:oF((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[mS,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters(),timeout:h.timeout??o.timeout}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=OC(JSON.stringify([e,c.toString(),p,WS,p]),t.id);if(s.pendingWritesIndex?s.pendingWritesIndex.successfulWriteTaskIds.has(r):n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=aP(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=jF(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=OC(JSON.stringify([g,c.toString(),p,WS,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[],x={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:{...Ql(Xl(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xS]:v,[gS]:e=>SF(e=>{g.push(...e)},r,e),[vS]:(n,r=!1)=>xF(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[yS]:l??d.__pregel_checkpointer,[MS]:{...d[MS],[f]:t.id},[TS]:NF({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[wS],namespaceHash:oF(y),pendingWritesIndex:s.pendingWritesIndex}),[ES]:t.channel_values[zS],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:x},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:oF((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[mS,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters(),timeout:m.timeout}}}else return{id:v,name:p,interrupts:[],path:e}}}}function AF(e,t,n,r,i,a,o,s,c){let{step:l,checkpointer:u,manager:d}=c,f=a[t];if(f===void 0)return;let p=f.getNode();if(p===void 0)return;let m=s.configurable??{},h=m.checkpoint_ns??``,g=[US],_=h===``?t:`${h}|${t}`,v=OC(JSON.stringify([_,l.toString(),t,US,`node_error_handler`,e.id]),r.id),y=`${_}:${v}`,b=[US,String(e.name),t,!1],x={langgraph_step:l,langgraph_node:t,langgraph_triggers:g,langgraph_path:b,langgraph_checkpoint_ns:y,checkpoint_ns:y};f.metadata!==void 0&&(x={...x,...f.metadata});let ee=[],te={checkpointId:r.id,checkpointNs:y,taskId:v,threadId:m.thread_id,runId:s.runId==null?void 0:String(s.runId),nodeAttempt:1};return{name:t,input:e.input,proc:p,subgraphs:f.subgraphs,writes:ee,config:{...Ql(Xl(s,{metadata:x,tags:f.tags,store:c.store??s.store}),{runName:t,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[xS]:v,[gS]:e=>SF(e=>ee.push(...e),a,e),[vS]:(e,n=!1)=>xF(r,o,{name:t,writes:ee,triggers:g,path:b},e,n),[yS]:u??m.__pregel_checkpointer,[MS]:{...m[MS],[h]:r.id},[TS]:NF({pendingWrites:i??[],taskId:v,currentTaskInput:e.input,resumeMap:s.configurable?.[wS],namespaceHash:oF(y)}),[ES]:r.channel_values[zS],[jS]:new mC(String(e.name),n),checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:te},triggers:g,retry_policy:f.retryPolicy,cache_key:void 0,id:v,path:b,writers:f.getWriters()}}function jF(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=cF(t,i,!1)}catch(e){if(e.name===xC.unminifiable_name)return;throw e}else if(i in t)try{r[n]=cF(t,i,!1)}catch(e){if(e.name===xC.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=cF(t,i,!1),n=!0;break}catch(e){if(e.name===xC.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function MF(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new XS(e.node,n)}function NF({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i,pendingWritesIndex:a}){let o=a?a.nullResume:e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],s={callCounter:0,interruptCounter:-1,resume:(()=>{let n=a?(a.resumeByTaskId.get(t)??[]).flat():e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),o}};return s}var PF={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},FF=(e,t)=>`${e.start}${t}${e.end}`;function IF(e){if(e==null)return;let t={};if(e.metadata!=null)for(let[n,r]of Object.entries(e.metadata))sN.has(n)||(t[n]=r);let n=LN(e.tags);return n!=null&&(t.tags=n),Object.keys(t).length>0?t:void 0}function*LF(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e){if(i?.tags?.includes(`langsmith:hidden`))continue;let e={id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)},s=IF(i);s!=null&&(e.metadata=s),yield e}}function RF(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function zF(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=RF(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*BF(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:zF(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===FS).map(e=>e[1])})}function*VF(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(pP))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:lF(t,n),metadata:r,next:i.map(e=>e.name),tasks:HF(i,a,u,s),parentConfig:o?c(o):void 0}}function HF(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?zF(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function UF(e,t,n){console.log([`${FF(PF.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(lF(t,n),null,2)].join(``))}function WF(e,t){let n=t.length;console.log([`${FF(PF.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${FF(PF.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
|
|
184
|
+
`);return await n?.handleLLMNewToken(r),{generations:[{message:new $t(r),text:r}],llmOutput:{}}}},kM=class e extends EE{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:ox(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:ox(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:ox(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:ox(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new $t({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new Uu({message:new nn({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new $t(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new Uu({message:new nn({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},AM=class e extends EE{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new $t(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new Uu({message:new nn({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:ox(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:ox(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:ox(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:ox(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return jx.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},jM=class extends xw{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},MM=class extends xw{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},NM=class extends RE{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},PM=class extends RE{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},FM=class extends cw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new fn(e))}async addAIMessage(e){this.messages.push(new $t(e))}async clear(){this.messages=[]}},IM=class extends lw{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},LM=class extends Yc{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},RM=class extends vT{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},zM=class extends fO{lc_namespace=[`test`,`fake`];output=[new dw({pageContent:`foo`}),new dw({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},BM=class extends Cx{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},VM=class extends hj{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},HM=class extends Yc{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},UM=class e extends EM{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??Kj}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>!n||n(new dw({metadata:e.metadata,pageContent:e.content})));return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new dw({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new dw({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},WM=s({FakeChatMessageHistory:()=>FM,FakeChatModel:()=>OM,FakeEmbeddings:()=>MM,FakeLLM:()=>NM,FakeListChatMessageHistory:()=>IM,FakeListChatModel:()=>AM,FakeRetriever:()=>zM,FakeRunnable:()=>BM,FakeSplitIntoListParser:()=>RM,FakeStreamingChatModel:()=>kM,FakeStreamingLLM:()=>PM,FakeTool:()=>VM,FakeTracer:()=>LM,FakeVectorStore:()=>UM,SingleRunExtractor:()=>HM,SyntheticEmbeddings:()=>jM,asAsyncIterable:()=>fk,openAIReasoningTextChunks:()=>hk,openAITextOnlyChunks:()=>mk,openAITextOnlyChunksWithUsage:()=>pk,openAIToolCallChunks:()=>gk,sseResponseFromOpenAIChunks:()=>_k,streamMatchers:()=>qO}),GM=s({agents:()=>KC,caches:()=>ew,callbacks__base:()=>Fr,callbacks__manager:()=>jl,callbacks__promises:()=>El,chat_history:()=>sw,document_loaders__base:()=>hw,document_loaders__langsmith:()=>_w,documents:()=>mw,embeddings:()=>bw,errors:()=>u,example_selectors:()=>jw,index:()=>GC,indexing:()=>Bw,language_models__base:()=>sT,language_models__chat_models:()=>wE,language_models__compat:()=>dE,language_models__event:()=>FE,language_models__llms:()=>IE,language_models__openai_completions_stream:()=>OE,language_models__profile:()=>zE,language_models__stream:()=>ZT,language_models__structured_output:()=>qT,load__serializable:()=>me,memory:()=>BE,messages:()=>iS,messages__tool:()=>yt,output_parsers:()=>BT,output_parsers__openai_functions:()=>YE,output_parsers__openai_tools:()=>XE,outputs:()=>Bu,prompt_values:()=>Vw,prompts:()=>cO,retrievers:()=>dO,retrievers__document_compressors:()=>lO,runnables:()=>oS,runnables__graph:()=>cx,singletons:()=>Gl,stores:()=>pO,structured_query:()=>PO,testing:()=>vk,tools:()=>mj,tracers__base:()=>Wc,tracers__console:()=>Xc,tracers__log_stream:()=>Mu,tracers__run_collector:()=>wj,tracers__tracer_langchain:()=>fl,types__stream:()=>Ej,utils__async_caller:()=>id,utils__chunk_array:()=>Dj,utils__context:()=>kj,utils__env:()=>Tr,utils__event_source_parse:()=>Nj,utils__format:()=>Hj,utils__function_calling:()=>Uj,utils__hash:()=>$C,utils__json_patch:()=>gT,utils__json_schema:()=>ix,utils__math:()=>Xj,utils__ssrf:()=>aM,utils__standard_schema:()=>gb,utils__stream:()=>nu,utils__testing:()=>WM,utils__tiktoken:()=>nT,utils__types:()=>VT,utils__uuid:()=>pr,vectorstores:()=>wM}),KM=50;function qM(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function JM(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:i,secretsFromEnv:a,path:o,depth:s,maxDepth:c}=this,l=o.join(`.`);if(s>c)throw Error(`Maximum recursion depth (${c}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>JM.call({...this,path:[...o,`${t}`],depth:s+1},e)));let u=e;if(le(u))return pe(u);if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`secret`){let[e]=u.id;if(e in i)return i[e];if(a){let t=Pr(e);if(t)return t}throw Error(`Missing secret "${e}" at ${l}`)}if(`lc`in u&&`type`in u&&`id`in u&&u.lc===1&&u.type===`not_implemented`){let e=JSON.stringify(u);throw Error(`Trying to load an object that doesn't implement serialization: ${l} -> ${e}`)}if(`lc`in u&&`type`in u&&`id`in u&&`kwargs`in u&&u.lc===1&&u.type===`constructor`){let e=u,i=JSON.stringify(e),[a,...c]=e.id.slice().reverse(),d=c.reverse(),f={langchain_core:GM,langchain:r},p=null,m=[d.join(`/`)];d[0]===`langchain_community`&&m.push([`langchain`,...d.slice(1)].join(`/`));let h=m.find(e=>e in t);if(WC.concat(n).includes(d.join(`/`))||h)if(h!==void 0)p=await t[h];else throw Error(`Missing key "${d.join(`/`)}" for ${l} in load(optionalImportsMap={})`);else{let e;if(d[0]===`langchain`||d[0]===`langchain_core`)e=f[d[0]],d.shift();else throw Error(`Invalid namespace: ${l} -> ${i}`);if(d.length===0)throw Error(`Invalid namespace: ${l} -> ${i}`);let t;do{if(t=d.join(`__`),t in e)break;d.pop()}while(d.length>0);t in e&&(p=e[t])}if(typeof p!=`object`||!p)throw Error(`Invalid namespace: ${l} -> ${i}`);let g=p[a]??Object.values(p).find(e=>typeof e==`function`&&_e(e)===a);if(typeof g!=`function`)throw Error(`Invalid identifer: ${l} -> ${i}`);let _=new g(oe(await JM.call({...this,path:[...o,`kwargs`],depth:s+1},e.kwargs),ae,qM(g)));return Object.defineProperty(_.constructor,"name",{value:a}),_}let d={};for(let[e,t]of Object.entries(u))d[e]=await JM.call({...this,path:[...o,e],depth:s+1},t);return d}async function YM(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??KM};return JM.call(r,n)}function XM(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function ZM(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>ZM(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await ZM(r);if(t.lc===2&&t.type===`undefined`)return;if(t.lc===2&&t.type===`delta_snapshot`)return new NC(t.value);if(t.lc===2&&t.type===`constructor`&&Array.isArray(t.id))try{let e=t.id[t.id.length-1],n;switch(e){case`Set`:n=Set;break;case`Map`:n=Map;break;case`RegExp`:n=RegExp;break;case`Error`:n=Error;break;case`Uint8Array`:n=Uint8Array;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(XM(t))return YM(JSON.stringify(t));return t}}return e}function QM(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function $M(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof NC?{lc:2,type:`delta_snapshot`,value:e.value}:e instanceof Set||e instanceof Map?QM(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?QM(RegExp,void 0,[e.source,e.flags]):e instanceof Error?QM(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args,...e.timeout===void 0?{}:{timeout:e.timeout}}:e instanceof Uint8Array?QM(Uint8Array,`from`,[Array.from(e)]):e}var eN=class{_dumps(e){return new TextEncoder().encode(BC(e,(e,t)=>$M(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return ZM(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function tN(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=tN(e[n]));return t}function nN(){return{v:4,id:DC(0),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function rN(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values??{}},channel_versions:{...e.channel_versions??{}},versions_seen:tN(e.versions_seen??{})}}function iN(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function aN(...e){return e.reduce((e,t,n)=>n===0?t:iN(e,t)>=0?e:t)}var oN={[kC]:-1,[AC]:-2,[jC]:-3,[MC]:-4},sN=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`checkpoint_map`,`langgraph_step`,`langgraph_node`,`langgraph_triggers`,`langgraph_path`,`langgraph_checkpoint_ns`]),cN=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function lN(e){if(e.length===0)throw new cN(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new cN(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new cN(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new cN(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new cN(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var uN=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){lN(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},dN=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,fN=class extends uN{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=dN(e)}get isRunning(){return this.running}async batch(e){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},pN=class{serde=new eN;constructor(e){this.serde=e||this.serde}},mN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function hN(e){return e!=null&&e.lc_graph_name===`DeltaChannel`}function gN(e){return e!=null&&e.lg_is_channel===!0}var _N=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===xC.unminifiable_name)return!1;throw e}}equals(e){return this===e}},vN=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function yN(e){if(e[vN]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];gN(r)&&(t[n]=r)}return Object.assign(t,{[vN]:!0}),t}function bN(e,t){let n=yN(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[vN]:!0}),r}function xN(e,t){if(!mN.test(t))throw TypeError(`Invalid task id for exit delta: ${t}`);let n=t.toLowerCase().split(`-`);return`${String(e).padStart(8,`0`)}-${n[1]}-${n[2]}-${n[3]}-${n[4]}`}function SN(e,t){let n=new Set,r=hS();for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=e[i];if(!hN(a)||!a.isAvailable())continue;let[o,s]=t[i]??[0,0];(o>=a.snapshotFrequency||s>=r)&&n.add(i)}return n}function CN(e,t,n,r){let i=r?.channelsToSnapshot??new Set,{updatedChannels:a,getNextVersion:o}=r??{},s,c=e.channel_versions;if(t===void 0)s=e.channel_values;else{s={},c={...e.channel_versions};for(let e in t){if(!Object.prototype.hasOwnProperty.call(t,e))continue;let n=t[e];if(i.has(e)){o!==void 0&&(a===void 0||!a.has(e))&&(c[e]=o(c[e])),s[e]=new NC(n.get());continue}if(!hN(n))try{s[e]=n.checkpoint()}catch(e){if(e.name!==xC.unminifiable_name)throw e}}}return{v:4,id:r?.id??DC(n),ts:new Date().toISOString(),channel_values:s,channel_versions:c,versions_seen:e.versions_seen}}async function wN(e,t,n){let r=bN(e,t),{saver:i,config:a}=n??{},o=yN(e),s=[];for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&hN(o[e])&&!Object.prototype.hasOwnProperty.call(t.channel_values,e)&&s.push(e);if(s.length===0||i===void 0||a===void 0)return r;let c=await i.getDeltaChannelHistory({config:a,channels:s});for(let e of s){let t=c[e];if(t===void 0)continue;let n=o[e].fromCheckpoint(t.seed);n.replayWrites(t.writes),r[e]=n}return r}var TN=class e extends _N{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new SC(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new xC;return this.value[0]}checkpoint(){if(this.value.length===0)throw new xC;return this.value[0]}isAvailable(){return this.value.length!==0}},EN=class e extends _N{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new xC;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}},DN=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,ON=class e extends _N{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;if(this.value===void 0){let e=t[0],[n,r]=$S(e);n?this.value=r:this.value=e,t=t.slice(1)}let n=!1;for(let e of t)if(eC(e)){if(n)throw new SC(`Can receive only one Overwrite value per step.`);let[,t]=$S(e);this.value=t,n=!0;continue}else!n&&this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new xC;return this.value}checkpoint(){if(this.value===void 0)throw new xC;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:DN(e)?this.operator===e.operator:!1}},kN=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},AN=function(e){return e?jN(e):new TN};AN.Root=e=>new kN(e);function jN(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new ON(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new ON(e.value,e.default):new TN}var MN=[`tags`,`metadata`,`callbacks`,`configurable`],NN=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`,`heartbeat`,`executionInfo`,`serverInfo`,`control`],PN=25,FN=new Set([`thread_id`,`checkpoint_id`,`checkpoint_ns`,`task_id`,`run_id`,`assistant_id`,`graph_id`]);function IN(e,t){if(!e)return t;let n=t??{};for(let t of FN){if(t in n)continue;let r=e[t];r!==void 0&&(n[t]=r)}return n}function LN(e){if(e==null||e.length===0)return;let t=e.filter(e=>!e.startsWith(`seq:step`));return t.length>0?t:void 0}function RN(e,t){if(t===void 0)return e;if(e===void 0)return Array.isArray(t)?[...t]:t.copy();if(Array.isArray(t)){if(Array.isArray(e))return e.concat(t);let n=e.copy();for(let e of t)n.addHandler(Bl(e),!0);return n}if(Array.isArray(e)){let n=t.copy();for(let t of e)n.addHandler(Bl(t),!0);return n}return new zl(t._parentRunId,{handlers:e.handlers.concat(t.handlers),inheritableHandlers:e.inheritableHandlers.concat(t.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(t.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(t.inheritableTags))),metadata:{...e.metadata,...t.metadata},inheritableMetadata:{...e.inheritableMetadata,...t.inheritableMetadata}})}function zN(e){let t;for(let n=e.length-1;n>=0;--n)if(e[n]!==void 0){t=e[n];break}let n=t?.configurable?.thread_id!==void 0,r=e.some(e=>e?.configurable?.[vS]!==void 0),i=Wl.getRunnableConfig()?.configurable?.[vS]!==void 0;return n&&!r&&!i}function BN(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:PN,configurable:{}},n=zN(e),r=Wl.getRunnableConfig();if(r!==void 0){for(let[e,i]of Object.entries(r))if(i!==void 0){if(e===`configurable`&&n)continue;if(MN.includes(e)){let n;n=Array.isArray(i)?[...i]:typeof i==`object`?e===`callbacks`&&`copy`in i&&typeof i.copy==`function`?i.copy():{...i}:i,t[e]=n}else t[e]=i}}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r===void 0||!NN.includes(e)||(e===`configurable`?t.configurable={...t.configurable,...r}:e===`metadata`?t.metadata={...t.metadata,...r}:e===`tags`?t.tags=[...t.tags??[],...r]:e===`callbacks`?t.callbacks=RN(t.callbacks,r):t[e]=r);return t.metadata=IN(t.configurable,t.metadata)??{},t}function VN(){return Wl.getRunnableConfig()}function HN(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function UN(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var WN=class extends Cx{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,i)=>{let a=Ql(t,{callbacks:n?.getChild()});Wl.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=BN(t),i=Xl(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await Wl.runWithConfig(i,async()=>this.func(e,i)),Cx.isRunnable(n)&&this.recurse?await Wl.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*GN(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function KN(e){let t=[];for await(let n of await e)t.push(n);return t}function qN(e){let t=[];for(let n of e)t.push(n);return t}function JN(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function YN(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var XN={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function ZN(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var QN=Symbol(`IS_WRITER`),$N=class e extends WN{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>ZS(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,trace:!1,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>tP(e)&&ZN(e.value)?{mapper:e.mapper,value:t}:eP(e)&&ZN(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(eP(e)){if(e.channel===`__pregel_tasks`)throw new SC(`Cannot write to the reserved channel TASKS`);if(ZN(e.value))throw new SC(`PASSTHROUGH value must be replaced`)}if(tP(e)&&ZN(e.value))throw new SC(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(ZS(r))n.push([HS,r]);else if(tP(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(eP(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(YN(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[gS];r(n)}static isWriter(t){return t instanceof e||QN in t&&!!t[QN]}static registerWriter(e){return Object.defineProperty(e,QN,{value:!0})}};function eP(e){return e!==void 0&&typeof e.channel==`string`}function tP(e){return e!==void 0&&!eP(e)&&Cx.isRunnable(e.mapper)}var nP=class e extends WN{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({trace:!1,func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[vS];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},rP=new zx,iP=class e extends wx{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=rP;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;timeout;subgraphs;ends;isErrorHandler;errorHandlerNode;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,timeout:u,tags:d,subgraphs:f,ends:p,isErrorHandler:m,errorHandlerNode:h}=e,g=[...e.config?.tags?e.config.tags:[],...d??[]];super({...e,bound:e.bound??rP,config:{...e.config?e.config:{},tags:g}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=g,this.retryPolicy=c,this.cachePolicy=l,this.timeout=u,this.subgraphs=f,this.ends=p,this.isErrorHandler=m,this.errorHandlerNode=h}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof $N&&e[e.length-2]instanceof $N;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new $N(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===rP&&e.length===0))return this.bound===rP&&e.length===1?e[0]:this.bound===rP?new Dx({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new Dx({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}pipe(t){return $N.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):this.bound===rP?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:Px(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy,timeout:this.timeout})}};function aP(e){let t=typeof e[lS];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function oP(e,t){if(Object.keys(e).length>0){let n=aP(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function sP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function cP(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function lP(e,t){let n=t?.parents??{};return Object.keys(n).length>0?cP(e,{[MS]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function uP(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}function dP(e){return`steps`in e&&Array.isArray(e.steps)}function fP(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function pP(e){let t=[e];for(let e of t)if(fP(e))return e;else dP(e)&&t.push(...e.steps)}var mP=class e extends _N{lc_graph_name=`EphemeralValue`;guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(t){let n=new e(this.guard);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0){let e=this.value.length>0;return this.value=[],e}if(e.length!==1&&this.guard)throw new SC(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new xC;return this.value[0]}checkpoint(){if(this.value.length===0)throw new xC;return this.value[0]}isAvailable(){return this.value.length!==0}},hP=class{#e=void 0;requestDrain(e=`shutdown`){this.#e=e}get drainRequested(){return this.#e!==void 0}get drainReason(){return this.#e}},V=e=>BigInt(e),gP=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),_P=V(`0x9E3779B1`),vP=V(`0x85EBCA77`),yP=V(`0xC2B2AE3D`),bP=V(`0x9E3779B185EBCA87`),xP=V(`0xC2B2AE3D27D4EB4F`),SP=V(`0x165667B19E3779F9`),CP=V(`0x85EBCA77C2B2AE63`),wP=V(`0x27D4EB2F165667C5`),TP=V(`0x165667919E3779F9`),EP=V(`0x9FB21C651E98DF25`),DP=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return gP(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),OP=(V(1)<<V(128))-V(1),kP=(V(1)<<V(64))-V(1),AP=(V(1)<<V(32))-V(1),jP=64,MP=jP/8,NP=8,PP=4;function FP(e){if(!e)throw Error(`Assert failed`)}function IP(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function LP(e){let t=e;return t=(t&V(65535))<<V(16)|(t&V(4294901760))>>V(16),t=(t&V(16711935))<<V(8)|(t&V(4278255360))>>V(8),t}function RP(e,t){return(e&AP)*(t&AP)&kP}function zP(e,t){return(e<<t|e>>V(32)-t)&AP}function BP(e,t,n){for(let r=0;r<MP;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=RP(a,a>>V(32))}return e}function VP(e,t,n,r){for(let i=0;i<r;i+=1)BP(e,gP(t,i*jP),gP(n,i*8));return e}function HP(e,t){for(let n=0;n<MP;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=$P(i,V(47)),i^=r,i*=_P,e[n]=i&kP}return e}function UP(e,t){return qP(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(NP,!0))}function WP(e,t,n){let r=n;return r+=UP(e.slice(0),gP(t,0*PP)),r+=UP(e.slice(2),gP(t,4*PP)),r+=UP(e.slice(4),gP(t,8*PP)),r+=UP(e.slice(6),gP(t,12*PP)),XP(r&kP)}function GP(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-jP)/8),s=jP*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=VP(a,gP(t,e*s),n,o),a=i(a,gP(n,n.byteLength-jP));{let e=Math.floor((t.byteLength-1-s*c)/jP);a=VP(a,gP(t,c*s),n,e),a=r(a,gP(t,t.byteLength-jP),gP(n,n.byteLength-jP-7))}return a}function KP(e,t){let n=new BigUint64Array([yP,bP,xP,SP,CP,vP,wP,_P]);FP(e.byteLength>128),n=GP(n,e,t,BP,HP),FP(n.length*8==64);{let r=WP(n,gP(t,11),V(e.byteLength)*bP&kP);return WP(n,gP(t,t.byteLength-jP-11),~(V(e.byteLength)*xP)&kP)<<V(64)|r}}function qP(e,t){let n=e*t&OP;return n&kP^n>>V(64)}function JP(e,t,n){return qP((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&kP,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&kP)}function YP(e,t,n,r,i){let a=e&kP,o=e>>V(64)&kP;return a+=JP(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=kP,o+=JP(n,gP(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=kP,o<<V(64)|a}function XP(e){let t=e;return t^=t>>V(37),t*=TP,t&=kP,t^=t>>V(32),t}function ZP(e){let t=e;return t^=t>>V(33),t*=xP,t&=kP,t^=t>>V(29),t*=SP,t&=kP,t^=t>>V(32),t}function QP(e,t,n){let r=e.byteLength;FP(r>0&&r<=3);let i=V(e.getUint8(r-1))|V(r<<8)|V(e.getUint8(0)<<16)|V(e.getUint8(r>>1)<<24),a=(i^(V(t.getUint32(0,!0))^V(t.getUint32(4,!0)))+n)&kP,o=(V(t.getUint32(8,!0))^V(t.getUint32(12,!0)))-n;return(ZP((zP(LP(i),V(13))^o)&kP)&kP)<<V(64)|ZP(a)}function $P(e,t){return e^e>>t}function eF(e,t,n){let r=e.byteLength;FP(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((V(i)|V(a)<<V(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&kP)*(bP+(V(r)<<V(2)))&OP;return o+=(o&kP)<<V(65),o&=OP,o^=o>>V(67),$P($P(o&kP,V(35))*EP&kP,V(28))|XP(o>>V(64))<<V(64)}}function tF(e,t,n){let r=e.byteLength;FP(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&kP,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&kP,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*bP,l=(c&kP)+(V(r-1)<<V(54));c=c&(OP^kP)|l,s^=a,c+=s+(s&AP)*(vP-V(1))<<V(64),c&=OP,c^=IP(c>>V(64));let u=(c&kP)*xP;return u+=(c>>V(64))*xP<<V(64),u&=OP,XP(u&kP)|XP(u>>V(64))<<V(64)}}function nF(e,t){let n=e.byteLength;return FP(n<=16),n>8?tF(e,DP,t):n>=4?eF(e,DP,t):n>0?QP(e,DP,t):ZP(t^DP.getBigUint64(64,!0)^DP.getBigUint64(72,!0))|ZP(t^DP.getBigUint64(80,!0)^DP.getBigUint64(88,!0))<<V(64)}function rF(e){return~e+V(1)&kP}function iF(e,t,n){let r=V(e.byteLength)*bP&kP,i=V(e.byteLength-1)/V(32);for(;i>=0;){let a=Number(i);r=YP(r,gP(e,16*a),gP(e,e.byteLength-16*(a+1)),gP(t,32*a),n),i-=V(1)}let a=r+(r>>V(64))&kP;a=XP(a);let o=(r&kP)*bP+(r>>V(64))*CP+(V(e.byteLength)-n&kP)*xP;return o&=kP,o=rF(XP(o)),a|o<<V(64)}function aF(e,t,n){let r=V(e.byteLength)*bP&kP;for(let i=32;i<160;i+=32)r=YP(r,gP(e,i-32),gP(e,i-16),gP(t,i-32),n);r=XP(r&kP)|XP(r>>V(64))<<V(64);for(let i=160;i<=e.byteLength;i+=32)r=YP(r,gP(e,i-32),gP(e,i-16),gP(t,3+i-160),n);r=YP(r,gP(e,e.byteLength-16),gP(e,e.byteLength-32),gP(t,103),rF(n));let i=r+(r>>V(64))&kP;i=XP(i);let a=(r&kP)*bP+(r>>V(64))*CP+(V(e.byteLength)-n&kP)*xP;return a&=kP,a=rF(XP(a)),i|a<<V(64)}function oF(e,t=V(0)){let n=new TextEncoder,r=gP(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?nF(r,t):i<=128?iF(r,DP,t):i<=240?aF(r,DP,t):KP(r,DP))}function sF(e){return/^[0-9a-f]{32}$/.test(e)}function cF(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===xC.unminifiable_name){if(r)return e;if(n)return null}throw e}}function lF(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=cF(e,i,!n)}catch(e){if(e.name===xC.unminifiable_name)continue}return r}else return cF(e,t)}function*uF(e,t){if(e.graph===nC.PARENT)throw new SC(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(ZS(e))yield[GS,HS,e];else if(typeof e==`string`)yield[GS,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(sF))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,IS,e]}else yield[GS,IS,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[GS,t,n];else for(let[t,n]of Object.entries(e.update))yield[GS,t,n]}}function*dF(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*fF(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield lF(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield cF(n,e))}function*pF(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===RS).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}var mF=class{func;name;input;retry;cache;timeout;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,timeout:a,callbacks:o}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.timeout=a,this.callbacks=o}};function hF(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function gF(e,t){return new Dx({name:e,first:new WN({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new $N([{channel:RS,value:XN}],[BS])})}var _F=e=>e===void 0?1:e+1;function vF(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function yF(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:aN(t,e[n]));return t}function bF(e,t,n){let r=aP(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(BS):t.includes(e.name));return a&&o}function xF(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=new Set;for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let t=i[e];hN(t)&&t.isAvailable()&&s.add(e)}let c=CN(e,i,-1,{channelsToSnapshot:s}),l=bN(i,c);TF(rN(c),l,[n],void 0,void 0),o=lF({...t,...l},r)}else o=lF(t,r);return o}function SF(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!ZS(r))throw new SC(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new SC(`Invalid node name "${r.node}" in Send packet`)}e(n)}var CF=new Set([LS,US,IS,FS,RS,fS,pS]),wF=new Set(KS);function TF(e,t,n,r,i){let a=new Map;for(let e of n)a.set(e,e.path?.slice(0,3)||[]);n.sort((e,t)=>{let n=a.get(e),r=a.get(t);for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let o=yN(t),s=!1,c=new Set;for(let t of n){t.triggers.length>0&&(s=!0),e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n]),wF.has(n)||c.add(n)}let l=yF(e.channel_versions),u=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(l),u=!0);let d={},f={};for(let e of n){let t=e.id??``;for(let[n,r]of e.writes)CF.has(n)||n in o&&(d[n]??=[],d[n].push(r),f[n]??=[],f[n].push(t))}for(let[e,t]of Object.entries(d)){if(t.length<2||o[e]?.lc_graph_name!==`DeltaChannel`)continue;let n=f[e],r=t.map((e,t)=>({val:e,taskId:n[t]}));r.sort((e,t)=>e.taskId<t.taskId?-1:+(e.taskId>t.taskId)),d[e]=r.map(e=>e.val)}l!=null&&r!=null&&(l=u?r(l):l);let p=new Set;for(let[t,n]of Object.entries(d))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===SC.unminifiable_name){let r=new SC(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(l),i.isAvailable()&&p.add(t))}if(s)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!p.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}if(s&&!vF(p,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(l),n.isAvailable()&&p.add(t))}return p}function*EF(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function DF(e){let t,n=new Map,r=new Set;if(e)for(let[i,a,o]of e){if(i===`00000000-0000-0000-0000-000000000000`&&a===`__resume__`&&t===void 0&&(t=o),a===`__resume__`&&i!==`00000000-0000-0000-0000-000000000000`){let e=n.get(i);e||(e=[],n.set(i,e)),e.push(o)}a!==`__error__`&&r.add(i)}return{nullResume:t,resumeByTaskId:n,successfulWriteTaskIds:r}}function OF(e,t,n,r,i,a,o){let s={},c=o.pendingWritesIndex?o:{...o,pendingWritesIndex:DF(t)},l=r[HS];if(l?.isAvailable()){let o=l.get().length;for(let l=0;l<o;l+=1){let o=kF([US,l],e,t,n,r,i,a,c);o!==void 0&&(s[o.id]=o)}}for(let o of EF(e,n,c)){let l=kF([WS,o],e,t,n,r,i,a,c);l!==void 0&&(s[l.id]=l)}return s}function kF(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&hF(e[e.length-1])){let p=e[e.length-1],m=gF(p.name,p.func),h=[US],g=f===``?p.name:`${f}|${p.name}`,_=OC(JSON.stringify([g,c.toString(),p.name,US,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v,checkpoint_ns:v};if(o){let e=[],o={checkpointId:t.id,checkpointNs:v,taskId:_,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p.name,input:p.input,proc:m,writes:e,config:{...Ql(Xl(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xS]:_,[gS]:t=>SF(t=>e.push(...t),r,t),[vS]:(n,r=!1)=>xF(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[yS]:l??d.__pregel_checkpointer,[MS]:{...d[MS],[f]:t.id},[TS]:NF({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[wS],namespaceHash:oF(v),pendingWritesIndex:s.pendingWritesIndex}),[ES]:t.channel_values[zS],checkpoint_id:void 0,checkpoint_ns:v}}),executionInfo:o},triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:oF((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[mS,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[],timeout:p.timeout}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[HS].get();if(p<0||p>=m.length)return;let h=YS(m[p])&&!ZS(m[p])?new XS(m[p].node,m[p].args,m[p].timeout===void 0?void 0:{timeout:m[p].timeout}):m[p];if(!YS(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[US],_=f===``?h.node:`${f}|${h.node}`,v=OC(JSON.stringify([_,c.toString(),h.node,US,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[],_={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:{...Ql(Xl(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xS]:v,[gS]:e=>SF(e=>m.push(...e),r,e),[vS]:(n,r=!1)=>xF(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[yS]:l??d.__pregel_checkpointer,[MS]:{...d[MS],[f]:t.id},[TS]:NF({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[wS],namespaceHash:oF(y),pendingWritesIndex:s.pendingWritesIndex}),[ES]:t.channel_values[zS],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:_},triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:oF((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[mS,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters(),timeout:h.timeout??o.timeout}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=OC(JSON.stringify([e,c.toString(),p,WS,p]),t.id);if(s.pendingWritesIndex?s.pendingWritesIndex.successfulWriteTaskIds.has(r):n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=aP(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=jF(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=OC(JSON.stringify([g,c.toString(),p,WS,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y,checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[],x={checkpointId:t.id,checkpointNs:y,taskId:v,threadId:d.thread_id,runId:a.runId==null?void 0:String(a.runId),nodeAttempt:1};return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:{...Ql(Xl(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[xS]:v,[gS]:e=>SF(e=>{g.push(...e)},r,e),[vS]:(n,r=!1)=>xF(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[yS]:l??d.__pregel_checkpointer,[MS]:{...d[MS],[f]:t.id},[TS]:NF({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[wS],namespaceHash:oF(y),pendingWritesIndex:s.pendingWritesIndex}),[ES]:t.channel_values[zS],checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:x},triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:oF((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[mS,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters(),timeout:m.timeout}}}else return{id:v,name:p,interrupts:[],path:e}}}}function AF(e,t,n,r,i,a,o,s,c){let{step:l,checkpointer:u,manager:d}=c,f=a[t];if(f===void 0)return;let p=f.getNode();if(p===void 0)return;let m=s.configurable??{},h=m.checkpoint_ns??``,g=[US],_=h===``?t:`${h}|${t}`,v=OC(JSON.stringify([_,l.toString(),t,US,`node_error_handler`,e.id]),r.id),y=`${_}:${v}`,b=[US,String(e.name),t,!1],x={langgraph_step:l,langgraph_node:t,langgraph_triggers:g,langgraph_path:b,langgraph_checkpoint_ns:y,checkpoint_ns:y};f.metadata!==void 0&&(x={...x,...f.metadata});let ee=[],te={checkpointId:r.id,checkpointNs:y,taskId:v,threadId:m.thread_id,runId:s.runId==null?void 0:String(s.runId),nodeAttempt:1};return{name:t,input:e.input,proc:p,subgraphs:f.subgraphs,writes:ee,config:{...Ql(Xl(s,{metadata:x,tags:f.tags,store:c.store??s.store}),{runName:t,callbacks:d?.getChild(`graph:step:${l}`),configurable:{[xS]:v,[gS]:e=>SF(e=>ee.push(...e),a,e),[vS]:(e,n=!1)=>xF(r,o,{name:t,writes:ee,triggers:g,path:b},e,n),[yS]:u??m.__pregel_checkpointer,[MS]:{...m[MS],[h]:r.id},[TS]:NF({pendingWrites:i??[],taskId:v,currentTaskInput:e.input,resumeMap:s.configurable?.[wS],namespaceHash:oF(y)}),[ES]:r.channel_values[zS],[jS]:new mC(String(e.name),n),checkpoint_id:void 0,checkpoint_ns:y}}),executionInfo:te},triggers:g,retry_policy:f.retryPolicy,cache_key:void 0,id:v,path:b,writers:f.getWriters()}}function jF(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=cF(t,i,!1)}catch(e){if(e.name===xC.unminifiable_name)return;throw e}else if(i in t)try{r[n]=cF(t,i,!1)}catch(e){if(e.name===xC.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=cF(t,i,!1),n=!0;break}catch(e){if(e.name===xC.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function MF(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new XS(e.node,n)}function NF({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i,pendingWritesIndex:a}){let o=a?a.nullResume:e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],s={callCounter:0,interruptCounter:-1,resume:(()=>{let n=a?(a.resumeByTaskId.get(t)??[]).flat():e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:o,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(s.nullResume)return delete s.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),o}};return s}var PF={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},FF=(e,t)=>`${e.start}${t}${e.end}`;function IF(e){if(e==null)return;let t={};if(e.metadata!=null)for(let[n,r]of Object.entries(e.metadata))sN.has(n)||(t[n]=r);let n=LN(e.tags);return n!=null&&(t.tags=n),Object.keys(t).length>0?t:void 0}function*LF(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e){if(i?.tags?.includes(`langsmith:hidden`))continue;let e={id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)},s=IF(i);s!=null&&(e.metadata=s),yield e}}function RF(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function zF(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=RF(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*BF(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:zF(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===FS).map(e=>e[1])})}function*VF(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(pP))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:lF(t,n),metadata:r,next:i.map(e=>e.name),tasks:HF(i,a,u,s),parentConfig:o?c(o):void 0}}function HF(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?zF(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function UF(e,t,n){console.log([`${FF(PF.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(lF(t,n),null,2)].join(``))}function WF(e,t){let n=t.length;console.log([`${FF(PF.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${FF(PF.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
|
|
185
185
|
`)].join(``))}function GF(e,t,n){let r={};for(let[e,i]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(i));console.log([`${FF(PF.blue,`[${e}:writes]`)}`,`\x1b[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length===1?``:`s`}:\x1b[0m\n`,Object.entries(r).map(([e,t])=>`- ${FF(PF.yellow,e)} -> ${t.map(e=>JSON.stringify(e)).join(`, `)}`).join(`
|
|
186
|
-
`)].join(``))}var KF=[`values`,`updates`,`messages`,`tools`,`custom`,`tasks`];function qF(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&(`source`in t||typeof t.step==`number`)&&!(`values`in t)&&!(`config`in t)}function JF(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,n]=e;if(typeof n!=`object`||!n)return{data:e};let r=n,i=typeof r.langgraph_node==`string`?r.langgraph_node:void 0,a=typeof r.run_id==`string`?r.run_id:void 0;return{data:a!=null&&typeof t==`object`&&t?{...t,run_id:a}:t,node:i}}function YF({namespace:e,mode:t,payload:n,seq:r}){let i=Date.now(),a={type:`event`};switch(t){case`messages`:{let{data:t,node:o}=JF(n);return[{...a,seq:r,method:`messages`,params:{namespace:e,timestamp:i,...o?{node:o}:{},data:t}}]}case`tools`:return[{...a,seq:r,method:`tools`,params:{namespace:e,timestamp:i,data:XF(n)}}];case`checkpoints`:return qF(n)?[{...a,seq:r,method:`checkpoints`,params:{namespace:e,timestamp:i,data:n}}]:[];case`values`:return[{...a,seq:r,method:`values`,params:{namespace:e,timestamp:i,data:n}}];case`updates`:{let t=ZF(n);return[{...a,seq:r,method:`updates`,params:{namespace:e,timestamp:i,...typeof t.node==`string`?{node:t.node}:{},data:t}}]}case`custom`:{let t=typeof n==`object`&&n&&!Array.isArray(n)&&`name`in n?n:{payload:n};return[{...a,seq:r,method:`custom`,params:{namespace:e,timestamp:i,data:t}}]}case`tasks`:return[{...a,seq:r,method:`tasks`,params:{namespace:e,timestamp:i,data:n}}];default:return[]}}function XF(e){if(typeof e!=`object`||!e)return{event:`tool-error`,tool_call_id:``,message:`Unexpected tools payload shape`};let t=e,n=String(t.toolCallId??``);switch(t.event){case`on_tool_start`:return{event:`tool-started`,tool_call_id:n,tool_name:String(t.name??`unknown`),input:t.input};case`on_tool_event`:return{event:`tool-output-delta`,tool_call_id:n,delta:typeof t.data==`string`?t.data:JSON.stringify(t.data??``)};case`on_tool_end`:return{event:`tool-finished`,tool_call_id:n,output:t.output};case`on_tool_error`:{let e=t.error;return{event:`tool-error`,tool_call_id:n,message:typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:String(e??`unknown error`)}}default:return{event:`tool-error`,tool_call_id:``,message:`Unknown tool event: ${String(t.event)}`}}}function ZF(e){if(typeof e!=`object`||!e)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[n,r]=t[0];return{node:n,values:typeof r==`object`&&r?r:{value:r}}}var QF=class extends ru{_abortController;_innerReader;constructor(e,t){let n=e.getReader(),r=t??new AbortController;super({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},$F=class extends ru{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,n=new Promise(e=>{t=e});super({start:e=>{t(e)}}),n.then(e=>{this.controller=e}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this._closed||!this.controller||(this.passthroughFn?.(e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){try{this.controller?.error(e)}finally{this._closed=!0}}},eI=class extends zr{name=`StreamToolsHandler`;awaitHandlers=!0;streamFn;runs={};constructor(e){super(),this.streamFn=e}handleToolStart(e,t,n,r,i,a,o,s){if(!a||i&&i.includes(`langsmith:hidden`))return;let c=a.langgraph_checkpoint_ns?.split(`|`)??[],l={ns:c,toolCallId:s,toolName:o??`unknown`,input:t};this.runs[n]=l,this.streamFn([c,`tools`,{event:`on_tool_start`,toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){let n=this.runs[t];n&&this.streamFn([n.ns,`tools`,{event:`on_tool_event`,toolCallId:n.toolCallId,name:n.toolName,data:e}])}handleToolEnd(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_end`,toolCallId:n.toolCallId,name:n.toolName,output:e}])}handleToolError(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_error`,toolCallId:n.toolCallId,name:n.toolName,error:e}])}};function tI(e){return JSON.stringify(e,function(e,t){let n=this[e];if(typeof n==`object`&&n&&`toDict`in n&&typeof n.toDict==`function`){let{type:e,data:t}=n.toDict();return{...t,type:e}}return t})}function nI(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function rI(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function iI(e){return!rI(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||``,checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function aI(e){if(rI(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([e])=>!e.startsWith(`__`))),n={...e,configurable:t};return delete n.callbacks,n}return e}function oI(e){let t={...e,checkpoint:iI(e.config),parent_checkpoint:iI(e.parentConfig),config:aI(e.config),parent_config:aI(e.parentConfig),tasks:e.tasks.map(e=>{if(rI(e.state)){let t=iI(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function sI(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${tI(e.data)}\n\n`))};try{for await(let t of e){let[e,n,i]=t,a=i;if(n===`debug`){let e=i;e.type===`checkpoint`&&(a={...e,payload:oI(e.payload)})}n===`checkpoints`&&(a=oI(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:nI(e)})}n.close()}})}function cI(...e){return new $F({passthroughFn:t=>{let n=t[1]===`checkpoints`&&qF(t[2]);for(let r of e)(r.modes.has(t[1])||n)&&r.push(t)},modes:new Set(e.flatMap(e=>Array.from(e.modes)))})}var lI=class{checkpointId;#e=new Set;constructor(e){this.checkpointId=e}#t(e){let t=e.includes(`:`)?e.slice(0,e.lastIndexOf(`:`)):e;return this.#e.has(t)?!1:(this.#e.add(t),!0)}async getCheckpoint(e,t,n){if(this.#t(e)){let e=[];for await(let r of t.list(n,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))e.push(r);return e.length>0?e[0]:void 0}return await t.getTuple(n)??void 0}},uI=Symbol.for(`INPUT_DONE`),dI=Symbol.for(`INPUT_RESUMING`),fI=25;function pI(e){if(!(typeof e!=`object`||!e)){if(rt.isInstance(e)){let t=e;t.id??(t.id=yr(),t.lc_kwargs!=null&&(t.lc_kwargs.id=t.id));return}if(Array.isArray(e)){for(let t of e)pI(t);return}}}function mI(e){return e===void 0||e===``?[]:e.split(`|`)}function hI(e){if(!e)return[];let t=``;for(let n of Object.keys(e))n!==``&&n.length>t.length&&(t=n);return mI(t)}var gI=class extends pN{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation(`get`,e)}async set(e){return this.enqueueOperation(`set`,e)}async clear(e){return this.enqueueOperation(`clear`,e)}async stop(){await this.queue}enqueueOperation(e,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>void 0,()=>void 0),n}},_I=class e{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;_exitDeltaWrites;_deltaChannelsWithOverwrite=new Set;_hasPersistedParent=!1;_initialCheckpointConfig;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status=`pending`;control;tasks={};stream;checkpointerPromises=new Set;isNested;resumeAtHead;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(e){let t=e.then(e=>(this.checkpointerPromises.delete(t),e),e=>{throw e});this.checkpointerPromises.add(t)}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(`__start__`in this.checkpoint.channel_versions)e=!0;else for(let t in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,t)){e=!0;break}let t=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,r=rC(this.input)&&this.input.resume!=null,i=this.input===dI,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(t||n||r||i||a)}get isReplaying(){return!this.skipDoneTasks}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer===void 0?this.checkpointerGetNextVersion=_F:this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer),this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.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 gI(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}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=cI(r,n.configurable[SS]));let i=n.configurable?!(`checkpoint_id`in n.configurable):!0,a=n.configurable?.[TS];n.configurable&&a&&(a.subgraphCounter>0&&(n=cP(n,{[kS]:[n.configurable[kS],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=n.configurable?.checkpoint_id,s=vS in(n.configurable??{});!s&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=cP(n,{checkpoint_ns:``,checkpoint_id:void 0}));let c=n;n.configurable?.checkpoint_id===void 0&&n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(c=cP(n,{checkpoint_id:n.configurable[MS][n.configurable?.checkpoint_ns]}));let l=mI(n.configurable?.checkpoint_ns),u;t.checkpointer?c.configurable?.checkpoint_id?u=await t.checkpointer.getTuple(c):n.configurable?.__pregel_replay_state?(u=await n.configurable[NS].getCheckpoint(n.configurable?.checkpoint_ns??``,t.checkpointer,c),n.configurable&&delete n.configurable[bS]):u=await t.checkpointer.getTuple(c):u=void 0;let d=u!==void 0;u||={config:n,checkpoint:nN(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]},c={...n,...u.config,configurable:{checkpoint_ns:``,...n.configurable,...u.config.configurable}};let f=u.parentConfig,p=rN(u.checkpoint),m={...u.metadata},h=u.pendingWrites??[],g=n.configurable?.checkpoint_ns,_=n.configurable?.[MS];typeof g==`string`&&g!==``&&typeof _==`object`&&_&&g in _&&h.length>0&&(h=h.filter(([,e])=>e!==IS));let v=!1,y=c.configurable?.thread_id,b=c.configurable?.checkpoint_ns??``;t.checkpointer&&o&&typeof y==`string`&&(v=(await t.checkpointer.getTuple({configurable:{thread_id:y,checkpoint_ns:b}}))?.config.configurable?.checkpoint_id===o&&m.source!==`update`&&m.source!==`fork`);let x=await wN(t.channelSpecs,p,{saver:t.checkpointer,config:c}),ee=(m.step??0)+1,te=ee+(n.recursionLimit??fI)+1,S={...p.channel_versions},ne=t.store?new fN(t.store):void 0;return ne&&await ne.start(),new e({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:m,checkpointConfig:c,prevCheckpointConfig:f,checkpointNamespace:l,channels:x,isNested:s,resumeAtHead:v,manager:t.manager,skipDoneTasks:i,step:ee,stop:te,checkpointPreviousVersions:S,checkpointPendingWrites:h,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:ne,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes,hasPersistedParent:d})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,t){let n=t;if(n.length===0)return;n.every(([e])=>e in oN)&&(n=Array.from(new Map(n.map(e=>[e[0],e])).values()));let r=!1;for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.channels[e].lc_graph_name===`UntrackedValue`){r=!0;break}let i=n;r&&(i=n.filter(([e])=>{let t=this.channels[e];return!t||t.lc_graph_name!==`UntrackedValue`}).map(([e,t])=>e===`__pregel_tasks`&&ZS(t)?[e,MF(t,this.channels)]:[e,t])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(t=>t[0]!==e);for(let[t,n]of i)this.checkpointPendingWrites.push([e,t,n]);for(let[e,t]of i){let n=this.channels[e];n!=null&&hN(n)&&pI(t)}let a=cP(this.checkpointConfig,{[kS]:this.config.configurable?.checkpoint_ns??``,[OS]:this.checkpoint.id});if(this.durability!==`exit`&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,n),!t.length||!this.cache||!this.tasks)return;let o=this.tasks[e];o==null||o.cache_key==null||t[0][0]===`__error__`||t[0][0]===`__interrupt__`||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,t,n=!1){let r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(`langsmith:hidden`))return;if(t.length>0)if(t[0][0]===`__interrupt__`){if(r.path?.[0]===`__pregel_push`&&r.path?.[r.path.length-1]===!0)return;let e=t.filter(e=>e[0]===FS).flatMap(e=>e[1]);this._emit([[`updates`,{[FS]:e}],[`values`,{[FS]:e}]])}else t[0][0]!==`__error__`&&this._emit(qN(GN(pF(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(qN(GN(BF([[r,t]],this.streamKeys),`tasks`)))}}async _matchCachedWrites(){if(!this.cache)return[];let e=[],t=([e,t])=>`ns:${e.join(`,`)}|key:${t}`,n=[],r={};for(let e of Object.values(this.tasks))e.cache_key!=null&&!e.writes.length&&(n.push([e.cache_key.ns,e.cache_key.key]),r[t([e.cache_key.ns,e.cache_key.key])]=e);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:n,value:a}of i){let i=r[t(n)];i!=null&&(i.writes.push(...a),e.push({task:i,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:t=[]}=e;if(this.status!==`pending`)throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![uI,dI].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new fC;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks),t=e.flatMap(e=>e.writes);this.updatedChannels=TF(this.checkpoint,this.channels,e,this.checkpointerGetNextVersion,this.triggerToNodes);for(let[e,n]of t){let t=this.channels[e];t!=null&&hN(t)&&eC(n)&&this._deltaChannelsWithOverwrite.add(e)}let n=await KN(GN(fF(this.outputKeys,t,this.channels),`values`));if(this._exitDeltaWrites!==void 0)for(let[e,t,n]of this.checkpointPendingWrites){let r=this.channels[t];r!=null&&hN(r)&&this._exitDeltaWrites.push([this.step,e,t,n])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),this._emitValuesWithCheckpointMeta(n),bF(this.checkpoint,this.interruptAfter,e))throw this.status=`interrupt_after`,new fC;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[bS]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;this.tasks=OF(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 n=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has(`checkpoints`)||this.stream.modes.has(`debug`))&&this._emit(await KN(GN(VF(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,n,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),`checkpoints`))),n.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(let[e,t,r]of this.checkpointPendingWrites){if(t===`__error__`||t===`__error_source_node__`||t===`__interrupt__`||t===`__resume__`)continue;let i=n.find(t=>t.id===e);i&&i.writes.push([t,r])}this._resumeErrorHandlersIfApplicable(),n=Object.values(this.tasks);for(let e of n)e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(n.every(e=>e.writes.length>0))return this.tick({inputKeys:t});if(bF(this.checkpoint,this.interruptBefore,n))throw this.status=`interrupt_before`,new fC;if(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`)){let e=await KN(GN(LF(n),`tasks`));this._emit(e)}return!0}async finishAndHandleError(e){this.durability===`exit`&&(!this.isNested||e!==void 0||this.checkpointNamespace.every(e=>!e.includes(`:`)))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=lF(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(e=>e.writes.length>0)&&(this.updatedChannels=TF(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(qN(GN(fF(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),vC(e)&&!e.interrupts.length&&this._emit([[`updates`,{[FS]:[]}],[`values`,{[FS]:[]}]],this.#e())),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&bF(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=kF([US,e.path??[],t,e.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!r)return;if(this.interruptBefore?.length>0&&bF(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`))&&this._emit(qN(GN(LF([r]),`tasks`))),this.debug&&WF(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});let i=await this._matchCachedWrites();for(let{task:e}of i)this._outputWrites(e.id,e.writes,!0);return r}getErrorHandlerNode(e){return this.nodes[e]?.errorHandlerNode}isErrorHandlerNode(e){return this.nodes[e]?.isErrorHandler===!0}scheduleErrorHandler(e,t){let n=this.getErrorHandlerNode(String(e.name));if(!n)return;let r=AF(e,n,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(r!==void 0)return this.tasks[r.id]=r,this._emit(qN(GN(LF([r]),`tasks`))),this.debug&&WF(this.step,[r]),r}_resumeErrorHandlersIfApplicable(){let e=new Map;for(let[t,n]of this.checkpointPendingWrites){if(n!==`__error_source_node__`)continue;let r=this.checkpointPendingWrites.find(([e,n])=>e===t&&n===`__error__`);if(r===void 0)continue;let i=r[2],a=Error(i?.message??String(i));i?.name&&(a.name=i.name),e.set(t,a)}for(let[t,n]of e){let e=this.tasks[t];e!==void 0&&this.getErrorHandlerNode(String(e.name))&&(e.writes.length===0&&e.writes.push([fS,{message:n.message,name:n.name}]),this.scheduleErrorHandler(e,n))}}_suppressInterrupt(e){return vC(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[TS];if(n&&n.nullResume!==void 0&&this.putWrites(GS,[[IS,n.nullResume]]),rC(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(sF)&&(this.config.configurable??={},this.config.configurable[wS]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of uF(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new bC(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===GS).map(e=>e.slice(1));r.length>0&&TF(this.checkpoint,this.channels,[{name:dS,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=rC(this.input),a=i&&r.length>0,o=this.isReplaying&&(this.isNested&&t?.checkpoint_ns!==void 0&&t?.checkpoint_ns!==``&&t?.checkpoint_map!==void 0&&t.checkpoint_ns in t.checkpoint_map||!(i&&this.input.resume!=null||t?.__pregel_resuming===!0||this.resumeAtHead));o&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==IS));let s=this.isResuming;if(s||a){let e={...this.checkpoint.versions_seen[FS]};for(let t in this.channels)Object.prototype.hasOwnProperty.call(this.channels,t)&&this.checkpoint.channel_versions[t]!==void 0&&(e[t]=this.checkpoint.channel_versions[t]);this.checkpoint.versions_seen[FS]=e,o&&this.checkpointMetadata.source!==`update`&&this.checkpointMetadata.source!==`fork`&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==FS),await this._putCheckpoint({source:`fork`}));let t=await KN(GN(fF(this.outputKeys,!0,this.channels),`values`));s?this.input=dI:a&&(await this._putCheckpoint({source:`input`}),this.input=uI),this._emitValuesWithCheckpointMeta(t)}else{let t=await KN(dF(e,this.input));if(t.length>0){let e=OF(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=TF(this.checkpoint,this.channels,Object.values(e).concat([{name:dS,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);let n=t.filter(([e])=>{let t=this.channels[e];return t!=null&&hN(t)});for(let[e,t]of n)eC(t)&&this._deltaChannelsWithOverwrite.add(e);if(n.length>0)if(this._exitDeltaWrites!==void 0)for(let[e,t]of n)this._exitDeltaWrites.push([this.step,GS,e,t]);else this.checkpointer!=null&&this.putWrites(GS,n);await this._putCheckpoint({source:`input`}),this.input=uI}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=uI;else throw new bC(`Received no input writes for ${JSON.stringify(e,null,2)}`)}if(!this.isNested){let e;if(o){let t=this.checkpoint.id;(this.checkpointMetadata.source===`update`||this.checkpointMetadata.source===`fork`)&&this.prevCheckpointConfig&&(t=this.prevCheckpointConfig.configurable?.checkpoint_id??t),e=new lI(t)}this.config=cP(this.config,{[bS]:this.isResuming,[NS]:e})}}#e(){let e=this.checkpointNamespace;if(!(e.length===0||e.length===1&&e[0]===``)||this.config.configurable?.__pregel_stream===void 0)return e;let t=hI(this.config.configurable?.[MS]);return t.length>0?t:e}_emit(e,t=this.checkpointNamespace){for(let[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([t,n,r]),(n===`checkpoints`||n===`tasks`)&&this.stream.modes.has(`debug`)){let e=n===`checkpoints`?this.step-1:this.step,i=new Date().toISOString(),a=n===`checkpoints`?`checkpoint`:typeof r==`object`&&r&&`result`in r?`task_result`:`task`;this.stream.push([t,`debug`,{step:e,type:a,timestamp:i,payload:r}])}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let e=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...e?{parent_id:e}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(e){let t=this._currentCheckpointMeta();for(let[n,r]of e)n===`values`&&t?.checkpoint!=null&&!this.stream.modes.has(`checkpoints`)&&this.stream.push([this.checkpointNamespace,`checkpoints`,t.checkpoint]),this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r])}_putCheckpoint(e){let t=this.checkpointMetadata===e,n=this.checkpointer!=null&&(this.durability!==`exit`||t),r=e=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=cP(this.checkpointConfig,{[kS]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=oP(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:rN(e),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}},i;if(t)i={...this.checkpointMetadata.counters_since_delta_snapshot??{}};else{let t=this.checkpointMetadata.counters_since_delta_snapshot??{};i={};let n=this.updatedChannels??new Set;for(let e in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,e)||!hN(this.channels[e]))continue;let[r,a]=t[e]??[0,0];i[e]=[n.has(e)?r+1:r,a+1]}this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}}let a=n?SN(this.channels,i):new Set;if(n)for(let e of this._deltaChannelsWithOverwrite)a.add(e);this.checkpoint=CN(this.checkpoint,n?this.channels:void 0,this.step,{id:t?this.checkpoint.id:void 0,channelsToSnapshot:a,updatedChannels:this.updatedChannels,getNextVersion:n?e=>this.checkpointerGetNextVersion(e):void 0});for(let e of a)i[e]=[0,0],this._deltaChannelsWithOverwrite.delete(e);let o={};for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let[t,n]=i[e];(t!==0||n!==0)&&(o[e]=[t,n])}Object.keys(o).length>0?this.checkpointMetadata.counters_since_delta_snapshot=o:delete this.checkpointMetadata.counters_since_delta_snapshot,n&&r(this.checkpoint),t||(this.step+=1)}async _putExitDeltaWrites(){if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;let e=this.checkpointMetadata.counters_since_delta_snapshot??{},t=SN(this.channels,e);for(let e of this._deltaChannelsWithOverwrite)t.add(e);let n=this._exitDeltaWrites.filter(([,,e])=>!t.has(e));if(n.length===0)return;let r;if(this._hasPersistedParent)r=this._initialCheckpointConfig;else{let e=nN();e.id=this.checkpointIdSaved??e.id,e.ts=new Date().toISOString();let t=cP(this._initialCheckpointConfig,{[OS]:void 0});r=cP(this._initialCheckpointConfig,{[OS]:e.id}),this._trackCheckpointerPromise(this.checkpointer.put(t,e,{source:`loop`,step:-2,parents:{}},{})),this.checkpointConfig=r}let i=cP(r,{[kS]:this.config.configurable?.checkpoint_ns??``,[OS]:r.configurable?.[OS]}),a=new Map,o=[];for(let[e,t,r,i]of n){let n=`${e}\u0000${t}`,s=a.get(n);s===void 0&&(s=[],a.set(n,s),o.push({key:n,step:e,tid:t})),s.push([r,i])}for(let{key:e,step:t,tid:n}of o){let r=xN(t,n);this._trackCheckpointerPromise(this.checkpointer.putWrites(i,a.get(e),r))}}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let e=cP(this.checkpointConfig,{[kS]:this.config.configurable?.checkpoint_ns??``,[OS]:this.checkpoint.id}),t={};for(let[e,n,r]of this.checkpointPendingWrites)t[e]??=[],t[e].push([n,r]);for(let[n,r]of Object.entries(t))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,r,n))}_matchWrites(e){for(let[t,n,r]of this.checkpointPendingWrites){if(n===`__error__`||n===`__interrupt__`||n===`__resume__`)continue;let i=Object.values(e).find(e=>e.id===t);i&&i.writes.push([n,r])}for(let t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}};function vI(e){return _t(e?.message)}function yI(e,t,n){if(!e)return;let r=e.langgraph_checkpoint_ns,i=e.checkpoint_ns,a=r??i;if(a)return[a.split(`|`),{tags:t,name:n,...e}]}var bI=class extends zr{name=`StreamMessagesHandler`;streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;n!=null&&(wt(t)?i??=`run-${n}-tool-${t.tool_call_id}`:((i==null||i===`run-${n}`)&&(i=this.stableMessageIdMap[n]??i??`run-${n}`),this.stableMessageIdMap[n]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],`messages`,[t,e[1]]])}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=yI(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(vI(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new nn({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];_t(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=yI(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((_t(e)||vt(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(_t(t)||vt(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(_t(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)_t(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(_t(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)_t(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function xI(e){if(`response_metadata`in e&&typeof e.response_metadata==`object`&&e.response_metadata!=null)return e.response_metadata}function SI(e){if(`usage_metadata`in e&&typeof e.usage_metadata==`object`&&e.usage_metadata!=null)return e.usage_metadata}function CI(e){switch(e.type){case`text`:return{type:`text`,text:``};case`reasoning`:return{type:`reasoning`,reasoning:``};case`tool_call`:case`tool_call_chunk`:return{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:``};default:return e}}function wI(e){switch(e.type){case`text`:{let t=typeof e.text==`string`?e.text:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`text-delta`,text:t}}:void 0}case`reasoning`:{let t=typeof e.reasoning==`string`?e.reasoning:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`reasoning-delta`,reasoning:t}}:void 0}case`tool_call_chunk`:return{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`block-delta`,fields:{...e,type:`tool_call_chunk`}}};default:return}}var TI=class extends zr{name=`StreamProtocolMessagesHandler`;streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;awaitHandlers=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let n=e.id;return t!=null&&(xt.isInstance(e)?n??=`run-${t}-tool-${e.tool_call_id}`:((n==null||n===`run-${t}`)&&(n=this.stableMessageIdMap[t]??n??`run-${t}`),this.stableMessageIdMap[t]??=n)),n!==e.id&&(e.id=n,e.lc_kwargs.id=n),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,n){let r=n==null?e[1]:{...e[1],run_id:n};this.streamFn([e[0],`messages`,[t,r]])}emitFinalMessage(e,t,n,r=!1){let i=t.id??(n==null?void 0:this.stableMessageIdMap[n]);if(r&&i!=null&&this.seen[i]!==void 0)return;let a=this.normalizeMessageId(t,n),o=t.type===`human`?`human`:t.type===`system`?`system`:t.type===`tool`?`tool`:`ai`,s=o===`tool`&&xt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:`message-start`,...a==null?{}:{id:a},...o===`ai`?{}:{role:o},...typeof s==`string`?{tool_call_id:s}:{}},n),(Array.isArray(t.content)?t.content:typeof t.content==`string`&&t.content.length>0?[{type:`text`,text:t.content}]:[]).forEach((t,r)=>{let i=typeof t.index==`number`?t.index:r;this.emit(e,{event:`content-block-start`,index:i,content:CI(t)},n);let a=wI({...t,index:i});a!=null&&this.emit(e,a,n),this.emit(e,{event:`content-block-finish`,index:i,content:t},n)}),this.emit(e,{event:`message-finish`,...SI(t)==null?{}:{usage:SI(t)},...xI(t)==null?{}:{responseMetadata:xI(t)}},n)}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split(`|`),{tags:a,name:s,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e;if(e.event===`message-start`){this.streamedRunIds.add(t);let n=e.id??`run-${t}`;this.seen[n]=!0,this.stableMessageIdMap[t]??=n,e.id??(r={...e,id:n})}this.emit(n,r,t)}handleLLMEnd(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e.generations?.[0]?.[0],i=rt.isInstance(r?.message)?r.message:void 0;if(i!=null)if(this.streamedRunIds.has(t)){let e=this.normalizeMessageId(i,t);e!=null&&(this.seen[e]=i)}else this.emitFinalMessage(n,i,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split(`|`),{tags:i,name:s,...a}],typeof t==`object`)){for(let e of Object.values(t))if((rt.isInstance(e)||ht.isInstance(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(rt.isInstance(t)||ht.isInstance(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n===void 0)return;let r=e=>{rt.isInstance(e)&&!xt.isInstance(e)&&this.emitFinalMessage(n,e,t,!0)};if(rt.isInstance(e))r(e);else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))if(Array.isArray(t))for(let e of t)r(e);else r(t);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}},EI=class{active=!0;lastProgress=Date.now();refreshOn;constructor(e){this.refreshOn=e}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn===`auto`&&(this.lastProgress=Date.now())}close(){this.active=!1}},DI=class extends zr{name=`IdleProgressCallbackHandler`;awaitHandlers=!1;#e;constructor(e){super(),this.#e=e}#t=()=>{this.#e.autoTouch()};handleLLMStart=this.#t;handleChatModelStart=this.#t;handleLLMNewToken=this.#t;handleLLMEnd=this.#t;handleLLMError=this.#t;handleChainStart=this.#t;handleChainEnd=this.#t;handleChainError=this.#t;handleToolStart=this.#t;handleToolEnd=this.#t;handleToolError=this.#t;handleText=this.#t;handleRetrieverStart=this.#t;handleRetrieverEnd=this.#t;handleRetrieverError=this.#t;handleCustomEvent=this.#t};function OI(e,t,n,r){let i=e.configurable??{},a={},o=i[gS];typeof o==`function`&&(a[gS]=e=>{if(t.active)return e&&e.length&&t.autoTouch(),o(e)});let s=i[_S];typeof s==`function`&&(a[_S]=(...e)=>{if(!t.active)throw Error(`Node "${r}" attempt was cancelled after its timeout fired`);return t.autoTouch(),s(...e)});let c={...Object.keys(a).length>0?cP(e,a):e};if(c.heartbeat=()=>{n.idleTimeout!==void 0&&t.touch()},typeof c.writer==`function`){let e=c.writer;c.writer=(n=>{if(t.active)return t.autoTouch(),e(n)})}if((n.refreshOn??`auto`)===`auto`&&n.idleTimeout!==void 0){let e=new DI(t),n=c.callbacks;if(n===void 0)c.callbacks=[e];else if(Array.isArray(n))c.callbacks=[...n,e];else{let t=n.copy();t.addHandler(e,!0),c.callbacks=t}}return c}async function kI(e,t,n,r){let i=new EI(n.refreshOn??`auto`),a=new AbortController,{signal:o,dispose:s}=uP(t.signal,a.signal),c=OI({...t,signal:o},i,n,String(e.name)),l=Date.now(),u=r(c).then(e=>({type:`ok`,value:e}),e=>({type:`err`,error:e})),d,f,p=()=>{d!==void 0&&clearTimeout(d),f!==void 0&&clearTimeout(f)},m=new Promise(e=>{if(n.runTimeout!==void 0&&(d=setTimeout(()=>e({type:`timeout`,kind:`run`}),n.runTimeout)),n.idleTimeout!==void 0){let t=n.idleTimeout,r=()=>{let n=i.lastProgress+t-Date.now();n<=0?e({type:`timeout`,kind:`idle`}):f=setTimeout(r,n)};f=setTimeout(r,t)}}),h;try{h=await Promise.race([u,m])}finally{p()}if(h.type!==`timeout`){let e=Date.now();n.runTimeout!==void 0&&e-l>=n.runTimeout?h={type:`timeout`,kind:`run`}:n.idleTimeout!==void 0&&e-i.lastProgress>=n.idleTimeout&&(h={type:`timeout`,kind:`idle`})}if(h.type===`ok`)return s?.(),h.value;if(h.type===`err`)throw s?.(),h.error;let g=Date.now()-l;throw i.close(),e.writes.splice(0,e.writes.length),a.abort(),s?.(),new yC({node:String(e.name),elapsed:g,kind:h.kind,runTimeout:n.runTimeout,idleTimeout:n.idleTimeout})}var AI=[400,401,402,403,404,405,406,407,409],jI=e=>{if(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`)||e.name===`AbortError`||e.name===`GraphValueError`||e?.code===`ECONNABORTED`)return!1;let t=e?.response?.status??e?.status;return!(t&&AI.includes(+t)||e?.error?.code===`insufficient_quota`)};async function MI(e,t,n,r){let i=e.retry_policy??t,a=0,o,s,c=e.config??{};n&&(c=cP(c,n)),c={...c,signal:r};let l=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:l});!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{s=e.timeout===void 0?await e.proc.invoke(e.input,c):await kI(e,c,e.timeout,t=>e.proc.invoke(e.input,t));break}catch(t){if(o=t,o.pregelTaskId=e.id,gC(o)){let t=c?.configurable?.checkpoint_ns,n=o.command;if(n.graph===t){for(let t of e.writers)await t.invoke(n,c);o=void 0;break}else if(n.graph===nC.PARENT){let e=UN(t);o.command=new nC({...o.command,graph:e})}}if(_C(o)||i===void 0||(a+=1,a>=(i.maxAttempts??3))||!(i.retryOn??jI)(o))break;let n=i.initialInterval??500,r=Math.min(i.maxInterval??128e3,n*(i.backoffFactor??2)**(a-1)),s=i.jitter??!0?r+Math.random()*1e3:r;await new Promise(e=>setTimeout(e,s));let u=o.name??o.constructor.unminifiable_name??o.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${a}) after ${u}: ${o}`),c=cP(c,{[bS]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:a+1,nodeFirstAttemptTime:l})}}return{task:e,result:s,error:o,signalAborted:r?.aborted}}var NI=Symbol.for(`promiseAdded`);function PI(){let e={next:()=>void 0,wait:Promise.resolve(NI)};function t(n){e.next=()=>{e.wait=new Promise(t),n(NI)}}return e.wait=new Promise(t),e}var FI=class{nodeFinished;loop;handledExceptions=new WeakSet;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks),d=u.filter(e=>e.writes.length===0),{signals:f,disposeCombinedSignal:p}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),m=this._executeTasksWithRetry(d,{signals:f,retryPolicy:n,maxConcurrency:i});for await(let{task:e,error:t,signalAborted:n}of m)this._commit(e,t),!(t!==void 0&&this.handledExceptions.has(t))&&(vC(t)||_C(t)&&!vC(o)?o=t:t&&(a.size===0||!n)&&(s.abort(),a.add(t)));if(p?.(),r?.(this.loop.step,u.map(e=>e.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(vC(o)||dC(o)||_C(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},i=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:o,dispose:s}=uP(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=cP(this.loop.config,{[PS]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=PI(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:n,scheduleTask:async(e,t,n)=>this.loop.acceptPush(e,t,n)};if(i?.composedAbortSignal?.aborted)throw Error(`Abort`);let c=0,l,u=uP(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((e,t)=>{l=()=>t(Error(`Abort`)),u.signal?.addEventListener(`abort`,l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(r??e.length)&&c<e.length;c+=1){let t=e[c];o[t.id]=MI(t,n,{[_S]:II?.bind(s,this,t)},i?.composedAbortSignal).catch(e=>({task:t,error:e,signalAborted:i?.composedAbortSignal?.aborted}))}let t=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);if(t===NI)continue;let f=t,{task:p,error:m}=f;if(m!==void 0&&!_C(m)&&!this.loop.isErrorHandlerNode(String(p.name))&&this.loop.getErrorHandlerNode(String(p.name))!==void 0){let e=this.loop.scheduleErrorHandler(p,m);e!==void 0&&(o[e.id]=MI(e,n,{[_S]:II?.bind(s,this,e)},i?.composedAbortSignal).catch(t=>({task:e,error:t,signalAborted:i?.composedAbortSignal?.aborted})),a.next())}yield f,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id]}}_shouldRouteToErrorHandler(e){let t=String(e.name);return this.loop.isErrorHandlerNode(t)?!1:this.loop.getErrorHandlerNode(t)!==void 0}_commit(e,t){if(t!==void 0)if(vC(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[FS,e]),r=e.writes.filter(e=>e[0]===IS);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else dC(t)?e.writes.length&&this.loop.putWrites(e.id,e.writes):_C(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):(e.writes.push([fS,{message:t.message,name:t.name}]),this._shouldRouteToErrorHandler(e)&&(e.writes.push([pS,String(e.name)]),this.handledExceptions.add(t)),this.loop.putWrites(e.id,e.writes));else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(`langsmith:hidden`))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([LS,null]),this.loop.putWrites(e.id,e.writes)}};async function II(e,t,n,r,i,a={}){let o=t.config?.configurable?.[TS];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new mF({func:n,name:r,input:i,cache:a.cache,retry:a.retry,timeout:a.timeout,callbacks:a.callbacks}),l=await this.scheduleTask(t,s,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let e=l.writes.filter(([e])=>e===RS),t=l.writes.filter(([e])=>e===fS);if(e.length>0){if(e.length===1)return Promise.resolve(e[0][1]);throw Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(t.length>0){if(t.length===1){let e=t[0][1],n=e instanceof Error?e:Error(String(e));return Promise.reject(n)}throw Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let t=MI(l,a.retry,{[_S]:II.bind(this,e,l)});return this.executingTasksMap[l.id]=t,this.barrier.next(),t.then(({result:e,error:t})=>t?Promise.reject(t):e)}}var LI=Symbol.for(`langgraph.stream_channel`),RI=class e{[LI]=!0;channelName;#e=[];#t=[];#n=!1;#r;#i;constructor(e){this.channelName=e}static local(){return new e}static remote(t){return new e(t)}static isInstance(e){return typeof e==`object`&&!!e&&LI in e&&e[LI]===!0}push(e){this.#e.push(e),this.#a(),this.#i?.(e)}iterate(e=0){let t=e;return{next:async()=>{for(;;){if(t<this.#e.length)return{value:this.#e[t++],done:!1};if(this.#n){if(this.#r)throw this.#r;return{value:void 0,done:!0}}await new Promise(e=>this.#t.push(e))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){let t=new TextEncoder,n=this.iterate(e.startAt),r=e.event??this.channelName,i=e.serialize??(e=>JSON.stringify(e)??`null`);return new ReadableStream({async pull(e){try{let a=await n.next();if(a.done){e.close();return}let o=[];r!=null&&o.push(`event: ${r}`);for(let e of i(a.value).split(/\r\n|\r|\n/))o.push(`data: ${e}`);e.enqueue(t.encode(`${o.join(`
|
|
186
|
+
`)].join(``))}var KF=[`values`,`updates`,`messages`,`tools`,`custom`,`tasks`];function qF(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&(`source`in t||typeof t.step==`number`)&&!(`values`in t)&&!(`config`in t)}function JF(e){if(!Array.isArray(e)||e.length!==2)return{data:e};let[t,n]=e;if(typeof n!=`object`||!n)return{data:e};let r=n,i=typeof r.langgraph_node==`string`?r.langgraph_node:void 0,a=typeof r.run_id==`string`?r.run_id:void 0;return{data:a!=null&&typeof t==`object`&&t?{...t,run_id:a}:t,node:i}}function YF({namespace:e,mode:t,payload:n,seq:r}){let i=Date.now(),a={type:`event`};switch(t){case`messages`:{let{data:t,node:o}=JF(n);return[{...a,seq:r,method:`messages`,params:{namespace:e,timestamp:i,...o?{node:o}:{},data:t}}]}case`tools`:return[{...a,seq:r,method:`tools`,params:{namespace:e,timestamp:i,data:XF(n)}}];case`checkpoints`:return qF(n)?[{...a,seq:r,method:`checkpoints`,params:{namespace:e,timestamp:i,data:n}}]:[];case`values`:return[{...a,seq:r,method:`values`,params:{namespace:e,timestamp:i,data:n}}];case`updates`:{let t=ZF(n);return[{...a,seq:r,method:`updates`,params:{namespace:e,timestamp:i,...typeof t.node==`string`?{node:t.node}:{},data:t}}]}case`custom`:{let t=typeof n==`object`&&n&&!Array.isArray(n)&&`name`in n?n:{payload:n};return[{...a,seq:r,method:`custom`,params:{namespace:e,timestamp:i,data:t}}]}case`tasks`:return[{...a,seq:r,method:`tasks`,params:{namespace:e,timestamp:i,data:n}}];default:return[]}}function XF(e){if(typeof e!=`object`||!e)return{event:`tool-error`,tool_call_id:``,message:`Unexpected tools payload shape`};let t=e,n=String(t.toolCallId??``);switch(t.event){case`on_tool_start`:return{event:`tool-started`,tool_call_id:n,tool_name:String(t.name??`unknown`),input:t.input};case`on_tool_event`:return{event:`tool-output-delta`,tool_call_id:n,delta:typeof t.data==`string`?t.data:JSON.stringify(t.data??``)};case`on_tool_end`:return{event:`tool-finished`,tool_call_id:n,output:t.output};case`on_tool_error`:{let e=t.error;return{event:`tool-error`,tool_call_id:n,message:typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:String(e??`unknown error`)}}default:return{event:`tool-error`,tool_call_id:``,message:`Unknown tool event: ${String(t.event)}`}}}function ZF(e){if(typeof e!=`object`||!e)return{values:{}};let t=Object.entries(e);if(t.length===0)return{values:{}};let[n,r]=t[0];return{node:n,values:typeof r==`object`&&r?r:{value:r}}}var QF=class extends ru{_abortController;_innerReader;constructor(e,t){let n=e.getReader(),r=t??new AbortController;super({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},$F=class extends ru{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,n=new Promise(e=>{t=e});super({start:e=>{t(e)}}),n.then(e=>{this.controller=e}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this._closed||!this.controller||(this.passthroughFn?.(e),this.controller.enqueue(e))}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){try{this.controller?.error(e)}finally{this._closed=!0}}},eI=class extends zr{name=`StreamToolsHandler`;awaitHandlers=!0;streamFn;runs={};constructor(e){super(),this.streamFn=e}handleToolStart(e,t,n,r,i,a,o,s){if(!a||i&&i.includes(`langsmith:hidden`))return;let c=a.langgraph_checkpoint_ns?.split(`|`)??[],l={ns:c,toolCallId:s,toolName:o??`unknown`,input:t};this.runs[n]=l,this.streamFn([c,`tools`,{event:`on_tool_start`,toolCallId:l.toolCallId,name:l.toolName,input:t}])}handleToolEvent(e,t){let n=this.runs[t];n&&this.streamFn([n.ns,`tools`,{event:`on_tool_event`,toolCallId:n.toolCallId,name:n.toolName,data:e}])}handleToolEnd(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_end`,toolCallId:n.toolCallId,name:n.toolName,output:e}])}handleToolError(e,t){let n=this.runs[t];delete this.runs[t],n&&this.streamFn([n.ns,`tools`,{event:`on_tool_error`,toolCallId:n.toolCallId,name:n.toolName,error:e}])}};function tI(e){return JSON.stringify(e,function(e,t){let n=this[e];if(typeof n==`object`&&n&&`toDict`in n&&typeof n.toDict==`function`){let{type:e,data:t}=n.toDict();return{...t,type:e}}return t})}function nI(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function rI(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function iI(e){return!rI(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||``,checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function aI(e){if(rI(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([e])=>!e.startsWith(`__`))),n={...e,configurable:t};return delete n.callbacks,n}return e}function oI(e){let t={...e,checkpoint:iI(e.config),parent_checkpoint:iI(e.parentConfig),config:aI(e.config),parent_config:aI(e.parentConfig),tasks:e.tasks.map(e=>{if(rI(e.state)){let t=iI(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function sI(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${tI(e.data)}\n\n`))};try{for await(let t of e){let[e,n,i]=t,a=i;if(n===`debug`){let e=i;e.type===`checkpoint`&&(a={...e,payload:oI(e.payload)})}n===`checkpoints`&&(a=oI(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:nI(e)})}n.close()}})}function cI(...e){return new $F({passthroughFn:t=>{let n=t[1]===`checkpoints`&&qF(t[2]);for(let r of e)(r.modes.has(t[1])||n)&&r.push(t)},modes:new Set(e.flatMap(e=>Array.from(e.modes)))})}var lI=class{checkpointId;#e=new Set;constructor(e){this.checkpointId=e}#t(e){let t=e.includes(`:`)?e.slice(0,e.lastIndexOf(`:`)):e;return this.#e.has(t)?!1:(this.#e.add(t),!0)}async getCheckpoint(e,t,n){if(this.#t(e)){let e=[];for await(let r of t.list(n,{before:{configurable:{checkpoint_id:this.checkpointId}},limit:1}))e.push(r);return e.length>0?e[0]:void 0}return await t.getTuple(n)??void 0}},uI=Symbol.for(`INPUT_DONE`),dI=Symbol.for(`INPUT_RESUMING`),fI=25;function pI(e){if(!(typeof e!=`object`||!e)){if(rt.isInstance(e)){let t=e;t.id??(t.id=yr(),t.lc_kwargs!=null&&(t.lc_kwargs.id=t.id));return}if(Array.isArray(e)){for(let t of e)pI(t);return}}}function mI(e){return e===void 0||e===``?[]:e.split(`|`)}function hI(e){if(!e)return[];let t=``;for(let n of Object.keys(e))n!==``&&n.length>t.length&&(t=n);return mI(t)}var gI=class extends pN{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation(`get`,e)}async set(e){return this.enqueueOperation(`set`,e)}async clear(e){return this.enqueueOperation(`clear`,e)}async stop(){await this.queue}enqueueOperation(e,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>void 0,()=>void 0),n}},_I=class e{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;_exitDeltaWrites;_deltaChannelsWithOverwrite=new Set;_hasPersistedParent=!1;_initialCheckpointConfig;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status=`pending`;control;tasks={};stream;checkpointerPromises=new Set;isNested;resumeAtHead;_checkpointerChainedPromise=Promise.resolve();_trackCheckpointerPromise(e){let t=e.then(e=>(this.checkpointerPromises.delete(t),e),e=>{throw e});this.checkpointerPromises.add(t)}store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(`__start__`in this.checkpoint.channel_versions)e=!0;else for(let t in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,t)){e=!0;break}let t=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,r=rC(this.input)&&this.input.resume!=null,i=this.input===dI,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(t||n||r||i||a)}get isReplaying(){return!this.skipDoneTasks}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer===void 0?this.checkpointerGetNextVersion=_F:this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer),this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.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 gI(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}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=cI(r,n.configurable[SS]));let i=!n.configurable||!(`checkpoint_id`in n.configurable),a=n.configurable?.[TS];n.configurable&&a&&(a.subgraphCounter>0&&(n=cP(n,{[kS]:[n.configurable[kS],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=n.configurable?.checkpoint_id,s=vS in(n.configurable??{});!s&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=cP(n,{checkpoint_ns:``,checkpoint_id:void 0}));let c=n;n.configurable?.checkpoint_id===void 0&&n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(c=cP(n,{checkpoint_id:n.configurable[MS][n.configurable?.checkpoint_ns]}));let l=mI(n.configurable?.checkpoint_ns),u;t.checkpointer?c.configurable?.checkpoint_id?u=await t.checkpointer.getTuple(c):n.configurable?.__pregel_replay_state?(u=await n.configurable[NS].getCheckpoint(n.configurable?.checkpoint_ns??``,t.checkpointer,c),n.configurable&&delete n.configurable[bS]):u=await t.checkpointer.getTuple(c):u=void 0;let d=u!==void 0;u||={config:n,checkpoint:nN(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]},c={...n,...u.config,configurable:{checkpoint_ns:``,...n.configurable,...u.config.configurable}};let f=u.parentConfig,p=rN(u.checkpoint),m={...u.metadata},h=u.pendingWrites??[],g=n.configurable?.checkpoint_ns,_=n.configurable?.[MS];typeof g==`string`&&g!==``&&typeof _==`object`&&_&&g in _&&h.length>0&&(h=h.filter(([,e])=>e!==IS));let v=!1,y=c.configurable?.thread_id,b=c.configurable?.checkpoint_ns??``;t.checkpointer&&o&&typeof y==`string`&&(v=(await t.checkpointer.getTuple({configurable:{thread_id:y,checkpoint_ns:b}}))?.config.configurable?.checkpoint_id===o&&m.source!==`update`&&m.source!==`fork`);let x=await wN(t.channelSpecs,p,{saver:t.checkpointer,config:c}),ee=(m.step??0)+1,te=ee+(n.recursionLimit??fI)+1,S={...p.channel_versions},ne=t.store?new fN(t.store):void 0;return ne&&await ne.start(),new e({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:p,checkpointMetadata:m,checkpointConfig:c,prevCheckpointConfig:f,checkpointNamespace:l,channels:x,isNested:s,resumeAtHead:v,manager:t.manager,skipDoneTasks:i,step:ee,stop:te,checkpointPreviousVersions:S,checkpointPendingWrites:h,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:ne,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes,hasPersistedParent:d})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this._trackCheckpointerPromise(this._checkpointerChainedPromise)}putWrites(e,t){let n=t;if(n.length===0)return;n.every(([e])=>e in oN)&&(n=Array.from(new Map(n.map(e=>[e[0],e])).values()));let r=!1;for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.channels[e].lc_graph_name===`UntrackedValue`){r=!0;break}let i=n;r&&(i=n.filter(([e])=>{let t=this.channels[e];return!t||t.lc_graph_name!==`UntrackedValue`}).map(([e,t])=>e===`__pregel_tasks`&&ZS(t)?[e,MF(t,this.channels)]:[e,t])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(t=>t[0]!==e);for(let[t,n]of i)this.checkpointPendingWrites.push([e,t,n]);for(let[e,t]of i){let n=this.channels[e];n!=null&&hN(n)&&pI(t)}let a=cP(this.checkpointConfig,{[kS]:this.config.configurable?.checkpoint_ns??``,[OS]:this.checkpoint.id});if(this.durability!==`exit`&&this.checkpointer!=null&&this._trackCheckpointerPromise(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,n),!t.length||!this.cache||!this.tasks)return;let o=this.tasks[e];o==null||o.cache_key==null||t[0][0]===`__error__`||t[0][0]===`__interrupt__`||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,t,n=!1){let r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(`langsmith:hidden`))return;if(t.length>0)if(t[0][0]===`__interrupt__`){if(r.path?.[0]===`__pregel_push`&&r.path?.[r.path.length-1]===!0)return;let e=t.filter(e=>e[0]===FS).flatMap(e=>e[1]);this._emit([[`updates`,{[FS]:e}],[`values`,{[FS]:e}]])}else t[0][0]!==`__error__`&&this._emit(qN(GN(pF(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(qN(GN(BF([[r,t]],this.streamKeys),`tasks`)))}}async _matchCachedWrites(){if(!this.cache)return[];let e=[],t=([e,t])=>`ns:${e.join(`,`)}|key:${t}`,n=[],r={};for(let e of Object.values(this.tasks))e.cache_key!=null&&!e.writes.length&&(n.push([e.cache_key.ns,e.cache_key.key]),r[t([e.cache_key.ns,e.cache_key.key])]=e);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:n,value:a}of i){let i=r[t(n)];i!=null&&(i.writes.push(...a),e.push({task:i,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:t=[]}=e;if(this.status!==`pending`)throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![uI,dI].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new fC;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks),t=e.flatMap(e=>e.writes);this.updatedChannels=TF(this.checkpoint,this.channels,e,this.checkpointerGetNextVersion,this.triggerToNodes);for(let[e,n]of t){let t=this.channels[e];t!=null&&hN(t)&&eC(n)&&this._deltaChannelsWithOverwrite.add(e)}let n=await KN(GN(fF(this.outputKeys,t,this.channels),`values`));if(this._exitDeltaWrites!==void 0)for(let[e,t,n]of this.checkpointPendingWrites){let r=this.channels[t];r!=null&&hN(r)&&this._exitDeltaWrites.push([this.step,e,t,n])}if(this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),this._emitValuesWithCheckpointMeta(n),bF(this.checkpoint,this.interruptAfter,e))throw this.status=`interrupt_after`,new fC;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[bS]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;this.tasks=OF(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 n=Object.values(this.tasks);if(this.checkpointer&&(this.stream.modes.has(`checkpoints`)||this.stream.modes.has(`debug`))&&this._emit(await KN(GN(VF(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,n,this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),`checkpoints`))),n.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(let[e,t,r]of this.checkpointPendingWrites){if(t===`__error__`||t===`__error_source_node__`||t===`__interrupt__`||t===`__resume__`)continue;let i=n.find(t=>t.id===e);i&&i.writes.push([t,r])}this._resumeErrorHandlersIfApplicable(),n=Object.values(this.tasks);for(let e of n)e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(n.every(e=>e.writes.length>0))return this.tick({inputKeys:t});if(bF(this.checkpoint,this.interruptBefore,n))throw this.status=`interrupt_before`,new fC;if(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`)){let e=await KN(GN(LF(n),`tasks`));this._emit(e)}return!0}async finishAndHandleError(e){this.durability===`exit`&&(!this.isNested||e!==void 0||this.checkpointNamespace.every(e=>!e.includes(`:`)))&&(await this._putExitDeltaWrites(),this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=lF(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(e=>e.writes.length>0)&&(this.updatedChannels=TF(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emitValuesWithCheckpointMeta(qN(GN(fF(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),vC(e)&&!e.interrupts.length&&this._emit([[`updates`,{[FS]:[]}],[`values`,{[FS]:[]}]],this.#e())),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&bF(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=kF([US,e.path??[],t,e.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!r)return;if(this.interruptBefore?.length>0&&bF(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}(this.stream.modes.has(`tasks`)||this.stream.modes.has(`debug`))&&this._emit(qN(GN(LF([r]),`tasks`))),this.debug&&WF(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});let i=await this._matchCachedWrites();for(let{task:e}of i)this._outputWrites(e.id,e.writes,!0);return r}getErrorHandlerNode(e){return this.nodes[e]?.errorHandlerNode}isErrorHandlerNode(e){return this.nodes[e]?.isErrorHandler===!0}scheduleErrorHandler(e,t){let n=this.getErrorHandlerNode(String(e.name));if(!n)return;let r=AF(e,n,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(r!==void 0)return this.tasks[r.id]=r,this._emit(qN(GN(LF([r]),`tasks`))),this.debug&&WF(this.step,[r]),r}_resumeErrorHandlersIfApplicable(){let e=new Map;for(let[t,n]of this.checkpointPendingWrites){if(n!==`__error_source_node__`)continue;let r=this.checkpointPendingWrites.find(([e,n])=>e===t&&n===`__error__`);if(r===void 0)continue;let i=r[2],a=Error(i?.message??String(i));i?.name&&(a.name=i.name),e.set(t,a)}for(let[t,n]of e){let e=this.tasks[t];e!==void 0&&this.getErrorHandlerNode(String(e.name))&&(e.writes.length===0&&e.writes.push([fS,{message:n.message,name:n.name}]),this.scheduleErrorHandler(e,n))}}_suppressInterrupt(e){return vC(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[TS];if(n&&n.nullResume!==void 0&&this.putWrites(GS,[[IS,n.nullResume]]),rC(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(sF)&&(this.config.configurable??={},this.config.configurable[wS]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of uF(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new bC(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===GS).map(e=>e.slice(1));r.length>0&&TF(this.checkpoint,this.channels,[{name:dS,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=rC(this.input),a=i&&r.length>0,o=this.isReplaying&&(this.isNested&&t?.checkpoint_ns!==void 0&&t?.checkpoint_ns!==``&&t?.checkpoint_map!==void 0&&t.checkpoint_ns in t.checkpoint_map||!(i&&this.input.resume!=null||t?.__pregel_resuming===!0||this.resumeAtHead));o&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==IS));let s=this.isResuming;if(s||a){let e={...this.checkpoint.versions_seen[FS]};for(let t in this.channels)Object.prototype.hasOwnProperty.call(this.channels,t)&&this.checkpoint.channel_versions[t]!==void 0&&(e[t]=this.checkpoint.channel_versions[t]);this.checkpoint.versions_seen[FS]=e,o&&this.checkpointMetadata.source!==`update`&&this.checkpointMetadata.source!==`fork`&&(this.checkpointPendingWrites=this.checkpointPendingWrites.filter(e=>e[1]!==FS),await this._putCheckpoint({source:`fork`}));let t=await KN(GN(fF(this.outputKeys,!0,this.channels),`values`));s?this.input=dI:a&&(await this._putCheckpoint({source:`input`}),this.input=uI),this._emitValuesWithCheckpointMeta(t)}else{let t=await KN(dF(e,this.input));if(t.length>0){let e=OF(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=TF(this.checkpoint,this.channels,Object.values(e).concat([{name:dS,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes);let n=t.filter(([e])=>{let t=this.channels[e];return t!=null&&hN(t)});for(let[e,t]of n)eC(t)&&this._deltaChannelsWithOverwrite.add(e);if(n.length>0)if(this._exitDeltaWrites!==void 0)for(let[e,t]of n)this._exitDeltaWrites.push([this.step,GS,e,t]);else this.checkpointer!=null&&this.putWrites(GS,n);await this._putCheckpoint({source:`input`}),this.input=uI}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=uI;else throw new bC(`Received no input writes for ${JSON.stringify(e,null,2)}`)}if(!this.isNested){let e;if(o){let t=this.checkpoint.id;(this.checkpointMetadata.source===`update`||this.checkpointMetadata.source===`fork`)&&this.prevCheckpointConfig&&(t=this.prevCheckpointConfig.configurable?.checkpoint_id??t),e=new lI(t)}this.config=cP(this.config,{[bS]:this.isResuming,[NS]:e})}}#e(){let e=this.checkpointNamespace;if(!(e.length===0||e.length===1&&e[0]===``)||this.config.configurable?.__pregel_stream===void 0)return e;let t=hI(this.config.configurable?.[MS]);return t.length>0?t:e}_emit(e,t=this.checkpointNamespace){for(let[n,r]of e)if(this.stream.modes.has(n)&&this.stream.push([t,n,r]),(n===`checkpoints`||n===`tasks`)&&this.stream.modes.has(`debug`)){let e=n===`checkpoints`?this.step-1:this.step,i=new Date().toISOString(),a=n===`checkpoints`?`checkpoint`:typeof r==`object`&&r&&`result`in r?`task_result`:`task`;this.stream.push([t,`debug`,{step:e,type:a,timestamp:i,payload:r}])}}_currentCheckpointMeta(){if(!this.checkpointMetadata||!this.checkpoint?.id)return;let e=this.prevCheckpointConfig?.configurable?.checkpoint_id;return{checkpoint:{id:this.checkpoint.id,...e?{parent_id:e}:{},step:this.checkpointMetadata.step,source:this.checkpointMetadata.source}}}_emitValuesWithCheckpointMeta(e){let t=this._currentCheckpointMeta();for(let[n,r]of e)n===`values`&&t?.checkpoint!=null&&!this.stream.modes.has(`checkpoints`)&&this.stream.push([this.checkpointNamespace,`checkpoints`,t.checkpoint]),this.stream.modes.has(n)&&this.stream.push([this.checkpointNamespace,n,r])}_putCheckpoint(e){let t=this.checkpointMetadata===e,n=this.checkpointer!=null&&(this.durability!==`exit`||t),r=e=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=cP(this.checkpointConfig,{[kS]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=oP(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:rN(e),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}},i;if(t)i={...this.checkpointMetadata.counters_since_delta_snapshot??{}};else{let t=this.checkpointMetadata.counters_since_delta_snapshot??{};i={};let n=this.updatedChannels??new Set;for(let e in this.channels){if(!Object.prototype.hasOwnProperty.call(this.channels,e)||!hN(this.channels[e]))continue;let[r,a]=t[e]??[0,0];i[e]=[n.has(e)?r+1:r,a+1]}this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}}let a=n?SN(this.channels,i):new Set;if(n)for(let e of this._deltaChannelsWithOverwrite)a.add(e);this.checkpoint=CN(this.checkpoint,n?this.channels:void 0,this.step,{id:t?this.checkpoint.id:void 0,channelsToSnapshot:a,updatedChannels:this.updatedChannels,getNextVersion:n?e=>this.checkpointerGetNextVersion(e):void 0});for(let e of a)i[e]=[0,0],this._deltaChannelsWithOverwrite.delete(e);let o={};for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let[t,n]=i[e];(t!==0||n!==0)&&(o[e]=[t,n])}Object.keys(o).length>0?this.checkpointMetadata.counters_since_delta_snapshot=o:delete this.checkpointMetadata.counters_since_delta_snapshot,n&&r(this.checkpoint),t||(this.step+=1)}async _putExitDeltaWrites(){if(this._exitDeltaWrites===void 0||this._exitDeltaWrites.length===0||this.checkpointer==null||this._initialCheckpointConfig===void 0)return;let e=this.checkpointMetadata.counters_since_delta_snapshot??{},t=SN(this.channels,e);for(let e of this._deltaChannelsWithOverwrite)t.add(e);let n=this._exitDeltaWrites.filter(([,,e])=>!t.has(e));if(n.length===0)return;let r;if(this._hasPersistedParent)r=this._initialCheckpointConfig;else{let e=nN();e.id=this.checkpointIdSaved??e.id,e.ts=new Date().toISOString();let t=cP(this._initialCheckpointConfig,{[OS]:void 0});r=cP(this._initialCheckpointConfig,{[OS]:e.id}),this._trackCheckpointerPromise(this.checkpointer.put(t,e,{source:`loop`,step:-2,parents:{}},{})),this.checkpointConfig=r}let i=cP(r,{[kS]:this.config.configurable?.checkpoint_ns??``,[OS]:r.configurable?.[OS]}),a=new Map,o=[];for(let[e,t,r,i]of n){let n=`${e}\u0000${t}`,s=a.get(n);s===void 0&&(s=[],a.set(n,s),o.push({key:n,step:e,tid:t})),s.push([r,i])}for(let{key:e,step:t,tid:n}of o){let r=xN(t,n);this._trackCheckpointerPromise(this.checkpointer.putWrites(i,a.get(e),r))}}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let e=cP(this.checkpointConfig,{[kS]:this.config.configurable?.checkpoint_ns??``,[OS]:this.checkpoint.id}),t={};for(let[e,n,r]of this.checkpointPendingWrites)t[e]??=[],t[e].push([n,r]);for(let[n,r]of Object.entries(t))this._trackCheckpointerPromise(this.checkpointer.putWrites(e,r,n))}_matchWrites(e){for(let[t,n,r]of this.checkpointPendingWrites){if(n===`__error__`||n===`__interrupt__`||n===`__resume__`)continue;let i=Object.values(e).find(e=>e.id===t);i&&i.writes.push([n,r])}for(let t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}};function vI(e){return _t(e?.message)}function yI(e,t,n){if(!e)return;let r=e.langgraph_checkpoint_ns,i=e.checkpoint_ns,a=r??i;if(a)return[a.split(`|`),{tags:t,name:n,...e}]}var bI=class extends zr{name=`StreamMessagesHandler`;streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;n!=null&&(wt(t)?i??=`run-${n}-tool-${t.tool_call_id}`:((i==null||i===`run-${n}`)&&(i=this.stableMessageIdMap[n]??i??`run-${n}`),this.stableMessageIdMap[n]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],`messages`,[t,e[1]]])}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=yI(o,a,s))}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(vI(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new nn({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];_t(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=yI(a,i,s),typeof t==`object`)){for(let e of Object.values(t))if((_t(e)||vt(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(_t(t)||vt(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(_t(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)_t(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(_t(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)_t(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}};function xI(e){if(`response_metadata`in e&&typeof e.response_metadata==`object`&&e.response_metadata!=null)return e.response_metadata}function SI(e){if(`usage_metadata`in e&&typeof e.usage_metadata==`object`&&e.usage_metadata!=null)return e.usage_metadata}function CI(e){switch(e.type){case`text`:return{type:`text`,text:``};case`reasoning`:return{type:`reasoning`,reasoning:``};case`tool_call`:case`tool_call_chunk`:return{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:``};default:return e}}function wI(e){switch(e.type){case`text`:{let t=typeof e.text==`string`?e.text:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`text-delta`,text:t}}:void 0}case`reasoning`:{let t=typeof e.reasoning==`string`?e.reasoning:``;return t.length>0?{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`reasoning-delta`,reasoning:t}}:void 0}case`tool_call_chunk`:return{event:`content-block-delta`,index:typeof e.index==`number`?e.index:0,delta:{type:`block-delta`,fields:{...e,type:`tool_call_chunk`}}};default:return}}var TI=class extends zr{name=`StreamProtocolMessagesHandler`;streamFn;metadatas={};seen={};streamedRunIds=new Set;stableMessageIdMap={};lc_prefer_chat_model_stream_events=!0;awaitHandlers=!0;constructor(e){super(),this.streamFn=e}normalizeMessageId(e,t){let n=e.id;return t!=null&&(xt.isInstance(e)?n??=`run-${t}-tool-${e.tool_call_id}`:((n==null||n===`run-${t}`)&&(n=this.stableMessageIdMap[t]??n??`run-${t}`),this.stableMessageIdMap[t]??=n)),n!==e.id&&(e.id=n,e.lc_kwargs.id=n),e.id!=null&&(this.seen[e.id]=e),e.id}emit(e,t,n){let r=n==null?e[1]:{...e[1],run_id:n};this.streamFn([e[0],`messages`,[t,r]])}emitFinalMessage(e,t,n,r=!1){let i=t.id??(n==null?void 0:this.stableMessageIdMap[n]);if(r&&i!=null&&this.seen[i]!==void 0)return;let a=this.normalizeMessageId(t,n),o=t.type===`human`?`human`:t.type===`system`?`system`:t.type===`tool`?`tool`:`ai`,s=o===`tool`&&xt.isInstance(t)?t.tool_call_id:void 0;this.emit(e,{event:`message-start`,...a==null?{}:{id:a},...o===`ai`?{}:{role:o},...typeof s==`string`?{tool_call_id:s}:{}},n),(Array.isArray(t.content)?t.content:typeof t.content==`string`&&t.content.length>0?[{type:`text`,text:t.content}]:[]).forEach((t,r)=>{let i=typeof t.index==`number`?t.index:r;this.emit(e,{event:`content-block-start`,index:i,content:CI(t)},n);let a=wI({...t,index:i});a!=null&&this.emit(e,a,n),this.emit(e,{event:`content-block-finish`,index:i,content:t},n)}),this.emit(e,{event:`message-finish`,...SI(t)==null?{}:{usage:SI(t)},...xI(t)==null?{}:{responseMetadata:xI(t)}},n)}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split(`|`),{tags:a,name:s,...o}])}handleLLMNewToken(){}handleChatModelStreamEvent(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e;if(e.event===`message-start`){this.streamedRunIds.add(t);let n=e.id??`run-${t}`;this.seen[n]=!0,this.stableMessageIdMap[t]??=n,e.id??(r={...e,id:n})}this.emit(n,r,t)}handleLLMEnd(e,t){let n=this.metadatas[t];if(n===void 0)return;let r=e.generations?.[0]?.[0],i=rt.isInstance(r?.message)?r.message:void 0;if(i!=null)if(this.streamedRunIds.has(t)){let e=this.normalizeMessageId(i,t);e!=null&&(this.seen[e]=i)}else this.emitFinalMessage(n,i,t,!0);this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleLLMError(e,t){this.streamedRunIds.delete(t),delete this.metadatas[t],delete this.stableMessageIdMap[t]}handleChainStart(e,t,n,r,i,a,o,s){if(a!==void 0&&s===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split(`|`),{tags:i,name:s,...a}],typeof t==`object`)){for(let e of Object.values(t))if((rt.isInstance(e)||ht.isInstance(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(rt.isInstance(t)||ht.isInstance(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n===void 0)return;let r=e=>{rt.isInstance(e)&&!xt.isInstance(e)&&this.emitFinalMessage(n,e,t,!0)};if(rt.isInstance(e))r(e);else if(Array.isArray(e))for(let t of e)r(t);else if(typeof e==`object`&&e)for(let t of Object.values(e))if(Array.isArray(t))for(let e of t)r(e);else r(t);delete this.stableMessageIdMap[t]}handleChainError(e,t){delete this.metadatas[t],delete this.stableMessageIdMap[t]}},EI=class{active=!0;lastProgress=Date.now();refreshOn;constructor(e){this.refreshOn=e}touch(){this.lastProgress=Date.now()}autoTouch(){this.refreshOn===`auto`&&(this.lastProgress=Date.now())}close(){this.active=!1}},DI=class extends zr{name=`IdleProgressCallbackHandler`;awaitHandlers=!1;#e;constructor(e){super(),this.#e=e}#t=()=>{this.#e.autoTouch()};handleLLMStart=this.#t;handleChatModelStart=this.#t;handleLLMNewToken=this.#t;handleLLMEnd=this.#t;handleLLMError=this.#t;handleChainStart=this.#t;handleChainEnd=this.#t;handleChainError=this.#t;handleToolStart=this.#t;handleToolEnd=this.#t;handleToolError=this.#t;handleText=this.#t;handleRetrieverStart=this.#t;handleRetrieverEnd=this.#t;handleRetrieverError=this.#t;handleCustomEvent=this.#t};function OI(e,t,n,r){let i=e.configurable??{},a={},o=i[gS];typeof o==`function`&&(a[gS]=e=>{if(t.active)return e&&e.length&&t.autoTouch(),o(e)});let s=i[_S];typeof s==`function`&&(a[_S]=(...e)=>{if(!t.active)throw Error(`Node "${r}" attempt was cancelled after its timeout fired`);return t.autoTouch(),s(...e)});let c={...Object.keys(a).length>0?cP(e,a):e};if(c.heartbeat=()=>{n.idleTimeout!==void 0&&t.touch()},typeof c.writer==`function`){let e=c.writer;c.writer=(n=>{if(t.active)return t.autoTouch(),e(n)})}if((n.refreshOn??`auto`)===`auto`&&n.idleTimeout!==void 0){let e=new DI(t),n=c.callbacks;if(n===void 0)c.callbacks=[e];else if(Array.isArray(n))c.callbacks=[...n,e];else{let t=n.copy();t.addHandler(e,!0),c.callbacks=t}}return c}async function kI(e,t,n,r){let i=new EI(n.refreshOn??`auto`),a=new AbortController,{signal:o,dispose:s}=uP(t.signal,a.signal),c=OI({...t,signal:o},i,n,String(e.name)),l=Date.now(),u=r(c).then(e=>({type:`ok`,value:e}),e=>({type:`err`,error:e})),d,f,p=()=>{d!==void 0&&clearTimeout(d),f!==void 0&&clearTimeout(f)},m=new Promise(e=>{if(n.runTimeout!==void 0&&(d=setTimeout(()=>e({type:`timeout`,kind:`run`}),n.runTimeout)),n.idleTimeout!==void 0){let t=n.idleTimeout,r=()=>{let n=i.lastProgress+t-Date.now();n<=0?e({type:`timeout`,kind:`idle`}):f=setTimeout(r,n)};f=setTimeout(r,t)}}),h;try{h=await Promise.race([u,m])}finally{p()}if(h.type!==`timeout`){let e=Date.now();n.runTimeout!==void 0&&e-l>=n.runTimeout?h={type:`timeout`,kind:`run`}:n.idleTimeout!==void 0&&e-i.lastProgress>=n.idleTimeout&&(h={type:`timeout`,kind:`idle`})}if(h.type===`ok`)return s?.(),h.value;if(h.type===`err`)throw s?.(),h.error;let g=Date.now()-l;throw i.close(),e.writes.splice(0,e.writes.length),a.abort(),s?.(),new yC({node:String(e.name),elapsed:g,kind:h.kind,runTimeout:n.runTimeout,idleTimeout:n.idleTimeout})}var AI=[400,401,402,403,404,405,406,407,409],jI=e=>{if(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`)||e.name===`AbortError`||e.name===`GraphValueError`||e?.code===`ECONNABORTED`)return!1;let t=e?.response?.status??e?.status;return!(t&&AI.includes(+t)||e?.error?.code===`insufficient_quota`)};async function MI(e,t,n,r){let i=e.retry_policy??t,a=0,o,s,c=e.config??{};n&&(c=cP(c,n)),c={...c,signal:r};let l=Date.now();for(c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeFirstAttemptTime:l});!r?.aborted;){e.writes.splice(0,e.writes.length),o=void 0;try{s=e.timeout===void 0?await e.proc.invoke(e.input,c):await kI(e,c,e.timeout,t=>e.proc.invoke(e.input,t));break}catch(t){if(o=t,o.pregelTaskId=e.id,gC(o)){let t=c?.configurable?.checkpoint_ns,n=o.command;if(n.graph===t){for(let t of e.writers)await t.invoke(n,c);o=void 0;break}else if(n.graph===nC.PARENT){let e=UN(t);o.command=new nC({...o.command,graph:e})}}if(_C(o)||i===void 0||(a+=1,a>=(i.maxAttempts??3))||!(i.retryOn??jI)(o))break;let n=i.initialInterval??500,r=Math.min(i.maxInterval??128e3,n*(i.backoffFactor??2)**(a-1)),s=i.jitter??!0?r+Math.random()*1e3:r;await new Promise(e=>setTimeout(e,s));let u=o.name??o.constructor.unminifiable_name??o.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${s.toFixed(2)}ms (attempt ${a}) after ${u}: ${o}`),c=cP(c,{[bS]:!0}),c.executionInfo!=null&&(c.executionInfo={...c.executionInfo,nodeAttempt:a+1,nodeFirstAttemptTime:l})}}return{task:e,result:s,error:o,signalAborted:r?.aborted}}var NI=Symbol.for(`promiseAdded`);function PI(){let e={next:()=>void 0,wait:Promise.resolve(NI)};function t(n){e.next=()=>{e.wait=new Promise(t),n(NI)}}return e.wait=new Promise(t),e}var FI=class{nodeFinished;loop;handledExceptions=new WeakSet;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks),d=u.filter(e=>e.writes.length===0),{signals:f,disposeCombinedSignal:p}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),m=this._executeTasksWithRetry(d,{signals:f,retryPolicy:n,maxConcurrency:i});for await(let{task:e,error:t,signalAborted:n}of m)this._commit(e,t),!(t!==void 0&&this.handledExceptions.has(t))&&(vC(t)||_C(t)&&!vC(o)?o=t:t&&(a.size===0||!n)&&(s.abort(),a.add(t)));if(p?.(),r?.(this.loop.step,u.map(e=>e.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(vC(o)||dC(o)||_C(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},i=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:o,dispose:s}=uP(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=cP(this.loop.config,{[PS]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=PI(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:n,scheduleTask:async(e,t,n)=>this.loop.acceptPush(e,t,n)};if(i?.composedAbortSignal?.aborted)throw Error(`Abort`);let c=0,l,u=uP(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((e,t)=>{l=()=>t(Error(`Abort`)),u.signal?.addEventListener(`abort`,l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(r??e.length)&&c<e.length;c+=1){let t=e[c];o[t.id]=MI(t,n,{[_S]:II?.bind(s,this,t)},i?.composedAbortSignal).catch(e=>({task:t,error:e,signalAborted:i?.composedAbortSignal?.aborted}))}let t=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);if(t===NI)continue;let f=t,{task:p,error:m}=f;if(m!==void 0&&!_C(m)&&!this.loop.isErrorHandlerNode(String(p.name))&&this.loop.getErrorHandlerNode(String(p.name))!==void 0){let e=this.loop.scheduleErrorHandler(p,m);e!==void 0&&(o[e.id]=MI(e,n,{[_S]:II?.bind(s,this,e)},i?.composedAbortSignal).catch(t=>({task:e,error:t,signalAborted:i?.composedAbortSignal?.aborted})),a.next())}yield f,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id]}}_shouldRouteToErrorHandler(e){let t=String(e.name);return!this.loop.isErrorHandlerNode(t)&&this.loop.getErrorHandlerNode(t)!==void 0}_commit(e,t){if(t!==void 0)if(vC(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[FS,e]),r=e.writes.filter(e=>e[0]===IS);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else dC(t)?e.writes.length&&this.loop.putWrites(e.id,e.writes):_C(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):(e.writes.push([fS,{message:t.message,name:t.name}]),this._shouldRouteToErrorHandler(e)&&(e.writes.push([pS,String(e.name)]),this.handledExceptions.add(t)),this.loop.putWrites(e.id,e.writes));else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(`langsmith:hidden`))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([LS,null]),this.loop.putWrites(e.id,e.writes)}};async function II(e,t,n,r,i,a={}){let o=t.config?.configurable?.[TS];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new mF({func:n,name:r,input:i,cache:a.cache,retry:a.retry,timeout:a.timeout,callbacks:a.callbacks}),l=await this.scheduleTask(t,s,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let e=l.writes.filter(([e])=>e===RS),t=l.writes.filter(([e])=>e===fS);if(e.length>0){if(e.length===1)return Promise.resolve(e[0][1]);throw Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(t.length>0){if(t.length===1){let e=t[0][1],n=e instanceof Error?e:Error(String(e));return Promise.reject(n)}throw Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let t=MI(l,a.retry,{[_S]:II.bind(this,e,l)});return this.executingTasksMap[l.id]=t,this.barrier.next(),t.then(({result:e,error:t})=>t?Promise.reject(t):e)}}var LI=Symbol.for(`langgraph.stream_channel`),RI=class e{[LI]=!0;channelName;#e=[];#t=[];#n=!1;#r;#i;constructor(e){this.channelName=e}static local(){return new e}static remote(t){return new e(t)}static isInstance(e){return typeof e==`object`&&!!e&&LI in e&&e[LI]===!0}push(e){this.#e.push(e),this.#a(),this.#i?.(e)}iterate(e=0){let t=e;return{next:async()=>{for(;;){if(t<this.#e.length)return{value:this.#e[t++],done:!1};if(this.#n){if(this.#r)throw this.#r;return{value:void 0,done:!0}}await new Promise(e=>this.#t.push(e))}}}}toAsyncIterable(e=0){return{[Symbol.asyncIterator]:()=>this.iterate(e)}}toEventStream(e={}){let t=new TextEncoder,n=this.iterate(e.startAt),r=e.event??this.channelName,i=e.serialize??(e=>JSON.stringify(e)??`null`);return new ReadableStream({async pull(e){try{let a=await n.next();if(a.done){e.close();return}let o=[];r!=null&&o.push(`event: ${r}`);for(let e of i(a.value).split(/\r\n|\r|\n/))o.push(`data: ${e}`);e.enqueue(t.encode(`${o.join(`
|
|
187
187
|
`)}\n\n`))}catch(t){e.error(t)}},async cancel(){await n.return?.()}})}get(e){if(e<0||e>=this.#e.length)throw RangeError(`StreamChannel index ${e} out of bounds (size=${this.#e.length})`);return this.#e[e]}get size(){return this.#e.length}get done(){return this.#n}close(){this.#n=!0,this.#a()}fail(e){this.#r=e,this.#n=!0,this.#a()}_wire(e){this.#i=e}_close(){this.close()}_fail(e){this.fail(e)}[Symbol.asyncIterator](){return this.iterate()}#a(){let e=this.#t.splice(0);for(let t of e)t()}};function zI(e){return RI.isInstance(e)}var BI=`custom:`;function VI(e){return`${BI}${e}`}function HI(e){return e!=null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var UI=Symbol(`resolveValues`),WI=Symbol(`rejectValues`),GI=class{_events=RI.local();_discoveries=RI.local();#e=0;#t=!1;#n;#r=!1;#i=[];#a=[];#o=[];#s=new Map;#c=new Map;#l=[];#u=[];register(e,t){this.#s.set(qI(e),t)}addTransformer(e){let t=this._events.size;this.#a.push(e),e.onRegister&&e.onRegister({push:(e,t)=>this.push(e,t)});for(let n=0;n<t;n+=1)e.process(this._events.get(n));this.#t&&(this.#n===void 0?e.finalize?.():e.fail?.(this.#n))}wireChannels(e){for(let[t,n]of Object.entries(e)){if(zI(n)){if(this.#o.push(n),typeof n.channelName!=`string`)continue;let e=VI(n.channelName);n._wire(t=>{this._events.push({type:`event`,seq:this.#e++,method:e,params:{namespace:this.#i,timestamp:Date.now(),data:t}})});continue}HI(n)&&this.#u.push({name:t,promise:Promise.resolve(n)})}}push(e,t){t.method===`values`&&this.#c.set(qI(e),t.params.data);let n=this.#i;this.#i=e;let r=!0;for(let e of this.#a)e.process(t)||(r=!1);this.#i=n,r&&this._events.push({...t,seq:this.#e++})}close(){this.#t=!0;for(let[e,t]of this.#c.entries()){let n=e?e.split(`\0`):[];this.#s.get(qI(n))?.[UI](t)}let e=[];for(let t of this.#a){let n=t.finalize?.();n!=null&&typeof n.then==`function`&&e.push(n)}for(let e of this.#o)e._close();let t=this.#u;t.length===0&&e.length===0?(this._events.close(),this._discoveries.close()):Promise.allSettled([...e,...t.map(async({name:e,promise:t})=>{try{let n=await t;this._events.done||this._events.push({type:`event`,seq:this.#e++,method:`custom`,params:{namespace:[],timestamp:Date.now(),data:{name:e,payload:n}}})}catch{}})]).then(()=>{this._events.close(),this._discoveries.close()});for(let e of this.#s.values())e[UI](void 0)}fail(e){this.#t=!0,this.#n=e;for(let t of this.#a)t.fail?.(e);for(let t of this.#o)t._fail(e);this._events.fail(e),this._discoveries.fail(e);for(let t of this.#s.values())t[WI](e)}markInterrupted(e){this.#r=!0,this.#l.push(...e)}get interrupted(){return this.#r}get interrupts(){return this.#l}subscribeEvents(e,t=0){let n=this._events.iterate(t);return{async next(){for(;;){let t=await n.next();if(t.done||JI(t.value.params.namespace,e))return t}}}}};async function KI(e,t){let n=0;try{for await(let r of e){let[e,i,a]=r;if(i===`values`&&tC(a)){let e=a[FS];t.markInterrupted(e.map(e=>({interruptId:e.id??``,payload:e.value})))}let o=YF({namespace:e,mode:i,payload:a,seq:n});n+=o.length;for(let n of o)t.push(e,n)}}catch(e){t.fail(e);return}t.close()}function qI(e){return e.join(`\0`)}function JI(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(e[n]!==t[n])return!1;return!0}function YI(e,t,n=0){return{[Symbol.asyncIterator](){let r=e.iterate(n);return{async next(){for(;;){let e=await r.next();if(e.done)return{value:void 0,done:!0};if(JI(e.value.namespace,t))return{value:e.value,done:!1}}}}}}}var XI=`root`;function ZI(e){if(e.length===0)return XI;let t=e[e.length-1],n=t.indexOf(`:`);return n===-1?t:t.slice(0,n)}function QI(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}function $I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eL(e){if(!$I(e)||e.event!==`started`)return;let t=e.cause;if($I(t)&&typeof t.type==`string`)return t}function tL(e){if($I(e)&&`result`in e&&typeof e.name==`string`&&typeof e.id==`string`&&!e.name.startsWith(`__`))return{name:e.name,id:e.id}}function nL(e={}){let t=e.rootGraphName??XI,n=e.initialStatus??`running`,r=e.emitRootOnRegister??!0,i=e.getGraphName??ZI,a=e.serializeError??QI,o=e.getTerminalStatusOverride,s=RI.local(),c=new Map,l=new Map,u=new Map,d=new Map,f=new Set,p=[],m,h=0,g=!1,_=e=>{if(e.length===0)return t;let n=u.get(qI(e));return typeof n==`string`&&n.length>0?n:i(e)},v=(e,t)=>{let n=qI(e);if(u.has(n))return;let r=($I(t)&&$I(t.metadata)?t.metadata:void 0)?.lc_agent_name;u.set(n,typeof r==`string`?r:void 0)},y=e=>{if(!$I(e))return;let t=e.id;if(typeof t!=`string`)return;let n=e.input,r;if($I(n)&&$I(n.tool_call)){let e=n.tool_call.id;typeof e==`string`&&(r=e)}else if(Array.isArray(n)){for(let e of n)if($I(e)&&typeof e.id==`string`){r=e.id;break}}r!=null&&d.set(t,r)},b=e=>{if(e.length===0)return;let t=u.get(qI(e));if(typeof t!=`string`||t.length===0)return;let n=e[e.length-1],r=n.indexOf(`:`);if(r===-1)return;let i=n.slice(r+1);if(i.length===0)return;let a=d.get(i);if(!(typeof a!=`string`||a.length===0))return{type:`toolCall`,tool_call_id:a}},x=e=>l.get(qI(e))??b(e),ee=(e,t,n)=>{let i=qI(e),a=c.get(i),o=a?.graphName??_(e);if(a!=null&&a.status===t&&a.graphName===o&&n?.error==null)return;a==null?(a={namespace:e,graphName:o,status:t},c.set(i,a)):a.status=t;let l={event:t,graph_name:o,...n?.cause==null?{}:{cause:n.cause},...n?.error==null?{}:{error:n.error}},u=Date.now();if(s.push({namespace:e,timestamp:u,...l}),!(e.length===0&&!r)&&m!=null){h+=1;try{m.push(e,{type:`event`,seq:0,method:`lifecycle`,params:{namespace:e,timestamp:u,data:l}})}finally{--h}}},te=e=>{let t=qI(e),n=c.get(t);return n??(n={namespace:e,graphName:_(e),status:void 0},c.set(t,n)),n},S=()=>{if(p.length===0)return;let e=p.splice(0,p.length);for(let t of e){let e=qI(t.namespace),n=c.get(e);n==null||n.status!==`started`||ee(t.namespace,`completed`)}},ne=e=>{let t=qI(e.namespace),n=c.get(t);n==null||n.status!==`started`||p.some(e=>qI(e.namespace)===t)||p.push(e)},re=(e,t)=>{for(let n=p.length-1;n>=0;--n){let r=p[n];r.source.type===`node`&&r.source.node===t&&qI(r.source.parent)===qI(e)&&p.splice(n,1)}},ie=e=>{for(let t=1;t<=e.length;t+=1){let n=e.slice(0,t),r=qI(n);if(c.has(r))continue;te(n);let i=x(n);ee(n,`started`,i==null?void 0:{cause:i})}},ae=()=>f.size>0?`interrupted`:`completed`,oe=e=>{for(let t of c.values())t.namespace.length!==0&&t.status===`started`&&ee(t.namespace,e);ee([],e),s.close()},se=async()=>{if(o==null)return ae();try{return await o()??ae()}catch{return ae()}},ce=(e,t)=>{let n=`${t}:`;for(let r of c.values()){if(r.namespace.length!==e.length+1||r.status!==`started`||!JI(r.namespace,e))continue;let i=r.namespace[r.namespace.length-1];if(i===t||i.startsWith(n))return r.namespace}},C=(e,t)=>{let n=[...e,`${t.name}:${t.id}`];return c.get(qI(n))?.status===`started`?n:void 0};return{__native:!0,init(){return{_lifecycleLog:s,lifecycle:YI(s,[],0)}},onRegister(e){m=e,te([]),r&&ee([],n)},process(e){let t=e.params.namespace;if(h>0)return!0;let n=e.method===`tasks`?tL(e.params.data):void 0;if(n==null?e.method===`tasks`&&(v(t,e.params.data),y(e.params.data)):re(t,n.name),S(),e.method===`lifecycle`){let n=eL(e.params.data);return n!=null&&l.set(qI(t),n),ie(t),!1}if(ie(t),e.method===`input`&&$I(e.params.data)&&e.params.data.event===`requested`){let t=e.params.data.id;typeof t==`string`&&f.add(t)}if(n!=null){let e=C(t,n);e!=null&&ne({namespace:e,source:{type:`task`}})}if(e.method===`updates`){let n=e.params.node;if(typeof n==`string`&&!n.startsWith(`__`)){let e=ce(t,n);e!=null&&ne({namespace:e,source:{type:`node`,parent:t,node:n}})}}return!0},finalize(){if(!g){if(g=!0,S(),o==null){oe(ae());return}return se().then(oe).catch(e=>{s.fail(e)})}},fail(e){if(g)return;g=!0;let t=a(e);for(let e of c.values())e.namespace.length!==0&&e.status===`started`&&ee(e.namespace,`failed`);ee([],`failed`,{error:t}),s.fail(e)}}}function rL(e){let t=e;return typeof t.run_id==`string`?`run:${t.run_id}`:e.event===`message-start`&&typeof t.id==`string`?`message:${t.id}`:`__default__`}function iL(e,t){let n=RI.local(),r=new Map,i=new Set;return{init:()=>({messages:n.toAsyncIterable()}),process(a){if(a.method!==`messages`||!JI(a.params.namespace,e)||a.params.namespace.length!==e.length+1||t!==void 0&&a.params.node!==t)return!0;let o=a.params.data;switch(o.event){case`message-start`:{let e=rL(o);if(o.role===`tool`){i.add(e);break}let t=RI.local(),s=Object.assign(new uE(t.toAsyncIterable()),{namespace:a.params.namespace,node:a.params.node});r.set(e,{source:t,stream:s}),t.push(o),n.push(s);break}case`content-block-start`:case`content-block-delta`:case`content-block-finish`:if(i.has(rL(o)))break;r.get(rL(o))?.source.push(o);break;case`message-finish`:{let e=rL(o);if(i.delete(e))break;let t=r.get(e);t&&(t.source.push(o),t.source.close(),r.delete(e));break}case`error`:if(i.has(rL(o)))break;r.get(rL(o))?.source.push(o);break}return!0},finalize(){for(let[e,t]of r)t.source.push({event:`message-finish`}),t.source.close(),r.delete(e);i.clear(),n.close()},fail(e){for(let[t,n]of r)n.source.fail(e),r.delete(t);i.clear(),n.fail(e)}}}function aL(e,t,n=0){let r=t.length+1;return{[Symbol.asyncIterator](){let i=e.iterate(n);return{async next(){for(;;){let e=await i.next();if(e.done)return{value:void 0,done:!0};let{ns:n,stream:a}=e.value;if(n.length===r&&JI(n,t))return{value:a,done:!1}}}}}}}function oL(e,t){let{createStream:n}=t,r=new Set;return{__native:!0,init(){return{_discoveries:e._discoveries,subgraphs:aL(e._discoveries,[],0)}},process(t){let i=t.params.namespace;if(i.length===0)return!0;let a=i.slice(0,1),o=qI(a);if(r.has(o))return!0;r.add(o);let s=n(a,e._discoveries.size,e._events.size);return e.register(a,s),e._discoveries.push({ns:a,stream:s}),!0}}}function sL(e){let t=RI.local();return{init:()=>({_valuesLog:t}),process(n){return n.method!==`values`||n.params.namespace.length!==e.length||!JI(n.params.namespace,e)||t.push(n.params.data),!0},finalize(){t.close()},fail(e){t.fail(e)}}}function cL(e){return`__native`in e&&e.__native===!0}var lL=Symbol(`setValuesLog`),uL=Symbol(`setMessagesIterable`),dL=Symbol(`setLifecycleIterable`),fL=Symbol(`setSubgraphsIterable`),pL={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},mL=class{path;extensions;_mux;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t,n=0,r=0,i,a){this.path=e,this._mux=t,this.#t=n,this.#e=r,this.extensions=i??{},this.#n=a??new AbortController,this.#a=new Promise((e,t)=>{this.#r=e,this.#i=t}),this.#a.catch(()=>{})}[Symbol.asyncIterator](){return this._mux.subscribeEvents(this.path,this.#e)}get subgraphs(){return this.#l?this.#l:aL(this._mux._discoveries,this.path,this.#t)}get values(){let e=this.#o,t=this.#a,n=this._mux,r=this.#e,i=this.path,a=e?e.toAsyncIterable():{[Symbol.asyncIterator]:()=>{let e=n.subscribeEvents(i,r);return{async next(){for(;;){let t=await e.next();if(t.done)return{value:void 0,done:!0};if(t.value.method===`values`&&t.value.params.namespace.length===i.length)return{value:t.value.params.data,done:!1}}}}}};return{[Symbol.asyncIterator]:()=>a[Symbol.asyncIterator](),then:t.then.bind(t)}}get messages(){if(this.#s)return this.#s;let e=iL(this.path),t=e.init();return this._mux.addTransformer(e),this.#s=t.messages,this.#s}get lifecycle(){return this.#c??pL}messagesFrom(e){let t=iL(this.path,e),n=t.init();return this._mux.addTransformer(t),n.messages}get output(){return this.#a}get interrupted(){return this._mux.interrupted}get interrupts(){return this._mux.interrupts}abort(e){this.#n.abort(e)}get signal(){return this.#n.signal}[UI](e){this.#r?.(e),this.#r=void 0}[WI](e){this.#i?.(e),this.#i=void 0}[lL](e){this.#o=e}[uL](e){this.#s=e}[dL](e){this.#c=e}[fL](e){this.#l=e}},hL=class extends mL{name;index;constructor(e,t,n=0,r=0,i,a){super(e,t,n,r,i,a);let o=e[e.length-1]??``,s=o.lastIndexOf(`:`);if(s>=0){this.name=o.slice(0,s);let e=o.slice(s+1);this.index=/^\d+$/.test(e)?Number(e):0}else this.name=o,this.index=0}};function gL(e,t=[],n){let{abortController:r}=n instanceof AbortController?{abortController:n}:n??{},i=new GI,a=nL(),o=a.init(),s=o._lifecycleLog,c=oL(i,{createStream:(e,t,n)=>{let r=new hL(e,i,t,n);return r[fL](aL(i._discoveries,e,t)),r[dL](YI(s,e,s.size)),r}}),l=c.init();i.addTransformer(c),i.addTransformer(a);let u=sL([]),d=iL([]);i.addTransformer(u),i.addTransformer(d);let f={},p=[];for(let e of t){let t=e();i.addTransformer(t);let n=t.init();cL(t)?p.push(n):Object.assign(f,n),typeof n==`object`&&n&&!cL(t)&&i.wireChannels(n)}let m=new mL([],i,0,0,f,r);for(let e of p)Object.assign(m,e);let h=u.init();m[lL](h._valuesLog);let g=d.init();return m[uL](g.messages),m[dL](o.lifecycle),m[fL](l.subgraphs),i.register([],m),KI(e,i).catch(e=>{}),m}var _L=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function vL({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new _L(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new _L(`"Node name ${FS} is reserved"`);if(n.constructor===iP)n.triggers.forEach(e=>s.add(e));else throw new _L(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new _L(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new _L(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new _L(`None of the input channels ${n} are subscribed to by any node`);Array.isArray(r)?r.forEach(e=>c.add(e)):c.add(r),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(e=>c.add(e));for(let e of c)if(!(e in t))throw new _L(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new _L(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new _L(`Node ${String(t)} not in nodes`)}}function yL(e,t){if(Array.isArray(e)){for(let n of e)if(!(n in t))throw Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw Error(`Key ${String(e)} not found in channels`)}var bL=class e extends _N{lc_graph_name=`Topic`;unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let n=new e({unique:this.unique,accumulate:this.accumulate});return t!==void 0&&(n.seen=new Set(t[0]),n.values=t[1]),n}update(e){let t=!1;this.accumulate||(t=this.values.length>0,this.values=[]);let n=e.flat();if(n.length>0)if(this.unique)for(let e of n)this.seen.has(e)||(t=!0,this.seen.add(e),this.values.push(e));else t=!0,this.values.push(...n);return t}get(){if(this.values.length===0)throw new xC;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}};function xL(e){let t=Wl.getRunnableConfig();if(!t)throw Error(`Called interrupt() outside the context of a graph.`);let n=t.configurable;if(!n)throw Error(`No configurable found in config`);if(!n.__pregel_checkpointer)throw new lC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[TS];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[gS]?.([[IS,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);let e=r.consumeNullResume();return r.resume.push(e),n[gS]?.([[IS,r.resume]]),e}let a=n[kS]?.split(`|`);throw new fC([{id:a?oF(a.join(`|`)):void 0,value:e}])}function SL(e){let t=new TextEncoder;return new ReadableStream({async start(n){try{for await(let r of e){let e=r.params.namespace,i=e.length?`${r.method}|${e.join(`|`)}`:r.method;n.enqueue(t.encode(`event: ${i}\ndata: ${JSON.stringify(r.params.data??{})}\n\n`))}}catch(e){n.enqueue(t.encode(`event: error\ndata: ${JSON.stringify({message:String(e)})}\n\n`))}finally{n.close()}}})}var CL=class{static subscribeTo(e,t){let{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw Error(`Can't specify a key when subscribing to multiple channels`);let i;return i=typeof e==`string`?n?{[n]:e}:[e]:Object.fromEntries(e.map(e=>[e,e])),new iP({channels:i,triggers:Array.isArray(e)?e:[e],tags:r})}static writeTo(e,t){let n=[];for(let t of e)n.push({channel:t,value:XN,skipNone:!1});for(let[e,r]of Object.entries(t??{}))Cx.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:XN,skipNone:!0,mapper:Px(r)}):n.push({channel:e,value:r,skipNone:!1});return new $N(n)}},wL=class extends Cx{lc_namespace=[`langgraph`,`pregel`];invoke(e,t){throw Error(`Not implemented`)}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},TL=class extends wL{static lc_name(){return`LangGraph`}lc_namespace=[`langgraph`,`pregel`];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=[`values`];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;streamTransformers;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,`__pregel_tasks`in this.channels&&`lc_graph_name`in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!==`Topic`)throw Error(`Channel '${HS}' is reserved and cannot be used in the graph.`);this.channels[HS]=new bL({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.streamTransformers=e.streamTransformers??[],this.autoValidate&&this.validate()}withConfig(e){let{streamTransformers:t,...n}=e,r=Xl(this.config,n),i=[...this.streamTransformers,...t??[]];return new this.constructor({...this,config:r,streamTransformers:i})}validate(){vL({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;let i=r.subgraphs?.length?r.subgraphs:[r.bound];for(let r of i){let i=pP(r);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let r=e;e!==void 0&&(r=e.slice(n.length+1));for(let[e,a]of i.getSubgraphs(r,t))yield[`${n}|${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=await wN(this.channels,t.checkpoint,{saver:typeof this.checkpointer==`object`?this.checkpointer:void 0,config:t.config??e});if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===GS).map(([e,t,n])=>[String(t),n]);e.length>0&&TF(t.checkpoint,i,[{name:dS,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(OF(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await KN(this.getSubgraphsAsync()),s=t.config.configurable?.checkpoint_ns??``,c={};for(let e of a){let r=o.find(([t])=>t===e.name);if(!r)continue;let i=`${String(e.name)}:${e.id}`;if(s&&(i=`${s}|${i}`),n===void 0){let n={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}};c[e.id]=n}else{let a={configurable:{[yS]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}},o=r[1];c[e.id]=await o.getState(a,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){let e=Object.fromEntries(a.map(e=>[e.id,e]));for(let[n,r,i]of t.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(r)||n in e&&e[n].writes.push([String(r),i]);let n=a.filter(e=>e.writes.length>0);n.length>0&&TF(t.checkpoint,i,n,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=a.filter(e=>e.writes.length===0).map(e=>e.name);return{values:lF(i,this.streamChannelsAsIs),next:u,tasks:HF(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:lP(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new lC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_read===void 0&&e.configurable?.__pregel_checkpointer===void 0){let i=HN(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(JN(e,{[yS]:n}),{subgraphs:t?.subgraphs})}let i=Xl(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new lC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=HN(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(JN(e,{[yS]:n}),t);return}}let i=Xl(this.config,e,{configurable:{checkpoint_ns:r}});for await(let e of n.list(i,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new lC(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});if(t.length===0)throw Error(`No supersteps provided`);if(t.some(e=>e.updates.length===0))throw Error(`No updates provided`);let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=HN(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(JN(e,{[yS]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?Xl(this.config,e):e,a=await n.getTuple(r),o=a===void 0?nN():rN(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=JN(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=JN(r,a.config.configurable),u={...a.metadata,...u});let{values:d,asNode:f}=t[0];if(d==null&&f===void 0){if(t.length>1)throw new SC(`Cannot create empty checkpoint with multiple updates`);return lP(await n.put(l,CN(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=await wN(this.channels,o,{saver:n,config:a?.config??l});if(d===null&&f===`__end__`){if(t.length>1)throw new SC(`Cannot apply multiple updates when clearing state`);if(a){let e=OF(o,a.pendingWrites||[],this.nodes,p,a.config,!0,{step:(a.metadata?.step??-1)+1,checkpointer:n,store:this.store}),t=(a.pendingWrites||[]).filter(e=>e[0]===GS).map(e=>e.slice(1));t.length>0&&TF(o,p,[{name:dS,writes:t,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(let[t,n,r]of a.pendingWrites||[])[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||t in e&&e[t].writes.push([n,r]);TF(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return lP(await n.put(l,CN(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},oP(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new SC(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new SC(`Cannot copy a non-existent checkpoint`);let e=e=>!Array.isArray(e)||e.length===0?!1:e.every(e=>Array.isArray(e)&&e.length===2),r=CN(o,void 0,c),s=await n.put(a.parentConfig??JN(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=OF(r,a.pendingWrites,this.nodes,p,s,!1,{step:c+2}),t=Object.values(e).reduce((e,{name:t,id:n})=>(e[t]??=[],e[t].push({id:n}),e),{}),n=d.reduce((e,n)=>{let[r,i]=n;e[i]??=[];let a=e[i].length,o=t[i]?.[a]?.id;return e[i].push({values:r,asNode:i,taskId:o}),e},{});return i(lP(s,a.metadata),Object.values(n).flat())}return lP(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new SC(`Cannot apply multiple updates when updating as input`);let e=await KN(dF(this.inputChannels,d));if(e.length===0)throw new SC(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);TF(o,p,[{name:dS,writes:e,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let r=a?.metadata?.step==null?-1:a.metadata.step+1,i=await n.put(l,CN(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},oP(s,o.channel_versions));return await n.putWrites(i,e,OC(dS,o.id)),lP(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=OF(o,a.pendingWrites,this.nodes,p,a.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(a.metadata?.step??-1)+1}),t=(a.pendingWrites??[]).filter(e=>e[0]===GS).map(e=>e.slice(1));t.length>0&&TF(a.checkpoint,p,[{name:dS,writes:t,triggers:[]}],void 0,this.triggerToNodes);for(let[t,n,r]of a.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||e[t]===void 0||e[t].writes.push([n,r]);let n=Object.values(e).filter(e=>e.writes.length>0);n.length>0&&TF(o,p,n,void 0,this.triggerToNodes)}let m=Object.values(o.versions_seen).map(e=>Object.values(e)).flat().find(e=>!!e),h=[];if(t.length===1){let{values:e,asNode:n,taskId:r}=t[0];if(n===void 0&&Object.keys(this.nodes).length===1)[n]=Object.keys(this.nodes);else if(n===void 0&&m===void 0)typeof this.inputChannels==`string`&&this.nodes[this.inputChannels]!==void 0&&(n=this.inputChannels);else if(n===void 0){let e=Object.entries(o.versions_seen).map(([e,t])=>Object.values(t).map(t=>[t,e])).flat().filter(([e,t])=>t!==FS).sort(([e],[t])=>iN(e,t));e&&(e.length===1?n=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(n=e[e.length-1][1]))}if(n===void 0)throw new SC(`Ambiguous update, specify "asNode"`);h.push({values:e,asNode:n,taskId:r})}else for(let{asNode:e,values:n,taskId:r}of t){if(e==null)throw new SC(`"asNode" is required when applying multiple updates`);h.push({values:n,asNode:e,taskId:r})}let g=[];for(let{asNode:e,values:t,taskId:n}of h){if(this.nodes[e]===void 0)throw new SC(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new SC(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?Dx.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[FS],id:n??OC(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,Ql({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[gS]:t=>e.writes.push(...t),[vS]:(t,n=!1)=>xF(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==US);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}TF(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=oP(s,o.channel_versions),v=await n.put(l,CN(o,p,c+1),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},_);for(let e of g){let t=e.writes.filter(e=>e[0]===US);t.length>0&&await n.putWrites(v,t,e.id)}return lP(v,a?a.metadata:void 0)},a=e;for(let{updates:e}of t)a=await i(a,e);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){let{debug:t,streamMode:n,inputKeys:r,outputKeys:i,interruptAfter:a,interruptBefore:o,...s}=e,c=!0,l=t===void 0?this.debug:t,u=i;u===void 0?u=this.streamChannelsAsIs:yL(u,this.channels);let d=r;d===void 0?d=this.inputChannels:yL(d,this.channels);let f=o??this.interruptBefore??[],p=a??this.interruptAfter??[],m;n===void 0?(m=e.configurable?.__pregel_task_id===void 0?this.streamMode:[`values`],c=!0):(m=Array.isArray(n)?n:[n],c=typeof n==`string`);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)h=e.configurable[yS];else if(this.checkpointer===!0)throw Error(`checkpointer: true cannot be used for root graphs.`);else h=this.checkpointer;let g=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?`exit`:`async`})(),y=e.durability??v??e?.configurable?.__pregel_durability??`async`;return[l,m,d,u,s,f,p,h,g,c,_,y]}async stream(e,t){let n=new AbortController,r=VN()?.configurable;r?.__pregel_read!==void 0&&t?.configurable?.__pregel_read===void 0&&(t={...t,configurable:{...r,...t?.configurable}});let i={recursionLimit:this.config?.recursionLimit,...t,signal:uP(t?.signal,n.signal).signal},a=await super.stream(e,i);return new QF(t?.encoding===`text/event-stream`?sI(a):a,n)}async#e(e,t){let{version:n,encoding:r,transformers:i,...a}=t,o={recursionLimit:this.config?.recursionLimit,...a,configurable:{...this.config?.configurable,...a?.configurable},version:n,streamMode:KF,subgraphs:!0,encoding:void 0},s=this.stream(e,o),c=gL({[Symbol.asyncIterator]:async function*(){let e=await s;for await(let t of e)yield t}},[...this.streamTransformers??[],...i??[]]);if(r===`text/event-stream`){let e=new AbortController;return e.signal.addEventListener(`abort`,()=>c.abort(e.signal.reason),{once:!0}),new QF(SL(c),e)}return c}streamEvents(e,t,n){if(t.version===`v3`)return this.#e(e,t);let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,signal:uP(t?.signal,r.signal).signal};return new QF(super.streamEvents(e,i,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let n=`version`in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,i=t?.version===`v3`,a=BN(this.config,t);if(a.recursionLimit===void 0||a.recursionLimit<1)throw Error(`Passed "recursionLimit" must be at least 1.`);if(this.checkpointer!==void 0&&this.checkpointer!==!1&&a.configurable===void 0)throw Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);let o=await this._validateInput(e),{runId:s,...c}=a,[l,u,,d,f,p,m,h,g,_,v,y]=this._defaults(c);f.metadata={ls_integration:`langgraph`,...f.metadata},f.context===void 0?f.configurable=await this._validateContext(f.configurable):f.context=await this._validateContext(f.context);let b=new $F({modes:new Set(u)});if(this.checkpointer===!0){f.configurable??={};let e=f.configurable.checkpoint_ns??``;f.configurable[kS]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(u.includes(`messages`)){let e=i?new TI(e=>b.push(e)):new bI(e=>b.push(e)),{callbacks:t}=f;if(t===void 0)f.callbacks=[e];else if(Array.isArray(t))f.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),f.callbacks=n}}if(u.includes(`tools`)){let e=new eI(e=>b.push(e)),{callbacks:t}=f;if(t===void 0)f.callbacks=[e];else if(Array.isArray(t))f.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),f.callbacks=n}}f.writer??=e=>{if(!u.includes(`custom`))return;let t=(VN()?.configurable?.[kS])?.split(`|`).slice(0,-1);b.push([t??[],`custom`,e])},f.interrupt??=this.userInterrupt??xL,f.serverInfo??=EL(f),f.control??=new hP;let x={tracerInheritableMetadata:kL(f)},ee=await(await zl._configureSync(f?.callbacks,void 0,f?.tags,void 0,f?.metadata,void 0,x))?.handleChainStart(this.toJSON(),sP(e,`input`),s,void 0,void 0,void 0,f?.runName??this.getName()),te=yN(this.channels),S,ne,re=(async()=>{try{S=await _I.initialize({input:o,config:f,checkpointer:h,nodes:this.nodes,channelSpecs:te,outputKeys:d,streamKeys:this.streamChannelsAsIs,store:g,cache:v,stream:b,interruptAfter:m,interruptBefore:p,manager:ee,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:y});let e=new FI({loop:S,nodeFinished:f.configurable?.[AS]});t?.subgraphs&&(S.config.configurable={...S.config.configurable,[SS]:S.stream}),await this._runLoop({loop:S,runner:e,debug:l,config:f}),y===`sync`&&await Promise.all(S?.checkpointerPromises??[])}catch(e){ne=e}finally{try{S&&(await S.store?.stop(),await S.cache?.stop()),await Promise.all(S?.checkpointerPromises??[])}catch(e){ne??=e}ne?(await new Promise(e=>{queueMicrotask(e)}),b.error(ne)):b.close()}})();try{for await(let e of b){if(e===void 0)throw Error(`Data structure error.`);let[a,o,s]=e,c=`version`in(t??{});if(u.includes(o)||o===`checkpoints`&&qF(s)&&(i||c&&r&&u.includes(`values`))){if(n===`text/event-stream`){r?yield[a,o,s]:yield[null,o,s];continue}r&&!_?yield[a,o,s]:_?r?yield[a,s]:yield s:yield[o,s]}}}catch(e){throw await ee?.handleChainError(ne),e}finally{await re}await ee?.handleChainEnd(S?.output??{},s,void 0,void 0,void 0)}async invoke(e,t){let n=t?.streamMode??`values`,r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},i=[],a=await this.stream(e,r),o=[],s;for await(let e of a)n===`values`?tC(e)?o.push(e[FS]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[FS]:e};if(typeof s==`object`)return{...s,[FS]:e}}return s}return i}async _runLoop(e){let{loop:t,runner:n,debug:r,config:i}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:e}of await t._matchCachedWrites())t._outputWrites(e.id,e.writes,!0);r&&UF(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&WF(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&GF(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`draining`)throw t.control==null?Error(`Draining status requires run control`):new uC(t.control.drainReason??`shutdown`);if(t.status===`out_of_steps`)throw new cC([`Recursion limit of ${i.recursionLimit} reached`,`without hitting a stop condition. You can increase the`,`limit by setting the "recursionLimit" config key.`].join(` `),{lc_error_code:`GRAPH_RECURSION_LIMIT`})}catch(e){if(a=e,!await t.finishAndHandleError(a))throw e}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}};function EL(e){let t=e.metadata??{},n=e.configurable??{},r=n.assistant_id??t.assistant_id,i=n.graph_id??t.graph_id,a=n.langgraph_auth_user,o;if(typeof a==`object`&&a&&`identity`in a&&(o=a),r!=null||i!=null||o!=null)return{assistantId:r==null?``:String(r),graphId:i==null?``:String(i),user:o}}var DL=new Set([`key`,`token`,`secret`,`password`,`auth`]);function OL(e,t){let n=e.toLowerCase(),r=!1;for(let e of DL)if(n.includes(e)){r=!0;break}return e.startsWith(`__`)||!(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)||r}function kL(e){let t=e.configurable;if(!t)return;let n={};for(let[e,r]of Object.entries(t))OL(e,r)||(n[e]=r);return Object.keys(n).length>0?n:void 0}var AL=class{path;ends;constructor(e){Cx.isRunnable(e.path)?this.path=e.path:this.path=Px(e.path),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return $N.registerWriter(new WN({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===pC.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
188
188
|
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),e}}}))}async _route(e,t,n,r){let i=await this.path.invoke(r?r(t):e,t);Array.isArray(i)||(i=[i]);let a;if(a=this.ends?i.map(e=>ZS(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(ZS).some(e=>e.node===`__end__`))throw new SC(`Cannot send a packet to the END node`);return await n(a,t)??e}},jL=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`)throw Error(`Node \`${e}\` is reserved.`);let n=Px(t);this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:fP(n)?[n]:r?.subgraphs,ends:r?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e===`__end__`)throw Error(`END cannot be a start node`);if(t===`__start__`)throw Error(`START cannot be an end node`);if(Array.from(this.edges).some(([t])=>t===e)&&!(`channels`in this))throw Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){let r=typeof e==`object`?e:{source:e,path:t,pathMap:n};this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),Cx.isRunnable(r.path)||(r.path=Px(r.path));let i=r.path.getName()===`RunnableLambda`?`condition`:r.path.getName();if(this.branches[r.source]&&this.branches[r.source][i])throw Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][i]=new AL(r),this}setEntryPoint(e){return this.warnIfCompiled(`Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph.`),this.addEdge(lS,e)}setFinishPoint(e){return this.warnIfCompiled(`Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph.`),this.addEdge(e,uS)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r,transformers:i}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let a=new ML({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[lS]:new mP,[uS]:new mP},inputChannels:lS,outputChannels:uS,streamChannels:[],streamMode:`values`,name:r,streamTransformers:i});for(let[e,t]of Object.entries(this.nodes))a.attachNode(e,t);for(let[e,t]of this.edges)a.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))a.attachBranch(e,n,r);return a.validate()}validate(e){let t=new Set([...this.allEdges].map(([e,t])=>e));for(let[e]of Object.entries(this.branches))t.add(e);for(let e of t)if(e!==`__start__`&&!(e in this.nodes))throw Error(`Found edge starting at unknown node \`${e}\``);let n=new Set([...this.allEdges].map(([e,t])=>t));for(let[e,t]of Object.entries(this.branches))for(let r of Object.values(t))if(r.ends!=null)for(let e of Object.values(r.ends))n.add(e);else{n.add(uS);for(let t of Object.keys(this.nodes))t!==e&&n.add(t)}for(let e of Object.values(this.nodes))for(let t of e.ends??[])n.add(t);if(Object.values(this.nodes).some(e=>e.isErrorHandler))for(let e of Object.keys(this.nodes))n.add(e);for(let e of Object.keys(this.nodes))if(!this.nodes[e].isErrorHandler&&!n.has(e))throw new CC([`Node \`${e}\` is not reachable.`,``,`If you are returning Command objects from your node,`,`make sure you are passing names of potential destination nodes as an "ends" array`,`into ".addNode(..., { ends: ["node1", "node2"] })".`].join(`
|
|
189
|
-
`),{lc_error_code:`UNREACHABLE_NODE`});for(let e of n)if(e!==`__end__`&&!(e in this.nodes))throw Error(`Found edge ending at unknown node \`${e}\``);if(e){for(let t of e)if(!(t in this.nodes))throw Error(`Interrupt node \`${t}\` is not present`)}this.compiled=!0}},ML=class extends TL{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new mP,this.nodes[e]=new iP({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new $N([{channel:e,value:XN}],[BS])),this.streamChannels.push(e)}attachEdge(e,t){if(t===`__end__`){if(e===`__start__`)throw Error(`Cannot have an edge from START to END`);this.nodes[e].writers.push(new $N([{channel:uS,value:XN}],[BS]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[lS]=CL.subscribeTo(lS,{tags:[BS]})),this.nodes[e].pipe(n.run(n=>new $N(n.map(n=>ZS(n)?n:{channel:n===`__end__`?uS:`branch:${e}:${t}:${n}`,value:XN}),[BS])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let n of r)if(n!==`__end__`){let r=`branch:${e}:${t}:${n}`;this.channels[r]=new mP,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new dx,r={[lS]:n.addNode({schema:SA()},lS)},i={},a={};t&&(a=Object.fromEntries((await KN(this.getSubgraphsAsync())).filter(e=>NL(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[uS]=n.addNode({schema:SA()},uS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=PL(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):await a[o].getGraphAsync({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!Cr(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(PL(e),PL(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[PL(e),PL(e)])),[uS]:uS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(PL(e),PL(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(PL(e),PL(n),void 0,!0);return FL(this.builder.nodes,o,s),n}getGraph(e){let t=e?.xray,n=new dx,r={[lS]:n.addNode({schema:SA()},lS)},i={},a={};t&&(a=Object.fromEntries(qN(this.getSubgraphs()).filter(e=>NL(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[uS]=n.addNode({schema:SA()},uS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=PL(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):a[o].getGraph({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!Cr(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(PL(e),PL(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[PL(e),PL(e)])),[uS]:uS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(PL(e),PL(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(PL(e),PL(n),void 0,!0);return FL(this.builder.nodes,o,s),n}};function NL(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function PL(e){return e===`subgraph`?`"${e}"`:e}function FL(e,t,n){let r=new Set(t.map(e=>e.src)),i=[...new Set(t.filter(e=>!e.conditional&&e.dest!==`__end__`).map(e=>e.dest))].sort();for(let t of i){if(r.has(t))continue;let i=Object.keys(e).find(e=>PL(e)===t);i!==void 0&&e[i]?.isErrorHandler||n(t,uS)}}var IL=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),LL=class e extends _N{lc_graph_name=`NamedBarrierValue`;names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(t){let n=new e(this.names);return t!==void 0&&(n.seen=new Set(t)),n}update(e){let t=!1;for(let n of e)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),t=!0);else throw new SC(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!IL(this.names,this.seen))throw new xC}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&IL(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&IL(this.names,this.seen)}},RL=class e extends _N{lc_graph_name=`NamedBarrierValueAfterFinish`;names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new e(this.names);if(t!==void 0){let[e,r]=t;n.seen=new Set(e),n.finished=r}return n}update(e){let t=!1;for(let n of e)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),t=!0;else if(!this.names.has(n))throw new SC(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!IL(this.names,this.seen))throw new xC}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&IL(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&IL(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&IL(this.names,this.seen)}};function zL(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function BL(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function VL(e){if(BL(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function HL(e){if(e!=null&&zL(e))try{let t=e[`~standard`].validate(void 0);if(t&&typeof t==`object`&&!(`then`in t&&typeof t.then==`function`)){let e=t;if(!e.issues){let t=e.value;return()=>t}}}catch{}}var UL=e=>e!=null&&e.lc_graph_name===`DeltaChannel`,WL=class e extends _N{lc_graph_name=`DeltaChannel`;value;reducer;snapshotFrequency;initialValueFactory;constructor(e,t){super();let n=t?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=e,this.snapshotFrequency=n,this.initialValueFactory=t?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let n=new e(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?n.value=this.initialValueFactory():PC(t)?n.value=t.value:n.value=t,n}replayWrites(e){let t=e.map(e=>e[2]);if(t.length===0)return;let n=this.value,r=0;for(let e=0;e<t.length;e+=1){let[i,a]=$S(t[e]);i&&(n=a??this.initialValueFactory(),r=e+1)}let i=t.slice(r);this.value=i.length>0?this.reducer(n,i):n}update(e){if(e.length===0)return!1;let t,n=!1;for(let r of e)if(eC(r)){if(n)throw new SC(`Can receive only one Overwrite value per step.`);n=!0,[,t]=$S(r)}if(n)return this.value=t??this.initialValueFactory(),!0;let r=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(r,e),!0}get(){if(this.value===void 0)throw new xC;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:!UL(e)||this.snapshotFrequency!==e.snapshotFrequency?!1:this.reducer===e.reducer}},GL=Symbol.for(`langgraph.channel.missing`),KL=class e extends _N{lc_graph_name=`UntrackedValue`;guard;_value=GL;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new e({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new SC(`UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this._value=e[e.length-1],!0}get(){if(this._value===GL)throw new xC;return this._value}checkpoint(){}isAvailable(){return this._value!==GL}},qL=Symbol.for(`langgraph.state.reduced_value`),JL=class{[qL]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&qL in e&&e[qL]===!0}},YL=Symbol.for(`langgraph.state.untracked_value`),XL=class{[YL]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&YL in e}},ZL=Symbol.for(`langgraph.state.delta_value`),QL=class{[ZL]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&ZL in e&&e[ZL]===!0}},$L=Symbol.for(`langgraph.state.state_schema`),eR=class{[$L]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(QL.isInstance(n)){let r=HL(n.valueSchema);e[t]=new WL(n.reducer,{snapshotFrequency:n.snapshotFrequency,initialValueFactory:r})}else if(JL.isInstance(n)){let r=HL(n.valueSchema);e[t]=new ON(n.reducer,r)}else if(XL.isInstance(n)){let r=n.schema?HL(n.schema):void 0;e[t]=new KL({guard:n.guard,initialValueFactory:r})}else if(zL(n))e[t]=new TN(HL(n));else throw Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let i;if(QL.isInstance(r)||JL.isInstance(r)?(i=VL(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):XL.isInstance(r)?i=r.schema?VL(r.schema):void 0:zL(r)&&(i=VL(r)),i){e[n]=i;let a=!1;a=QL.isInstance(r)||JL.isInstance(r)?HL(r.valueSchema)!==void 0:XL.isInstance(r)?r.schema?HL(r.schema)!==void 0:!1:HL(r)!==void 0,a||t.push(n)}}return{type:`object`,properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;QL.isInstance(n)||JL.isInstance(n)?(r=VL(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):XL.isInstance(n)?r=n.schema?VL(n.schema):void 0:zL(n)&&(r=VL(n)),r&&(e[t]=r)}return{type:`object`,properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=this.fields[n];if(e===void 0){t[n]=r;continue}let i;if(QL.isInstance(e)||JL.isInstance(e)){let[a,o]=$S(r);if(a){i=e.valueSchema;let r=await i[`~standard`].validate(o);if(r.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(r.issues)}`);t[n]={[QS]:r.value};continue}i=e.inputSchema}else XL.isInstance(e)?i=e.schema:zL(e)&&(i=e);if(i){let e=await i[`~standard`].validate(r);if(e.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(e.issues)}`);t[n]=e.value}else t[n]=r}return t}static isInstance(e){return typeof e==`object`&&!!e&&$L in e&&e[$L]===!0}};function tR(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(En),a=r.map(En);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=yr(),e.lc_kwargs.id=e.id);let o;for(let e=0;e<a.length;e+=1){let t=a[e];(t.id===null||t.id===void 0)&&(t.id=yr(),t.lc_kwargs.id=t.id),gn.isInstance(t)&&t.id===`__remove_all__`&&(o=e)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((e,t)=>[e.id,t])),l=new Set;for(let e of a){let t=c.get(e.id);if(t!==void 0)gn.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(gn.isInstance(e))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);c.set(e.id,s.length),s.push(e)}}return s.filter(e=>!l.has(e.id))}function nR(e,t){let n=[];for(let e of t)Array.isArray(e)?n.push(...e):n.push(e);let r=e.length>0&&rt.isInstance(e[0])?e:e.map(En),i=n.map(En),a=new Map;for(let e=0;e<r.length;e+=1){let t=r[e].id;t!=null&&a.set(t,e)}let o=[...r];for(let e of i){let t=e.id;gn.isInstance(e)&&t===`__remove_all__`?(o.length=0,a.clear()):t==null?o.push(e):gn.isInstance(e)?a.has(t)&&(o[a.get(t)]=null,a.delete(t)):a.has(t)?o[a.get(t)]=e:(a.set(t,o.length),o.push(e))}return o.filter(e=>e!==null)}var rR=dj().default(()=>[]),iR=dj();new JL(rR,{inputSchema:iR,reducer:tR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}}),new QL(rR,{inputSchema:iR,reducer:nR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var aR=new class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=v_(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new ON(n.reducer.fn,n.default):t[e]=new TN(n?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,e])=>e===!0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`|`),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let n=Object.entries(v_(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=l_(i)??l_(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=y_(e,Object.fromEntries(n)),$g(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=b_(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function oR(e){return e==null?!1:!!(eR.isInstance(e)||__(e)||typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(e=>typeof e==`function`||gN(e)))}function sR(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&oR(t.state),r=`stateSchema`in t&&oR(t.stateSchema),i=`input`in t&&oR(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!oR(t.input)||`output`in t&&t.output!=null&&!oR(t.output))}var cR=`__root__`,lR=`__default_error_handler__`,uR=Symbol.for(`langgraph.state.partial`),dR=class extends jL{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=aR;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new wC;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(eR.isInstance(r)||__(r))&&(this._schemaRuntimeDefinition=r),n.input&&(eR.isInstance(n.input)||__(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=uR,n.output&&(eR.isInstance(n.output)||__(n.output))?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):i,o=n.output?this._getChannelsFromSchema(n.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&__(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.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=cS(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new WN({func:(t,n)=>{let r=n?.configurable?.[jS];return e(t,r,n)},name:lR,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(sR(e)){if(__(t)||kN.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(oR(e)){if(__(t)||kN.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(mR(e))return{state:fR(e.channels)};throw new wC}_getChannelsFromSchema(e){if(eR.isInstance(e))return e.getChannels();if(__(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 wC(`Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.`)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(e=>[e,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let e;if(e=typeof n==`function`?n():n,this.channels[t]!==void 0){if(!this.channels[t].equals(e)&&e.lc_graph_name!==`LastValue`)throw Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([e,t])=>[e,t]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){if(e in this.channels)throw Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`||e===`__start__`)throw Error(`Node \`${e}\` is reserved.`);let n=this._schemaDefinition;r?.input!==void 0&&(n=this._getChannelsFromSchema(r.input)),this._addSchema(n);let i;i=Cx.isRunnable(t)?t:typeof t==`function`?new WN({func:t,name:e,trace:!1}):Px(t);let a=r?.cachePolicy,o;a!==void 0&&(o=typeof a==`boolean`?a?{}:!1:a);let s;if(r?.errorHandler!==void 0){if(s=`__error_handler__${e}`,s in this.nodes)throw Error(`Cannot add error handler to node \`${e}\`: the reserved name \`${s}\` 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).`);let t=r.errorHandler,i={runnable:new WN({func:(e,n)=>{let r=n?.configurable?.[jS];return t(e,r,n)},name:s,trace:!1}),metadata:void 0,input:n??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[s]=i}let c={runnable:i,retryPolicy:r?.retryPolicy,cachePolicy:o,timeout:cS(r?.timeout),metadata:r?.metadata,input:n??this._schemaDefinition,subgraphs:fP(i)?[i]:r?.subgraphs,ends:r?.ends,defer:r?.defer,errorHandlerNode:s};this.nodes[e]=c}return this}addEdge(e,t){if(typeof e==`string`)return super.addEdge(e,t);this.compiled&&console.warn(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`);for(let t of e){if(t===`__end__`)throw Error(`END cannot be a start node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`)}if(t===`__end__`)throw Error(`END cannot be an end node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw Error(`Sequence requires at least one node.`);let n;for(let[e,r,i]of t){if(e in this.nodes)throw Error(`Node names must be unique: node with the name "${e}" already exists.`);let t=e;this.addNode(e,r,i),n!=null&&this.addEdge(n,t),n=t}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(lR in this.nodes)throw Error(`Cannot apply a default error handler: the reserved node name \`${lR}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[lR]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c===void 0?void 0:lR})}finally{c!==void 0&&delete this.nodes[lR]}}_compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===cR?cR:l,d=Object.keys(this.channels),f=d.length===1&&d[0]===cR?cR:d,p=this._interrupt,m=new pR({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[lS]:new mP},inputChannels:lS,outputChannels:u,streamChannels:f,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:p,streamTransformers:s});m.attachNode(lS);let h=this._nodeDefaults,g=h.retryPolicy!==void 0||h.cachePolicy!==void 0||h.timeout!==void 0||c!==void 0;for(let[e,t]of Object.entries(this.nodes)){let n=t.isErrorHandler===!0,r=g?{...t,retryPolicy:t.retryPolicy??h.retryPolicy,cachePolicy:n||t.cachePolicy===!1?void 0:t.cachePolicy??h.cachePolicy,timeout:t.timeout??h.timeout,errorHandlerNode:!n&&c!==void 0&&t.errorHandlerNode===void 0?c:t.errorHandlerNode}:t;m.attachNode(e,r)}m.attachBranch(lS,VS,gR(),{withReader:!1});for(let[e]of Object.entries(this.nodes))m.attachBranch(e,VS,gR(),{withReader:!1});for(let[e,t]of this.edges)m.attachEdge(e,t);for(let[e,t]of this.waitingEdges)m.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))m.attachBranch(e,n,r);return m.validate()}};function fR(e){let t={};for(let[n,r]of Object.entries(e))t[n]=jN(r);return t}var pR=class extends ML{description;_metaRegistry=aR;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;n=e===`__start__`?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([e])=>e):Object.keys(this.builder.channels);function r(e){if(rC(e))return e.graph===nC.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>rC(e))){let t=[];for(let n of e)if(rC(n)){if(n.graph===nC.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([cR,n]);return t}else if(e!=null)return[[cR,e]];return null}let i=e,a=async e=>{if(e==null||e.length===0)return e;let t=this.builder._schemaRuntimeDefinition;if(eR.isInstance(t)){let n=new Set(t.getChannelKeys());return Promise.all(e.map(async([e,r])=>{if(!n.has(e))return[e,r];let i=await t.validateInput({[e]:r});return[e,Object.prototype.hasOwnProperty.call(i,e)?i[e]:r]}))}if(__(t)){let n=new Set(Object.keys(v_(t)));if(e.filter(([e])=>n.has(e)).length===0)return e;let r=b_(this._metaRegistry.getExtendedChannelSchemas(t,{withReducerSchema:!0})),i=b_(t);return e.map(([e,t])=>{if(!n.has(e))return[e,t];let[a,o]=$S(t);if(a){let n=c_(i,{[e]:o});return[e,Object.prototype.hasOwnProperty.call(n,e)?{[QS]:n[e]}:t]}let s=c_(r,{[e]:t});return[e,Object.prototype.hasOwnProperty.call(s,e)?s[e]:t]})}return e};async function o(e){if(!e)return null;if(rC(e))return e.graph===nC.PARENT?null:a(e._updateAsTuples().filter(([e])=>n.includes(e)));if(Array.isArray(e)&&e.length>0&&e.some(rC)){let t=[];for(let r of e)if(rC(r)){if(r.graph===nC.PARENT)continue;t.push(...r._updateAsTuples().filter(([e])=>n.includes(e)))}else{let e=await o(r);e&&t.push(...e??[])}return a(t)}else if(typeof e==`object`&&!Array.isArray(e))return a(Object.entries(e).filter(([e])=>n.includes(e)));else{let t=Array.isArray(e)?`array`:typeof e;throw new SC(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${t}`,{lc_error_code:`INVALID_GRAPH_NODE_RETURN_VALUE`})}}let s=[{value:XN,mapper:new WN({func:n.length&&n[0]===cR?r:o,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new iP({tags:[BS],triggers:[lS],channels:[lS],writers:[new $N(s,[BS])]});else{let n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map(e=>[e,e])),i=Object.keys(r).length===1&&cR in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new EN:new mP(!1);let o=t?.cachePolicy,c=o===!1?void 0:o;this.nodes[e]=new iP({triggers:[a],channels:i?Object.keys(r):r,writers:[new $N(s,[BS])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter(([e])=>e in r)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:c,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!==`__end__`){if(typeof e==`string`)this.nodes[e].writers.push(new $N([{channel:`branch:to:${t}`,value:null}],[BS]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new RL(new Set(e)):new LL(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new $N([{channel:n,value:t}],[BS]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==uS);if(!r.length)return;let i=r.map(t=>ZS(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await $N.doWrite({...n,tags:(n.tags??[]).concat([BS])},i)},r.withReader?e=>nP.doRead(e,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(eR.isInstance(t)){if(rC(e)){let n=e;return e.update&&(n.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),n}return await t.validateInput(e)}if(t===uR&&eR.isInstance(n)){if(rC(e)){let t=e;return e.update&&(t.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),t}return await n.validateInput(e)}let r=(()=>{let e=e=>{if(e!=null)return this._metaRegistry.getExtendedChannelSchemas(e,{withReducerSchema:!0})};if(__(t))return e(t);if(t===uR)return __(n)?b_(e(n)):void 0})();if(rC(e)){let t=e;if(e.update&&r!=null){let n=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,i=c_(r,n);t.update=Object.fromEntries(Object.keys(n).map(e=>[e,i[e]]))}return t}return r==null?e:c_(r,e)}isInterrupted(e){return tC(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return __(t)&&c_(t,e),e}};function mR(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function hR(e){if(ZS(e))return[e];let t=[];rC(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(rC));let n=[];for(let e of t){if(e.graph===nC.PARENT)throw new hC(e);ZS(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function gR(){return new AL({path:new WN({func:hR,tags:[BS],trace:!1,recurse:!1,name:`<control_branch>`})})}var _R=e=>Array.isArray(e)&&e.every(_t),vR=e=>typeof e==`object`&&!!e&&`messages`in e&&_R(e.messages),yR=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,bR=class extends WN{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:n,tags:r,handleToolErrors:i}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,t,n){let r=this.tools.find(t=>t.name===e.name);try{if(r===void 0)throw Error(`Tool "${e.name}" not found.`);let i={...e,type:`tool_call`},a={...t,state:n,toolCallId:e.id??``,config:t,context:t.context,store:t.store??null,writer:t.writer??t.configurable?.writer??null},o=await r.invoke(i,a);return _t(o)&&o.getType()===`tool`||rC(o)?o:new xt({status:`success`,name:r.name,content:typeof o==`string`?o:JSON.stringify(o),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||vC(t))throw t;return new xt({status:`error`,content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??``})}}async run(e,t){let n;if(yR(e)){let{lg_tool_call:r,...i}=e;n=[await this.runTool(r,t,i)]}else{let r;if(_R(e))r=e;else if(vR(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(en(t)){a=t;break}}if(a==null||!en(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(n=>this.runTool(n,t,e))??[])}if(!n.some(rC))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)rC(t)?t.graph===nC.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>ZS(e))?i?i.goto.push(...t.goto):i=new nC({graph:nC.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},xR=/<name>(.*?)<\/name>/s,SR=/<content>(.*?)<\/content>/s;function CR(e){if(!(_t(e)&&(en(e)||vt(e)&&tn(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new $t({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new $t({...e.lc_kwargs,content:n,name:void 0})}function wR(e){if(!en(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(xR),r=e.text.match(SR);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(xR),r=e.text.match(SR);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(xR),a=r.match(SR);if(!i||!a)return e;n=i[1],t=a[1]}return new $t({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function TR(e,t){let n,r;if(t===`inline`)n=CR,r=wR;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return Dx.from([jx.from(i),e,jx.from(r)])}function ER(e){if(typeof e==`string`||_t(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(Cx.isRunnable(e))return jx.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var DR=`prompt`;function OR(e){let t;if(e==null)t=jx.from(e=>e.messages).withConfig({runName:DR});else if(typeof e==`string`){let n=new _n(e);t=jx.from(e=>[n,...e.messages??[]]).withConfig({runName:DR})}else if(_t(e)&&e._getType()===`system`)t=jx.from(t=>[e,...t.messages]).withConfig({runName:DR});else if(typeof e==`function`)t=jx.from(e).withConfig({runName:DR});else if(Cx.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function kR(e){return Cx.isRunnable(e)}function AR(e,t,n){if([e,t,n].filter(e=>e!=null).length>1)throw Error(`Expected only one of prompt, stateModifier, or messageModifier, got multiple values`);let r=e;return t==null?n!=null&&(r=ER(n)):r=t,OR(r)}function jR(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function MR(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function NR(e){return jR(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function PR(e,t){let n=e;if(Dx.isRunnableSequence(n)&&(n=n.steps.find(e=>wx.isRunnableBinding(e)||jR(e)||MR(e))||n),MR(n)&&(n=await n._model()),!wx.isRunnableBinding(n))return!0;let r=n.kwargs!=null&&typeof n.kwargs==`object`&&`tools`in n.kwargs&&Array.isArray(n.kwargs.tools)?n.kwargs.tools??null:n.config!=null&&typeof n.config==`object`&&`tools`in n.config&&Array.isArray(n.config.tools)?n.config.tools??null:null;if(r!=null&&r.length===1&&`functionDeclarations`in r[0]&&(r=r[0].functionDeclarations),r==null)return!0;if(t.length!==r.length)throw Error(`Number of tools in the model.bindTools() and tools passed to createReactAgent must match`);let i=new Set(t.flatMap(e=>kR(e)?e.name:[])),a=new Set;for(let e of r){let t;if(`type`in e&&e.type===`function`)t=e.function.name;else if(`name`in e)t=e.name;else if(`toolSpec`in e&&`name`in e.toolSpec)t=e.toolSpec.name;else continue;t&&a.add(t)}let o=[...i].filter(e=>!a.has(e));if(o.length>0)throw Error(`Missing tools '${o}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}var FR=(e,t)=>{if(NR(e))return e.bindTools(t);if(wx.isRunnableBinding(e)&&NR(e.bound)){let n=e.bound.bindTools(t);return wx.isRunnableBinding(n)?new wx({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new wx({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function IR(e,t){let n=FR(e,t);if(n)return n;if(MR(e)){let n=FR(await e._model(),t);if(n)return n}if(Dx.isRunnableSequence(e)){let n=e.steps.findIndex(e=>wx.isRunnableBinding(e)||jR(e)||MR(e));if(n>=0){let r=FR(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),Dx.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function LR(e){let t=e;if(Dx.isRunnableSequence(t)&&(t=t.steps.find(e=>wx.isRunnableBinding(e)||jR(e)||MR(e))||t),MR(t)&&(t=await t._model()),wx.isRunnableBinding(t)&&(t=t.bound),!jR(t))throw Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}var RR=()=>AN.Root({messages:AN({reducer:tR,default:()=>[]}),structuredResponse:AN}),zR=AN.Root({llmInputMessages:AN({reducer:(e,t)=>tR([],t),default:()=>[]})});function BR(e){let{llm:t,tools:n,messageModifier:r,stateModifier:i,prompt:a,stateSchema:o,contextSchema:s,checkpointSaver:c,checkpointer:l,interruptBefore:u,interruptAfter:d,store:f,responseFormat:p,preModelHook:m,postModelHook:h,name:g,description:_,version:v=`v1`,includeAgentName:y}=e,b,x;Array.isArray(n)?(b=n,x=new bR(b.filter(kR))):(b=n.tools,x=n);let ee=null,te=async e=>{if(ee)return ee;let t;t=await PR(e,b)?await IR(e,b):e;let n=AR(a,i,r),o=y===`inline`?TR(t,y):t;return ee=n.pipe(o),ee},S=async(e,t,n)=>{let o=await e(t,n);return AR(a,i,r).pipe(y===`inline`?TR(o,y):o)},ne=new Set(b.filter(kR).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function re(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ie=async(e,n)=>{if(p==null)throw Error(`Attempted to generate structured output with no passed response schema. Please contact us for help.`);let r=[...e.messages],i,a=typeof t==`function`?await t(e,n):await LR(t);if(!jR(a))throw Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${a.constructor.name}`);if(typeof p==`object`&&`schema`in p){let{prompt:e,schema:t,...n}=p;i=a.withStructuredOutput(t,n),e!=null&&r.unshift(new _n({content:e}))}else i=a.withStructuredOutput(p);let o=await i.invoke(r,n);if(o==null)throw Error("Failed to parse structured response against the provided `responseFormat` schema: the structured-output parser returned null/undefined, which usually means the model output did not satisfy the schema.");return{structuredResponse:o}},ae=async(e,n)=>{let r=await(typeof t==`function`?await S(t,e,n):await te(t)).invoke(re(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},oe=new dR(o??RR(),s).addNode(`tools`,x);if(!(`messages`in oe._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let se=oe,ce=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),C=`agent`,le;return m==null?C=`agent`:(se.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),C=`pre_model_hook`,le=AN.Root({...oe._schemaDefinition,...zR.spec})),se.addNode(`agent`,ae,{input:le}).addEdge(lS,C),h!=null&&se.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter(wt).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(en(n)){r=n;break}}let i=r?.tool_calls?.filter(e=>e.id==null||!n.has(e.id))??[],a=t[t.length-1];return i.length>0?v===`v2`?i.map(t=>new XS(`tools`,{...e,lg_tool_call:t})):`tools`:a&&wt(a)?C:p==null?uS:`generate_structured_response`},ce({tools:`tools`,[C]:C,generate_structured_response:p==null?null:`generate_structured_response`,[uS]:p==null?uS:null})),p!==void 0&&oe.addNode(`generate_structured_response`,ie).addEdge(`generate_structured_response`,uS),h??se.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!en(n)||!n.tool_calls?.length?p==null?uS:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new XS(`tools`,{...e,lg_tool_call:t})):`tools`},ce({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[uS]:p==null?uS:null})),ne.size>0?se.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!wt(n))break;if(n.name!==void 0&&ne.has(n.name))return uS}return C},ce({[C]:C,[uS]:uS})):se.addEdge(`tools`,C),se.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function VR(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function H(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function U(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var HR=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return HR=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function UR(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var WR=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},W=class extends Error{},GR=class e extends W{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new qR({message:r,cause:WR(n)});let a=n?.error;return t===400?new YR(t,a,r,i):t===401?new XR(t,a,r,i):t===403?new ZR(t,a,r,i):t===404?new QR(t,a,r,i):t===409?new $R(t,a,r,i):t===422?new ez(t,a,r,i):t===429?new tz(t,a,r,i):t>=500?new nz(t,a,r,i):new e(t,a,r,i)}},KR=class extends GR{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},qR=class extends GR{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},JR=class extends qR{constructor({message:e}={}){super({message:e??`Request timed out.`})}},YR=class extends GR{},XR=class extends GR{},ZR=class extends GR{},QR=class extends GR{},$R=class extends GR{},ez=class extends GR{},tz=class extends GR{},nz=class extends GR{},rz=class extends W{constructor(){super(`Could not parse response content as the length limit was reached`)}},iz=class extends W{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},az=class extends Error{constructor(e){super(e)}},oz=class extends GR{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},sz=class extends W{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},cz=/^[a-z][a-z0-9+.-]*:/i,lz=e=>cz.test(e),uz=e=>(uz=Array.isArray,uz(e)),dz=uz;function fz(e){return typeof e==`object`?e??{}:{}}function pz(e){if(!e)return!0;for(let t in e)return!1;return!0}function mz(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function hz(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var gz=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new W(`${e} must be an integer`);if(t<0)throw new W(`${e} must be a positive integer`);return t},_z=e=>{try{return JSON.parse(e)}catch{return}},vz=e=>new Promise(t=>setTimeout(t,e)),yz=`6.45.0`,bz=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function xz(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var Sz=()=>{let e=xz();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":Tz(Deno.build.os),"X-Stainless-Arch":wz(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":Tz(globalThis.process.platform??`unknown`),"X-Stainless-Arch":wz(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Cz();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Cz(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var wz=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Tz=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Ez,Dz=()=>Ez??=Sz();function Oz(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function kz(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Az(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return kz({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function jz(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Mz(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Nz=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Pz=`RFC3986`,Fz=e=>String(e),Iz={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Fz},Lz=(e,t)=>(Lz=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Lz(e,t)),Rz=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),zz=1024,Bz=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=zz){let t=a.length>=zz?a.slice(e,e+zz):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=Rz[r];continue}if(r<2048){n[n.length]=Rz[192|r>>6]+Rz[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=Rz[224|r>>12]+Rz[128|r>>6&63]+Rz[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=Rz[240|r>>18]+Rz[128|r>>12&63]+Rz[128|r>>6&63]+Rz[128|r&63]}o+=n.join(``)}return o};function Vz(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Hz(e,t){if(uz(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Uz={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Wz=function(e,t){Array.prototype.push.apply(e,uz(t)?t:[t])},Gz,Kz={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Bz,encodeValuesOnly:!1,format:Pz,formatter:Fz,indices:!1,serializeDate(e){return(Gz??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function qz(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Jz={};function Yz(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(Jz))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(Jz)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&uz(v)&&(v=Hz(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,Kz.encoder,g,`key`,p):t;v=``}if(qz(v)||Vz(v)){if(c){let e=h?t:c(t,Kz.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,Kz.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&uz(v))h&&c&&(v=Hz(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(uz(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let S=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&uz(v)&&v.length===1?S+`[]`:S;if(i&&uz(v)&&v.length===0)return ne+`[]`;for(let t=0;t<te.length;++t){let y=te[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let S=d&&s?y.replace(/\./g,`%2E`):y,re=uz(v)?typeof n==`function`?n(ne,S):ne:ne+(d?`.`+S:`[`+S+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Jz,_),Wz(ee,Yz(x,re,n,r,i,a,o,s,n===`comma`&&h&&uz(v)?null:c,l,u,d,f,p,m,h,g,ie))}return ee}function Xz(e=Kz){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||Kz.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Pz;if(e.format!==void 0){if(!Lz(Iz,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Iz[n],i=Kz.filter;(typeof e.filter==`function`||uz(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Uz?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:Kz.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:Kz.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:Kz.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:Kz.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:Kz.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?Kz.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:Kz.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:Kz.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:Kz.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:Kz.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:Kz.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:Kz.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:Kz.strictNullHandling}}function Zz(e,t={}){let n=e,r=Xz(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):uz(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Uz[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||Wz(o,Yz(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Qz(e){return Zz(e,{arrayFormat:`brackets`})}function $z(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var eB;function tB(e){let t;return(eB??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var nB;function rB(e){let t;return(nB??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var iB,aB,oB=class{constructor(){iB.set(this,void 0),aB.set(this,void 0),H(this,iB,new Uint8Array,`f`),H(this,aB,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?tB(e):e;H(this,iB,$z([U(this,iB,`f`),t]),`f`);let n=[],r;for(;(r=sB(U(this,iB,`f`),U(this,aB,`f`)))!=null;){if(r.carriage&&U(this,aB,`f`)==null){H(this,aB,r.index,`f`);continue}if(U(this,aB,`f`)!=null&&(r.index!==U(this,aB,`f`)+1||r.carriage)){n.push(rB(U(this,iB,`f`).subarray(0,U(this,aB,`f`)-1))),H(this,iB,U(this,iB,`f`).subarray(U(this,aB,`f`)),`f`),H(this,aB,null,`f`);continue}let e=U(this,aB,`f`)===null?r.preceding:r.preceding-1,t=rB(U(this,iB,`f`).subarray(0,e));n.push(t),H(this,iB,U(this,iB,`f`).subarray(r.index),`f`),H(this,aB,null,`f`)}return n}flush(){return U(this,iB,`f`).length?this.decode(`
|
|
189
|
+
`),{lc_error_code:`UNREACHABLE_NODE`});for(let e of n)if(e!==`__end__`&&!(e in this.nodes))throw Error(`Found edge ending at unknown node \`${e}\``);if(e){for(let t of e)if(!(t in this.nodes))throw Error(`Interrupt node \`${t}\` is not present`)}this.compiled=!0}},ML=class extends TL{builder;constructor({builder:e,...t}){super(t),this.builder=e}withConfig(e){return super.withConfig(e)}attachNode(e,t){this.channels[e]=new mP,this.nodes[e]=new iP({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new $N([{channel:e,value:XN}],[BS])),this.streamChannels.push(e)}attachEdge(e,t){if(t===`__end__`){if(e===`__start__`)throw Error(`Cannot have an edge from START to END`);this.nodes[e].writers.push(new $N([{channel:uS,value:XN}],[BS]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[lS]=CL.subscribeTo(lS,{tags:[BS]})),this.nodes[e].pipe(n.run(n=>new $N(n.map(n=>ZS(n)?n:{channel:n===`__end__`?uS:`branch:${e}:${t}:${n}`,value:XN}),[BS])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let n of r)if(n!==`__end__`){let r=`branch:${e}:${t}:${n}`;this.channels[r]=new mP,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new dx,r={[lS]:n.addNode({schema:SA()},lS)},i={},a={};t&&(a=Object.fromEntries((await KN(this.getSubgraphsAsync())).filter(e=>NL(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[uS]=n.addNode({schema:SA()},uS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=PL(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):await a[o].getGraphAsync({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!Cr(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(PL(e),PL(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[PL(e),PL(e)])),[uS]:uS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(PL(e),PL(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(PL(e),PL(n),void 0,!0);return FL(this.builder.nodes,o,s),n}getGraph(e){let t=e?.xray,n=new dx,r={[lS]:n.addNode({schema:SA()},lS)},i={},a={};t&&(a=Object.fromEntries(qN(this.getSubgraphs()).filter(e=>NL(e[1]))));let o=[];function s(e,t,a,s=!1){if(t===`__end__`&&i.__end__===void 0&&(i[uS]=n.addNode({schema:SA()},uS)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return o.push({src:e,dest:t,conditional:s}),n.addEdge(r[e],i[t],a===t?void 0:a,s)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=PL(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):a[o].getGraph({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!Cr(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let c=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of c)s(PL(e),PL(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[PL(e),PL(e)])),[uS]:uS};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))s(PL(e),PL(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)s(PL(e),PL(n),void 0,!0);return FL(this.builder.nodes,o,s),n}};function NL(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function PL(e){return e===`subgraph`?`"${e}"`:e}function FL(e,t,n){let r=new Set(t.map(e=>e.src)),i=[...new Set(t.filter(e=>!e.conditional&&e.dest!==`__end__`).map(e=>e.dest))].sort();for(let t of i){if(r.has(t))continue;let i=Object.keys(e).find(e=>PL(e)===t);i!==void 0&&e[i]?.isErrorHandler||n(t,uS)}}var IL=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),LL=class e extends _N{lc_graph_name=`NamedBarrierValue`;names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(t){let n=new e(this.names);return t!==void 0&&(n.seen=new Set(t)),n}update(e){let t=!1;for(let n of e)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),t=!0);else throw new SC(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!IL(this.names,this.seen))throw new xC}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&IL(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&IL(this.names,this.seen)}},RL=class e extends _N{lc_graph_name=`NamedBarrierValueAfterFinish`;names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new e(this.names);if(t!==void 0){let[e,r]=t;n.seen=new Set(e),n.finished=r}return n}update(e){let t=!1;for(let n of e)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),t=!0;else if(!this.names.has(n))throw new SC(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!IL(this.names,this.seen))throw new xC}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&IL(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&IL(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&IL(this.names,this.seen)}};function zL(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function BL(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function VL(e){if(BL(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function HL(e){if(e!=null&&zL(e))try{let t=e[`~standard`].validate(void 0);if(t&&typeof t==`object`&&!(`then`in t&&typeof t.then==`function`)){let e=t;if(!e.issues){let t=e.value;return()=>t}}}catch{}}var UL=e=>e!=null&&e.lc_graph_name===`DeltaChannel`,WL=class e extends _N{lc_graph_name=`DeltaChannel`;value;reducer;snapshotFrequency;initialValueFactory;constructor(e,t){super();let n=t?.snapshotFrequency??1e3;if(!Number.isInteger(n)||n<=0)throw Error(`snapshotFrequency must be a positive integer, got ${n}`);this.reducer=e,this.snapshotFrequency=n,this.initialValueFactory=t?.initialValueFactory??(()=>[]),this.value=void 0}fromCheckpoint(t){let n=new e(this.reducer,{snapshotFrequency:this.snapshotFrequency,initialValueFactory:this.initialValueFactory});return t===void 0?n.value=this.initialValueFactory():PC(t)?n.value=t.value:n.value=t,n}replayWrites(e){let t=e.map(e=>e[2]);if(t.length===0)return;let n=this.value,r=0;for(let e=0;e<t.length;e+=1){let[i,a]=$S(t[e]);i&&(n=a??this.initialValueFactory(),r=e+1)}let i=t.slice(r);this.value=i.length>0?this.reducer(n,i):n}update(e){if(e.length===0)return!1;let t,n=!1;for(let r of e)if(eC(r)){if(n)throw new SC(`Can receive only one Overwrite value per step.`);n=!0,[,t]=$S(r)}if(n)return this.value=t??this.initialValueFactory(),!0;let r=this.value===void 0?this.initialValueFactory():this.value;return this.value=this.reducer(r,e),!0}get(){if(this.value===void 0)throw new xC;return this.value}checkpoint(){}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:!UL(e)||this.snapshotFrequency!==e.snapshotFrequency?!1:this.reducer===e.reducer}},GL=Symbol.for(`langgraph.channel.missing`),KL=class e extends _N{lc_graph_name=`UntrackedValue`;guard;_value=GL;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new e({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new SC(`UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this._value=e[e.length-1],!0}get(){if(this._value===GL)throw new xC;return this._value}checkpoint(){}isAvailable(){return this._value!==GL}},qL=Symbol.for(`langgraph.state.reduced_value`),JL=class{[qL]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&qL in e&&e[qL]===!0}},YL=Symbol.for(`langgraph.state.untracked_value`),XL=class{[YL]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&YL in e}},ZL=Symbol.for(`langgraph.state.delta_value`),QL=class{[ZL]=!0;valueSchema;inputSchema;reducer;snapshotFrequency;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.snapshotFrequency=t.snapshotFrequency,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&ZL in e&&e[ZL]===!0}},$L=Symbol.for(`langgraph.state.state_schema`),eR=class{[$L]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if(QL.isInstance(n)){let r=HL(n.valueSchema);e[t]=new WL(n.reducer,{snapshotFrequency:n.snapshotFrequency,initialValueFactory:r})}else if(JL.isInstance(n)){let r=HL(n.valueSchema);e[t]=new ON(n.reducer,r)}else if(XL.isInstance(n)){let r=n.schema?HL(n.schema):void 0;e[t]=new KL({guard:n.guard,initialValueFactory:r})}else if(zL(n))e[t]=new TN(HL(n));else throw Error(`Invalid state field "${t}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let i;if(QL.isInstance(r)||JL.isInstance(r)?(i=VL(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):XL.isInstance(r)?i=r.schema?VL(r.schema):void 0:zL(r)&&(i=VL(r)),i){e[n]=i;let a=!1;a=QL.isInstance(r)||JL.isInstance(r)?HL(r.valueSchema)!==void 0:XL.isInstance(r)?r.schema?HL(r.schema)!==void 0:!1:HL(r)!==void 0,a||t.push(n)}}return{type:`object`,properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;QL.isInstance(n)||JL.isInstance(n)?(r=VL(n.inputSchema),n.jsonSchemaExtra&&(r={...r??{},...n.jsonSchemaExtra})):XL.isInstance(n)?r=n.schema?VL(n.schema):void 0:zL(n)&&(r=VL(n)),r&&(e[t]=r)}return{type:`object`,properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=this.fields[n];if(e===void 0){t[n]=r;continue}let i;if(QL.isInstance(e)||JL.isInstance(e)){let[a,o]=$S(r);if(a){i=e.valueSchema;let r=await i[`~standard`].validate(o);if(r.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(r.issues)}`);t[n]={[QS]:r.value};continue}i=e.inputSchema}else XL.isInstance(e)?i=e.schema:zL(e)&&(i=e);if(i){let e=await i[`~standard`].validate(r);if(e.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(e.issues)}`);t[n]=e.value}else t[n]=r}return t}static isInstance(e){return typeof e==`object`&&!!e&&$L in e&&e[$L]===!0}};function tR(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(En),a=r.map(En);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=yr(),e.lc_kwargs.id=e.id);let o;for(let e=0;e<a.length;e+=1){let t=a[e];(t.id===null||t.id===void 0)&&(t.id=yr(),t.lc_kwargs.id=t.id),gn.isInstance(t)&&t.id===`__remove_all__`&&(o=e)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((e,t)=>[e.id,t])),l=new Set;for(let e of a){let t=c.get(e.id);if(t!==void 0)gn.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(gn.isInstance(e))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);c.set(e.id,s.length),s.push(e)}}return s.filter(e=>!l.has(e.id))}function nR(e,t){let n=[];for(let e of t)Array.isArray(e)?n.push(...e):n.push(e);let r=e.length>0&&rt.isInstance(e[0])?e:e.map(En),i=n.map(En),a=new Map;for(let e=0;e<r.length;e+=1){let t=r[e].id;t!=null&&a.set(t,e)}let o=[...r];for(let e of i){let t=e.id;gn.isInstance(e)&&t===`__remove_all__`?(o.length=0,a.clear()):t==null?o.push(e):gn.isInstance(e)?a.has(t)&&(o[a.get(t)]=null,a.delete(t)):a.has(t)?o[a.get(t)]=e:(a.set(t,o.length),o.push(e))}return o.filter(e=>e!==null)}var rR=dj().default(()=>[]),iR=dj();new JL(rR,{inputSchema:iR,reducer:tR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}}),new QL(rR,{inputSchema:iR,reducer:nR,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}});var aR=new class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=v_(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new ON(n.reducer.fn,n.default):t[e]=new TN(n?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,e])=>e===!0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`|`),r=this._extensionCache.get(n)??new Map;if(r.has(e))return r.get(e);let i=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let n=Object.entries(v_(e)).map(([e,n])=>{let r=this.get(n),i=t.withReducerSchema?r?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&r?.jsonSchemaExtra){let e=l_(i)??l_(n),t=JSON.stringify({...r.jsonSchemaExtra,description:e});i=i.describe(`lg:${t}`)}return[e,i]});i=y_(e,Object.fromEntries(n)),$g(i)&&(i._def.unknownKeys=`strip`)}return t.asPartial&&(i=b_(i)),r.set(e,i),this._extensionCache.set(n,r),i}};function oR(e){return e!=null&&!!(eR.isInstance(e)||__(e)||typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(e=>typeof e==`function`||gN(e)))}function sR(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&oR(t.state),r=`stateSchema`in t&&oR(t.stateSchema),i=`input`in t&&oR(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!oR(t.input)||`output`in t&&t.output!=null&&!oR(t.output))}var cR=`__root__`,lR=`__default_error_handler__`,uR=Symbol.for(`langgraph.state.partial`),dR=class extends jL{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=aR;_configSchema;_configRuntimeSchema;_interrupt;_writer;_nodeDefaults={};constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new wC;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(eR.isInstance(r)||__(r))&&(this._schemaRuntimeDefinition=r),n.input&&(eR.isInstance(n.input)||__(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=uR,n.output&&(eR.isInstance(n.output)||__(n.output))?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):i,o=n.output?this._getChannelsFromSchema(n.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&__(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.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=cS(e.timeout)),e.errorHandler!==void 0&&(this._nodeDefaults.errorHandler=e.errorHandler),this}_createDefaultErrorHandlerSpec(){let e=this._nodeDefaults.errorHandler;if(e!==void 0)return{runnable:new WN({func:(t,n)=>{let r=n?.configurable?.[jS];return e(t,r,n)},name:lR,trace:!1}),metadata:void 0,input:this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0}}_normalizeToStateGraphInit(e,t){if(sR(e)){if(__(t)||kN.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(oR(e)){if(__(t)||kN.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(mR(e))return{state:fR(e.channels)};throw new wC}_getChannelsFromSchema(e){if(eR.isInstance(e))return e.getChannels();if(__(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 wC(`Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.`)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(e=>[e,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let e;if(e=typeof n==`function`?n():n,this.channels[t]!==void 0){if(!this.channels[t].equals(e)&&e.lc_graph_name!==`LastValue`)throw Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([e,t])=>[e,t]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){if(e in this.channels)throw Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`||e===`__start__`)throw Error(`Node \`${e}\` is reserved.`);let n=this._schemaDefinition;r?.input!==void 0&&(n=this._getChannelsFromSchema(r.input)),this._addSchema(n);let i;i=Cx.isRunnable(t)?t:typeof t==`function`?new WN({func:t,name:e,trace:!1}):Px(t);let a=r?.cachePolicy,o;a!==void 0&&(o=typeof a==`boolean`?a?{}:!1:a);let s;if(r?.errorHandler!==void 0){if(s=`__error_handler__${e}`,s in this.nodes)throw Error(`Cannot add error handler to node \`${e}\`: the reserved name \`${s}\` 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).`);let t=r.errorHandler,i={runnable:new WN({func:(e,n)=>{let r=n?.configurable?.[jS];return t(e,r,n)},name:s,trace:!1}),metadata:void 0,input:n??this._schemaDefinition,retryPolicy:void 0,cachePolicy:void 0,isErrorHandler:!0};this.nodes[s]=i}let c={runnable:i,retryPolicy:r?.retryPolicy,cachePolicy:o,timeout:cS(r?.timeout),metadata:r?.metadata,input:n??this._schemaDefinition,subgraphs:fP(i)?[i]:r?.subgraphs,ends:r?.ends,defer:r?.defer,errorHandlerNode:s};this.nodes[e]=c}return this}addEdge(e,t){if(typeof e==`string`)return super.addEdge(e,t);this.compiled&&console.warn(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`);for(let t of e){if(t===`__end__`)throw Error(`END cannot be a start node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`)}if(t===`__end__`)throw Error(`END cannot be an end node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw Error(`Sequence requires at least one node.`);let n;for(let[e,r,i]of t){if(e in this.nodes)throw Error(`Node names must be unique: node with the name "${e}" already exists.`);let t=e;this.addNode(e,r,i),n!=null&&this.addEdge(n,t),n=t}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s}={}){let c=this._createDefaultErrorHandlerSpec();if(c!==void 0){if(lR in this.nodes)throw Error(`Cannot apply a default error handler: the reserved node name \`${lR}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`);this.nodes[lR]=c}try{return this._compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c===void 0?void 0:lR})}finally{c!==void 0&&delete this.nodes[lR]}}_compileResolved({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o,transformers:s,defaultErrorHandlerNode:c}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let l=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),u=l.length===1&&l[0]===cR?cR:l,d=Object.keys(this.channels),f=d.length===1&&d[0]===cR?cR:d,p=this._interrupt,m=new pR({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[lS]:new mP},inputChannels:lS,outputChannels:u,streamChannels:f,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:p,streamTransformers:s});m.attachNode(lS);let h=this._nodeDefaults,g=h.retryPolicy!==void 0||h.cachePolicy!==void 0||h.timeout!==void 0||c!==void 0;for(let[e,t]of Object.entries(this.nodes)){let n=t.isErrorHandler===!0,r=g?{...t,retryPolicy:t.retryPolicy??h.retryPolicy,cachePolicy:n||t.cachePolicy===!1?void 0:t.cachePolicy??h.cachePolicy,timeout:t.timeout??h.timeout,errorHandlerNode:!n&&c!==void 0&&t.errorHandlerNode===void 0?c:t.errorHandlerNode}:t;m.attachNode(e,r)}m.attachBranch(lS,VS,gR(),{withReader:!1});for(let[e]of Object.entries(this.nodes))m.attachBranch(e,VS,gR(),{withReader:!1});for(let[e,t]of this.edges)m.attachEdge(e,t);for(let[e,t]of this.waitingEdges)m.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))m.attachBranch(e,n,r);return m.validate()}};function fR(e){let t={};for(let[n,r]of Object.entries(e))t[n]=jN(r);return t}var pR=class extends ML{description;_metaRegistry=aR;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;n=e===`__start__`?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([e])=>e):Object.keys(this.builder.channels);function r(e){if(rC(e))return e.graph===nC.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>rC(e))){let t=[];for(let n of e)if(rC(n)){if(n.graph===nC.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([cR,n]);return t}else if(e!=null)return[[cR,e]];return null}let i=e,a=async e=>{if(e==null||e.length===0)return e;let t=this.builder._schemaRuntimeDefinition;if(eR.isInstance(t)){let n=new Set(t.getChannelKeys());return Promise.all(e.map(async([e,r])=>{if(!n.has(e))return[e,r];let i=await t.validateInput({[e]:r});return[e,Object.prototype.hasOwnProperty.call(i,e)?i[e]:r]}))}if(__(t)){let n=new Set(Object.keys(v_(t)));if(e.filter(([e])=>n.has(e)).length===0)return e;let r=b_(this._metaRegistry.getExtendedChannelSchemas(t,{withReducerSchema:!0})),i=b_(t);return e.map(([e,t])=>{if(!n.has(e))return[e,t];let[a,o]=$S(t);if(a){let n=c_(i,{[e]:o});return[e,Object.prototype.hasOwnProperty.call(n,e)?{[QS]:n[e]}:t]}let s=c_(r,{[e]:t});return[e,Object.prototype.hasOwnProperty.call(s,e)?s[e]:t]})}return e};async function o(e){if(!e)return null;if(rC(e))return e.graph===nC.PARENT?null:a(e._updateAsTuples().filter(([e])=>n.includes(e)));if(Array.isArray(e)&&e.length>0&&e.some(rC)){let t=[];for(let r of e)if(rC(r)){if(r.graph===nC.PARENT)continue;t.push(...r._updateAsTuples().filter(([e])=>n.includes(e)))}else{let e=await o(r);e&&t.push(...e??[])}return a(t)}else if(typeof e==`object`&&!Array.isArray(e))return a(Object.entries(e).filter(([e])=>n.includes(e)));else{let t=Array.isArray(e)?`array`:typeof e;throw new SC(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${t}`,{lc_error_code:`INVALID_GRAPH_NODE_RETURN_VALUE`})}}let s=[{value:XN,mapper:new WN({func:n.length&&n[0]===cR?r:o,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new iP({tags:[BS],triggers:[lS],channels:[lS],writers:[new $N(s,[BS])]});else{let n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map(e=>[e,e])),i=Object.keys(r).length===1&&cR in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new EN:new mP(!1);let o=t?.cachePolicy,c=o===!1?void 0:o;this.nodes[e]=new iP({triggers:[a],channels:i?Object.keys(r):r,writers:[new $N(s,[BS])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter(([e])=>e in r)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:c,timeout:t?.timeout,subgraphs:t?.subgraphs,ends:t?.ends,isErrorHandler:t?.isErrorHandler,errorHandlerNode:t?.errorHandlerNode})}}attachEdge(e,t){if(t!==`__end__`){if(typeof e==`string`)this.nodes[e].writers.push(new $N([{channel:`branch:to:${t}`,value:null}],[BS]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new RL(new Set(e)):new LL(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new $N([{channel:n,value:t}],[BS]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==uS);if(!r.length)return;let i=r.map(t=>ZS(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await $N.doWrite({...n,tags:(n.tags??[]).concat([BS])},i)},r.withReader?e=>nP.doRead(e,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(eR.isInstance(t)){if(rC(e)){let n=e;return e.update&&(n.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),n}return await t.validateInput(e)}if(t===uR&&eR.isInstance(n)){if(rC(e)){let t=e;return e.update&&(t.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),t}return await n.validateInput(e)}let r=(()=>{let e=e=>{if(e!=null)return this._metaRegistry.getExtendedChannelSchemas(e,{withReducerSchema:!0})};if(__(t))return e(t);if(t===uR)return __(n)?b_(e(n)):void 0})();if(rC(e)){let t=e;if(e.update&&r!=null){let n=Array.isArray(e.update)?Object.fromEntries(e.update):e.update,i=c_(r,n);t.update=Object.fromEntries(Object.keys(n).map(e=>[e,i[e]]))}return t}return r==null?e:c_(r,e)}isInterrupted(e){return tC(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return __(t)&&c_(t,e),e}};function mR(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function hR(e){if(ZS(e))return[e];let t=[];rC(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(rC));let n=[];for(let e of t){if(e.graph===nC.PARENT)throw new hC(e);ZS(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function gR(){return new AL({path:new WN({func:hR,tags:[BS],trace:!1,recurse:!1,name:`<control_branch>`})})}var _R=e=>Array.isArray(e)&&e.every(_t),vR=e=>typeof e==`object`&&!!e&&`messages`in e&&_R(e.messages),yR=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e,bR=class extends WN{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:n,tags:r,handleToolErrors:i}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.tools=e,this.handleToolErrors=i??this.handleToolErrors}async runTool(e,t,n){let r=this.tools.find(t=>t.name===e.name);try{if(r===void 0)throw Error(`Tool "${e.name}" not found.`);let i={...e,type:`tool_call`},a={...t,state:n,toolCallId:e.id??``,config:t,context:t.context,store:t.store??null,writer:t.writer??t.configurable?.writer??null},o=await r.invoke(i,a);return _t(o)&&o.getType()===`tool`||rC(o)?o:new xt({status:`success`,name:r.name,content:typeof o==`string`?o:JSON.stringify(o),tool_call_id:e.id})}catch(t){if(!this.handleToolErrors||vC(t))throw t;return new xt({status:`error`,content:`Error: ${t.message}\n Please fix your mistakes.`,name:e.name,tool_call_id:e.id??``})}}async run(e,t){let n;if(yR(e)){let{lg_tool_call:r,...i}=e;n=[await this.runTool(r,t,i)]}else{let r;if(_R(e))r=e;else if(vR(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(en(t)){a=t;break}}if(a==null||!en(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(n=>this.runTool(n,t,e))??[])}if(!n.some(rC))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)rC(t)?t.graph===nC.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>ZS(e))?i?i.goto.push(...t.goto):i=new nC({graph:nC.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}},xR=/<name>(.*?)<\/name>/s,SR=/<content>(.*?)<\/content>/s;function CR(e){if(!(_t(e)&&(en(e)||vt(e)&&tn(e)))||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new $t({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new $t({...e.lc_kwargs,content:n,name:void 0})}function wR(e){if(!en(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(xR),r=e.text.match(SR);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(xR),r=e.text.match(SR);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(xR),a=r.match(SR);if(!i||!a)return e;n=i[1],t=a[1]}return new $t({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function TR(e,t){let n,r;if(t===`inline`)n=CR,r=wR;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return Dx.from([jx.from(i),e,jx.from(r)])}function ER(e){if(typeof e==`string`||_t(e)&&e._getType()===`system`)return e;if(typeof e==`function`)return async t=>e(t.messages);if(Cx.isRunnable(e))return jx.from(e=>e.messages).pipe(e);throw Error(`Unexpected type for messageModifier: ${typeof e}`)}var DR=`prompt`;function OR(e){let t;if(e==null)t=jx.from(e=>e.messages).withConfig({runName:DR});else if(typeof e==`string`){let n=new _n(e);t=jx.from(e=>[n,...e.messages??[]]).withConfig({runName:DR})}else if(_t(e)&&e._getType()===`system`)t=jx.from(t=>[e,...t.messages]).withConfig({runName:DR});else if(typeof e==`function`)t=jx.from(e).withConfig({runName:DR});else if(Cx.isRunnable(e))t=e;else throw Error(`Got unexpected type for 'prompt': ${typeof e}`);return t}function kR(e){return Cx.isRunnable(e)}function AR(e,t,n){if([e,t,n].filter(e=>e!=null).length>1)throw Error(`Expected only one of prompt, stateModifier, or messageModifier, got multiple values`);let r=e;return t==null?n!=null&&(r=ER(n)):r=t,OR(r)}function jR(e){return`invoke`in e&&typeof e.invoke==`function`&&`_modelType`in e}function MR(e){return`_queuedMethodOperations`in e&&`_model`in e&&typeof e._model==`function`}function NR(e){return jR(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}async function PR(e,t){let n=e;if(Dx.isRunnableSequence(n)&&(n=n.steps.find(e=>wx.isRunnableBinding(e)||jR(e)||MR(e))||n),MR(n)&&(n=await n._model()),!wx.isRunnableBinding(n))return!0;let r=n.kwargs!=null&&typeof n.kwargs==`object`&&`tools`in n.kwargs&&Array.isArray(n.kwargs.tools)?n.kwargs.tools??null:n.config!=null&&typeof n.config==`object`&&`tools`in n.config&&Array.isArray(n.config.tools)?n.config.tools??null:null;if(r!=null&&r.length===1&&`functionDeclarations`in r[0]&&(r=r[0].functionDeclarations),r==null)return!0;if(t.length!==r.length)throw Error(`Number of tools in the model.bindTools() and tools passed to createReactAgent must match`);let i=new Set(t.flatMap(e=>kR(e)?e.name:[])),a=new Set;for(let e of r){let t;if(`type`in e&&e.type===`function`)t=e.function.name;else if(`name`in e)t=e.name;else if(`toolSpec`in e&&`name`in e.toolSpec)t=e.toolSpec.name;else continue;t&&a.add(t)}let o=[...i].filter(e=>!a.has(e));if(o.length>0)throw Error(`Missing tools '${o}' in the model.bindTools().Tools in the model.bindTools() must match the tools passed to createReactAgent.`);return!1}var FR=(e,t)=>{if(NR(e))return e.bindTools(t);if(wx.isRunnableBinding(e)&&NR(e.bound)){let n=e.bound.bindTools(t);return wx.isRunnableBinding(n)?new wx({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new wx({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};async function IR(e,t){let n=FR(e,t);if(n)return n;if(MR(e)){let n=FR(await e._model(),t);if(n)return n}if(Dx.isRunnableSequence(e)){let n=e.steps.findIndex(e=>wx.isRunnableBinding(e)||jR(e)||MR(e));if(n>=0){let r=FR(e.steps[n],t);if(r){let t=e.steps.slice();return t.splice(n,1,r),Dx.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}async function LR(e){let t=e;if(Dx.isRunnableSequence(t)&&(t=t.steps.find(e=>wx.isRunnableBinding(e)||jR(e)||MR(e))||t),MR(t)&&(t=await t._model()),wx.isRunnableBinding(t)&&(t=t.bound),!jR(t))throw Error(`Expected \`llm\` to be a ChatModel or RunnableBinding (e.g. llm.bind_tools(...)) with invoke() and generate() methods, got ${t.constructor.name}`);return t}var RR=()=>AN.Root({messages:AN({reducer:tR,default:()=>[]}),structuredResponse:AN}),zR=AN.Root({llmInputMessages:AN({reducer:(e,t)=>tR([],t),default:()=>[]})});function BR(e){let{llm:t,tools:n,messageModifier:r,stateModifier:i,prompt:a,stateSchema:o,contextSchema:s,checkpointSaver:c,checkpointer:l,interruptBefore:u,interruptAfter:d,store:f,responseFormat:p,preModelHook:m,postModelHook:h,name:g,description:_,version:v=`v1`,includeAgentName:y}=e,b,x;Array.isArray(n)?(b=n,x=new bR(b.filter(kR))):(b=n.tools,x=n);let ee=null,te=async e=>{if(ee)return ee;let t;t=await PR(e,b)?await IR(e,b):e;let n=AR(a,i,r),o=y===`inline`?TR(t,y):t;return ee=n.pipe(o),ee},S=async(e,t,n)=>{let o=await e(t,n);return AR(a,i,r).pipe(y===`inline`?TR(o,y):o)},ne=new Set(b.filter(kR).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name));function re(e){let{messages:t,llmInputMessages:n,...r}=e;return n!=null&&n.length>0?{messages:n,...r}:{messages:t,...r}}let ie=async(e,n)=>{if(p==null)throw Error(`Attempted to generate structured output with no passed response schema. Please contact us for help.`);let r=[...e.messages],i,a=typeof t==`function`?await t(e,n):await LR(t);if(!jR(a))throw Error(`Expected \`llm\` to be a ChatModel with .withStructuredOutput() method, got ${a.constructor.name}`);if(typeof p==`object`&&`schema`in p){let{prompt:e,schema:t,...n}=p;i=a.withStructuredOutput(t,n),e!=null&&r.unshift(new _n({content:e}))}else i=a.withStructuredOutput(p);let o=await i.invoke(r,n);if(o==null)throw Error("Failed to parse structured response against the provided `responseFormat` schema: the structured-output parser returned null/undefined, which usually means the model output did not satisfy the schema.");return{structuredResponse:o}},ae=async(e,n)=>{let r=await(typeof t==`function`?await S(t,e,n):await te(t)).invoke(re(e),n);return r.name=g,r.lc_kwargs.name=g,{messages:[r]}},oe=new dR(o??RR(),s).addNode(`tools`,x);if(!(`messages`in oe._schemaDefinition))throw Error("Missing required `messages` key in state schema.");let se=oe,ce=e=>Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null)),C=`agent`,le;return m==null?C=`agent`:(se.addNode(`pre_model_hook`,m).addEdge(`pre_model_hook`,`agent`),C=`pre_model_hook`,le=AN.Root({...oe._schemaDefinition,...zR.spec})),se.addNode(`agent`,ae,{input:le}).addEdge(lS,C),h!=null&&se.addNode(`post_model_hook`,h).addEdge(`agent`,`post_model_hook`).addConditionalEdges(`post_model_hook`,e=>{let{messages:t}=e,n=new Set(t.filter(wt).map(e=>e.tool_call_id)),r;for(let e=t.length-1;e>=0;--e){let n=t[e];if(en(n)){r=n;break}}let i=r?.tool_calls?.filter(e=>e.id==null||!n.has(e.id))??[],a=t[t.length-1];return i.length>0?v===`v2`?i.map(t=>new XS(`tools`,{...e,lg_tool_call:t})):`tools`:a&&wt(a)?C:p==null?uS:`generate_structured_response`},ce({tools:`tools`,[C]:C,generate_structured_response:p==null?null:`generate_structured_response`,[uS]:p==null?uS:null})),p!==void 0&&oe.addNode(`generate_structured_response`,ie).addEdge(`generate_structured_response`,uS),h??se.addConditionalEdges(`agent`,e=>{let{messages:t}=e,n=t[t.length-1];return!en(n)||!n.tool_calls?.length?p==null?uS:`generate_structured_response`:v===`v2`?n.tool_calls.map(t=>new XS(`tools`,{...e,lg_tool_call:t})):`tools`},ce({tools:`tools`,generate_structured_response:p==null?null:`generate_structured_response`,[uS]:p==null?uS:null})),ne.size>0?se.addConditionalEdges(`tools`,e=>{let t=e;for(let e=t.messages.length-1;e>=0;--e){let n=t.messages[e];if(!wt(n))break;if(n.name!==void 0&&ne.has(n.name))return uS}return C},ce({[C]:C,[uS]:uS})):se.addEdge(`tools`,C),se.compile({checkpointer:l??c,interruptBefore:u,interruptAfter:d,store:f,name:g,description:_})}function VR(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function H(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function U(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var HR=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return HR=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function UR(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var WR=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},W=class extends Error{},GR=class e extends W{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new qR({message:r,cause:WR(n)});let a=n?.error;return t===400?new YR(t,a,r,i):t===401?new XR(t,a,r,i):t===403?new ZR(t,a,r,i):t===404?new QR(t,a,r,i):t===409?new $R(t,a,r,i):t===422?new ez(t,a,r,i):t===429?new tz(t,a,r,i):t>=500?new nz(t,a,r,i):new e(t,a,r,i)}},KR=class extends GR{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},qR=class extends GR{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},JR=class extends qR{constructor({message:e}={}){super({message:e??`Request timed out.`})}},YR=class extends GR{},XR=class extends GR{},ZR=class extends GR{},QR=class extends GR{},$R=class extends GR{},ez=class extends GR{},tz=class extends GR{},nz=class extends GR{},rz=class extends W{constructor(){super(`Could not parse response content as the length limit was reached`)}},iz=class extends W{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},az=class extends Error{constructor(e){super(e)}},oz=class extends GR{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},sz=class extends W{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},cz=/^[a-z][a-z0-9+.-]*:/i,lz=e=>cz.test(e),uz=e=>(uz=Array.isArray,uz(e)),dz=uz;function fz(e){return typeof e==`object`?e??{}:{}}function pz(e){if(!e)return!0;for(let t in e)return!1;return!0}function mz(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function hz(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var gz=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new W(`${e} must be an integer`);if(t<0)throw new W(`${e} must be a positive integer`);return t},_z=e=>{try{return JSON.parse(e)}catch{return}},vz=e=>new Promise(t=>setTimeout(t,e)),yz=`6.45.0`,bz=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function xz(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var Sz=()=>{let e=xz();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":Tz(Deno.build.os),"X-Stainless-Arch":wz(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":Tz(globalThis.process.platform??`unknown`),"X-Stainless-Arch":wz(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Cz();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":yz,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Cz(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var wz=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Tz=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Ez,Dz=()=>Ez??=Sz();function Oz(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function kz(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Az(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return kz({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function jz(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Mz(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Nz=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Pz=`RFC3986`,Fz=e=>String(e),Iz={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Fz},Lz=(e,t)=>(Lz=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Lz(e,t)),Rz=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),zz=1024,Bz=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=zz){let t=a.length>=zz?a.slice(e,e+zz):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=Rz[r];continue}if(r<2048){n[n.length]=Rz[192|r>>6]+Rz[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=Rz[224|r>>12]+Rz[128|r>>6&63]+Rz[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=Rz[240|r>>18]+Rz[128|r>>12&63]+Rz[128|r>>6&63]+Rz[128|r&63]}o+=n.join(``)}return o};function Vz(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Hz(e,t){if(uz(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Uz={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Wz=function(e,t){Array.prototype.push.apply(e,uz(t)?t:[t])},Gz,Kz={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Bz,encodeValuesOnly:!1,format:Pz,formatter:Fz,indices:!1,serializeDate(e){return(Gz??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function qz(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Jz={};function Yz(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(Jz))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(Jz)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&uz(v)&&(v=Hz(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,Kz.encoder,g,`key`,p):t;v=``}if(qz(v)||Vz(v)){if(c){let e=h?t:c(t,Kz.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,Kz.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&uz(v))h&&c&&(v=Hz(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(uz(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let S=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&uz(v)&&v.length===1?S+`[]`:S;if(i&&uz(v)&&v.length===0)return ne+`[]`;for(let t=0;t<te.length;++t){let y=te[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let S=d&&s?y.replace(/\./g,`%2E`):y,re=uz(v)?typeof n==`function`?n(ne,S):ne:ne+(d?`.`+S:`[`+S+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Jz,_),Wz(ee,Yz(x,re,n,r,i,a,o,s,n===`comma`&&h&&uz(v)?null:c,l,u,d,f,p,m,h,g,ie))}return ee}function Xz(e=Kz){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||Kz.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Pz;if(e.format!==void 0){if(!Lz(Iz,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Iz[n],i=Kz.filter;(typeof e.filter==`function`||uz(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Uz?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:Kz.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:Kz.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:Kz.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:Kz.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:Kz.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?Kz.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:Kz.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:Kz.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:Kz.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:Kz.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:Kz.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:Kz.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:Kz.strictNullHandling}}function Zz(e,t={}){let n=e,r=Xz(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):uz(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Uz[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||Wz(o,Yz(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Qz(e){return Zz(e,{arrayFormat:`brackets`})}function $z(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var eB;function tB(e){let t;return(eB??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var nB;function rB(e){let t;return(nB??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var iB,aB,oB=class{constructor(){iB.set(this,void 0),aB.set(this,void 0),H(this,iB,new Uint8Array,`f`),H(this,aB,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?tB(e):e;H(this,iB,$z([U(this,iB,`f`),t]),`f`);let n=[],r;for(;(r=sB(U(this,iB,`f`),U(this,aB,`f`)))!=null;){if(r.carriage&&U(this,aB,`f`)==null){H(this,aB,r.index,`f`);continue}if(U(this,aB,`f`)!=null&&(r.index!==U(this,aB,`f`)+1||r.carriage)){n.push(rB(U(this,iB,`f`).subarray(0,U(this,aB,`f`)-1))),H(this,iB,U(this,iB,`f`).subarray(U(this,aB,`f`)),`f`),H(this,aB,null,`f`);continue}let e=U(this,aB,`f`)===null?r.preceding:r.preceding-1,t=rB(U(this,iB,`f`).subarray(0,e));n.push(t),H(this,iB,U(this,iB,`f`).subarray(r.index),`f`),H(this,aB,null,`f`)}return n}flush(){return U(this,iB,`f`).length?this.decode(`
|
|
190
190
|
`):[]}};iB=new WeakMap,aB=new WeakMap,oB.NEWLINE_CHARS=new Set([`
|
|
191
191
|
`,`\r`]),oB.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function sB(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function cB(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var lB={off:0,error:200,warn:300,info:400,debug:500},uB=(e,t,n)=>{if(e){if(mz(lB,e))return e;hB(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(lB))}`)}};function dB(){}function fB(e,t,n){return!t||lB[e]>lB[n]?dB:t[e].bind(t)}var pB={error:dB,warn:dB,info:dB,debug:dB},mB=new WeakMap;function hB(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return pB;let r=mB.get(t);if(r&&r[0]===n)return r[1];let i={error:fB(`error`,t,n),warn:fB(`warn`,t,n),info:fB(`info`,t,n),debug:fB(`debug`,t,n)};return mB.set(t,[n,i]),i}var gB=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),_B,vB=class e{constructor(e,t,n){this.iterator=e,_B.set(this,void 0),this.controller=t,H(this,_B,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?hB(r):console;async function*s(){if(a)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of yB(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new GR(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new GR(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(UR(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new oB,n=jz(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(UR(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(_B=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,U(this,_B,`f`)),new e(()=>i(n),this.controller,U(this,_B,`f`))]}toReadableStream(){let e=this,t;return kz({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=tB(JSON.stringify(n)+`
|
|
192
192
|
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*yB(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new W(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new W(`Attempted to iterate over a response with no body`);let n=new xB,r=new oB,i=jz(e.body);for await(let e of bB(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*bB(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?tB(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=cB(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var xB=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
193
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=SB(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function SB(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function CB(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return hB(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):vB.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:wB(await n.json(),n):await n.text()})();return hB(e).debug(`[${r}] response parsed`,gB({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function wB(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var TB,EB=class e extends Promise{constructor(e,t,n=CB){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,TB.set(this,void 0),H(this,TB,e,`f`)}_thenUnwrap(t){return new e(U(this,TB,`f`),this.responsePromise,async(e,n)=>wB(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(U(this,TB,`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)}};TB=new WeakMap;var DB,OB=class{constructor(e,t,n,r){DB.set(this,void 0),H(this,DB,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,DB,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(DB=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},kB=class extends EB{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await CB(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},AB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},jB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...fz(this.options.query),after:t}}:null}},MB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...fz(this.options.query),after:e}}:null}},NB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...fz(this.options.query),after:e}}:null}},PB={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},FB=`urn:ietf:params:oauth:grant-type:token-exchange`,IB=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??Oz()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:FB,subject_token:await this.config.provider.getToken(),subject_token_type:PB[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new oz(t.status,n,t.headers):GR.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json();if(typeof n!=`object`||!n||!(`access_token`in n)||typeof n.access_token!=`string`||n.access_token.trim().length===0)throw new W(`Token exchange response missing 'access_token' field`);let r=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:r,expiresAt:a},r}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},LB=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function RB(e,t,n){return LB(),new File(e,t??`unknown_file`,n)}function zB(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var BB=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,VB=async(e,t)=>JB(e.body)?{...e,body:await GB(e.body,t)}:e,HB=async(e,t)=>({...e,body:await GB(e.body,t)}),UB=new WeakMap;function WB(e){let t=typeof e==`function`?e:e.fetch,n=UB.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return UB.set(t,r),r}var GB=async(e,t)=>{if(!await WB(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>YB(n,e,t))),n},KB=e=>e instanceof Blob&&`name`in e,qB=e=>typeof e==`object`&&!!e&&(e instanceof Response||BB(e)||KB(e)),JB=e=>{if(qB(e))return!0;if(Array.isArray(e))return e.some(JB);if(e&&typeof e==`object`){for(let t in e)if(JB(e[t]))return!0}return!1},YB=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,RB([await n.blob()],zB(n)));else if(BB(n))e.append(t,RB([await new Response(Az(n)).blob()],zB(n)));else if(KB(n))e.append(t,n,zB(n));else if(Array.isArray(n))await Promise.all(n.map(n=>YB(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>YB(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},XB=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,ZB=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&XB(e),QB=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function $B(e,t,n){if(LB(),e=await e,ZB(e))return e instanceof File?e:RB([await e.arrayBuffer()],e.name);if(QB(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),RB(await eV(r),t,n)}let r=await eV(e);if(t||=zB(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return RB(r,t,n)}async function eV(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(XB(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(BB(e))for await(let n of e)t.push(...await eV(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${tV(e)}`)}return t}function tV(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var G=class{constructor(e){this._client=e}};function nV(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rV=Object.freeze(Object.create(null)),K=((e=nV)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??rV)??rV)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new W(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
194
|
-
`)}\n${a}\n${t}`)}return a})(nV),iV=class extends G{list(e,t={},n){return this._client.getAPIList(K`/chat/completions/${e}/messages`,jB,{query:t,...n,__security:{bearerAuth:!0}})}};function aV(e){return e!==void 0&&`function`in e&&e.function!==void 0}function oV(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function sV(e){return e?.$brand===`auto-parseable-response-format`}function cV(e){return e?.$brand===`auto-parseable-tool`}function lV(e,t){return!t||!mV(t)?{...e,choices:e.choices.map(e=>(hV(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:uV(e,t)}function uV(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new rz;if(e.finish_reason===`content_filter`)throw new iz;return hV(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>fV(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?dV(t,e.message.content):null}}});return{...e,choices:n}}function dV(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function fV(e,t){let n=e.tools?.find(e=>aV(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:cV(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function pV(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>aV(e)&&e.function?.name===t.function.name);return aV(n)&&(cV(n)||n?.function.strict||!1)}function mV(e){return sV(e.response_format)?!0:e.tools?.some(e=>cV(e)||e.type===`function`&&e.function.strict===!0)??!1}function hV(e){for(let t of e||[])if(t.type!==`function`)throw new W(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function gV(e){for(let t of e??[]){if(t.type!==`function`)throw new W(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new W(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _V=e=>e?.role===`assistant`,vV=e=>e?.role===`tool`,yV,bV,xV,SV,CV,wV,TV,EV,DV,OV,kV,AV,jV,MV,NV,PV=class{constructor(){yV.add(this),this.controller=new AbortController,bV.set(this,void 0),xV.set(this,()=>{}),SV.set(this,()=>{}),CV.set(this,void 0),wV.set(this,()=>{}),TV.set(this,()=>{}),EV.set(this,{}),DV.set(this,[]),OV.set(this,!1),kV.set(this,!1),AV.set(this,!1),jV.set(this,!1),H(this,bV,new Promise((e,t)=>{H(this,xV,e,`f`),H(this,SV,t,`f`)}),`f`),H(this,CV,new Promise((e,t)=>{H(this,wV,e,`f`),H(this,TV,t,`f`)}),`f`),U(this,bV,`f`).catch(()=>{}),U(this,CV,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},U(this,yV,`m`,NV).bind(this))},0)}_connected(){this.ended||(U(this,xV,`f`).call(this),this._emit(`connect`))}get ended(){return U(this,OV,`f`)}get errored(){return U(this,kV,`f`)}get aborted(){return U(this,AV,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),U(this,DV,`f`).push({signal:e,listener:t})}on(e,t){return(U(this,EV,`f`)[e]||(U(this,EV,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=U(this,EV,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(U(this,EV,`f`)[e]||(U(this,EV,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{H(this,jV,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){H(this,jV,!0,`f`),await U(this,CV,`f`)}_emit(e,...t){if(U(this,OV,`f`))return;e===`end`&&(U(this,yV,`m`,MV).call(this),H(this,OV,!0,`f`),U(this,wV,`f`).call(this));let n=U(this,EV,`f`)[e];if(n&&(U(this,EV,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!U(this,jV,`f`)&&!n?.length&&Promise.reject(e),U(this,SV,`f`).call(this,e),U(this,TV,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!U(this,jV,`f`)&&!n?.length&&Promise.reject(e),U(this,SV,`f`).call(this,e),U(this,TV,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};bV=new WeakMap,xV=new WeakMap,SV=new WeakMap,CV=new WeakMap,wV=new WeakMap,TV=new WeakMap,EV=new WeakMap,DV=new WeakMap,OV=new WeakMap,kV=new WeakMap,AV=new WeakMap,jV=new WeakMap,yV=new WeakSet,MV=function(){for(let{signal:e,listener:t}of U(this,DV,`f`).splice(0))e.removeEventListener(`abort`,t)},NV=function(e){if(H(this,kV,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new KR),e instanceof KR)return H(this,AV,!0,`f`),this._emit(`abort`,e);if(e instanceof W)return this._emit(`error`,e);if(e instanceof Error){let t=new W(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new W(String(e)))};function FV(e){return typeof e.parse==`function`}var IV,LV,RV,zV,BV,VV,HV,UV,WV=10,GV=class extends PV{constructor(){super(...arguments),IV.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),vV(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(_V(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new W(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),U(this,IV,`m`,LV).call(this)}async finalMessage(){return await this.done(),U(this,IV,`m`,RV).call(this)}async finalFunctionToolCall(){return await this.done(),U(this,IV,`m`,zV).call(this)}async finalFunctionToolCallResult(){return await this.done(),U(this,IV,`m`,BV).call(this)}async totalUsage(){return await this.done(),U(this,IV,`m`,VV).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=U(this,IV,`m`,RV).call(this);t&&this._emit(`finalMessage`,t);let n=U(this,IV,`m`,LV).call(this);n&&this._emit(`finalContent`,n);let r=U(this,IV,`m`,zV).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=U(this,IV,`m`,BV).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,U(this,IV,`m`,VV).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),U(this,IV,`m`,HV).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(uV(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,...s}=t,c=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:l=WV,afterCompletion:u}=r||{},d=t.tools.map(e=>{if(cV(e)){if(!e.$callback)throw new W("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in t?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let m=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o)return{message:{role:i,tool_call_id:t,content:`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`},functionCalled:!1};if(c&&c!==r)return{message:{role:i,tool_call_id:t,content:`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(c)} requested. Please try again`},functionCalled:!1};let s;if(FV(o)){let e;try{e=await o.parse(a)}catch(e){return{message:{role:i,tool_call_id:t,content:e instanceof Error?e.message:String(e)},functionCalled:!1}}s=await o.function(e,n)}else s=await o.function(a,n);return{message:{role:i,tool_call_id:t,content:U(this,IV,`m`,UV).call(this,s)},functionCalled:!0}};for(let i=0;i<l;++i){let i=await this._createChatCompletion(e,{...s,tool_choice:a,tools:p,messages:[...this.messages]},r),o=i.choices[0]?.message;if(!o)throw new W(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await u?.(i,n);return}if(c||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await m(e);if(t.message&&this._addMessage(t.message),c&&t.functionCalled){await u?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(m));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await u?.(i,n)}}};IV=new WeakSet,LV=function(){return U(this,IV,`m`,RV).call(this).content??null},RV=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(_V(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new W(`stream ended without producing a ChatCompletionMessage with role=assistant`)},zV=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(_V(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},BV=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(vV(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},VV=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},HV=function(e){if(e.n!=null&&e.n>1)throw new W(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},UV=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var KV=class e extends GV{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),_V(e)&&e.content&&this._emit(`content`,e.content)}},qV={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},JV=class extends Error{},YV=class extends Error{};function XV(e,t=qV.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return ZV(e.trim(),t)}var ZV=(e,t)=>{let n=e.length,r=0,i=e=>{throw new JV(`${e} at position ${r}`)},a=e=>{throw new YV(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||qV.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||qV.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||qV.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||qV.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||qV.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||qV.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(qV.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&qV.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(qV.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(qV.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(qV.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&qV.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(qV.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(qV.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&qV.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
193
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=SB(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function SB(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function CB(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return hB(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):vB.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:wB(await n.json(),n):await n.text()})();return hB(e).debug(`[${r}] response parsed`,gB({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function wB(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var TB,EB=class e extends Promise{constructor(e,t,n=CB){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,TB.set(this,void 0),H(this,TB,e,`f`)}_thenUnwrap(t){return new e(U(this,TB,`f`),this.responsePromise,async(e,n)=>wB(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(U(this,TB,`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)}};TB=new WeakMap;var DB,OB=class{constructor(e,t,n,r){DB.set(this,void 0),H(this,DB,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,DB,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(DB=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},kB=class extends EB{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await CB(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},AB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},jB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...fz(this.options.query),after:t}}:null}},MB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...fz(this.options.query),after:e}}:null}},NB=class extends OB{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...fz(this.options.query),after:e}}:null}},PB={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},FB=`urn:ietf:params:oauth:grant-type:token-exchange`,IB=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??Oz()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:FB,subject_token:await this.config.provider.getToken(),subject_token_type:PB[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new oz(t.status,n,t.headers):GR.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json();if(typeof n!=`object`||!n||!(`access_token`in n)||typeof n.access_token!=`string`||n.access_token.trim().length===0)throw new W(`Token exchange response missing 'access_token' field`);let r=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:r,expiresAt:a},r}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}},LB=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function RB(e,t,n){return LB(),new File(e,t??`unknown_file`,n)}function zB(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var BB=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,VB=async(e,t)=>JB(e.body)?{...e,body:await GB(e.body,t)}:e,HB=async(e,t)=>({...e,body:await GB(e.body,t)}),UB=new WeakMap;function WB(e){let t=typeof e==`function`?e:e.fetch,n=UB.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return UB.set(t,r),r}var GB=async(e,t)=>{if(!await WB(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>YB(n,e,t))),n},KB=e=>e instanceof Blob&&`name`in e,qB=e=>typeof e==`object`&&!!e&&(e instanceof Response||BB(e)||KB(e)),JB=e=>{if(qB(e))return!0;if(Array.isArray(e))return e.some(JB);if(e&&typeof e==`object`){for(let t in e)if(JB(e[t]))return!0}return!1},YB=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,RB([await n.blob()],zB(n)));else if(BB(n))e.append(t,RB([await new Response(Az(n)).blob()],zB(n)));else if(KB(n))e.append(t,n,zB(n));else if(Array.isArray(n))await Promise.all(n.map(n=>YB(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>YB(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},XB=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,ZB=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&XB(e),QB=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function $B(e,t,n){if(LB(),e=await e,ZB(e))return e instanceof File?e:RB([await e.arrayBuffer()],e.name);if(QB(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),RB(await eV(r),t,n)}let r=await eV(e);if(t||=zB(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return RB(r,t,n)}async function eV(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(XB(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(BB(e))for await(let n of e)t.push(...await eV(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${tV(e)}`)}return t}function tV(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var G=class{constructor(e){this._client=e}};function nV(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rV=Object.freeze(Object.create(null)),K=((e=nV)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??rV)??rV)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new W(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
194
|
+
`)}\n${a}\n${t}`)}return a})(nV),iV=class extends G{list(e,t={},n){return this._client.getAPIList(K`/chat/completions/${e}/messages`,jB,{query:t,...n,__security:{bearerAuth:!0}})}};function aV(e){return e!==void 0&&`function`in e&&e.function!==void 0}function oV(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function sV(e){return e?.$brand===`auto-parseable-response-format`}function cV(e){return e?.$brand===`auto-parseable-tool`}function lV(e,t){return!t||!mV(t)?{...e,choices:e.choices.map(e=>(hV(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:uV(e,t)}function uV(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new rz;if(e.finish_reason===`content_filter`)throw new iz;return hV(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>fV(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?dV(t,e.message.content):null}}});return{...e,choices:n}}function dV(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function fV(e,t){let n=e.tools?.find(e=>aV(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:cV(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function pV(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>aV(e)&&e.function?.name===t.function.name);return aV(n)&&(cV(n)||n?.function.strict||!1)}function mV(e){return sV(e.response_format)?!0:e.tools?.some(e=>cV(e)||e.type===`function`&&e.function.strict===!0)??!1}function hV(e){for(let t of e||[])if(t.type!==`function`)throw new W(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function gV(e){for(let t of e??[]){if(t.type!==`function`)throw new W(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new W(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _V=e=>e?.role===`assistant`,vV=e=>e?.role===`tool`,yV,bV,xV,SV,CV,wV,TV,EV,DV,OV,kV,AV,jV,MV,NV,PV=class{constructor(){yV.add(this),this.controller=new AbortController,bV.set(this,void 0),xV.set(this,()=>{}),SV.set(this,()=>{}),CV.set(this,void 0),wV.set(this,()=>{}),TV.set(this,()=>{}),EV.set(this,{}),DV.set(this,[]),OV.set(this,!1),kV.set(this,!1),AV.set(this,!1),jV.set(this,!1),H(this,bV,new Promise((e,t)=>{H(this,xV,e,`f`),H(this,SV,t,`f`)}),`f`),H(this,CV,new Promise((e,t)=>{H(this,wV,e,`f`),H(this,TV,t,`f`)}),`f`),U(this,bV,`f`).catch(()=>{}),U(this,CV,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},U(this,yV,`m`,NV).bind(this))},0)}_connected(){this.ended||(U(this,xV,`f`).call(this),this._emit(`connect`))}get ended(){return U(this,OV,`f`)}get errored(){return U(this,kV,`f`)}get aborted(){return U(this,AV,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),U(this,DV,`f`).push({signal:e,listener:t})}on(e,t){return(U(this,EV,`f`)[e]||(U(this,EV,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=U(this,EV,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(U(this,EV,`f`)[e]||(U(this,EV,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{H(this,jV,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){H(this,jV,!0,`f`),await U(this,CV,`f`)}_emit(e,...t){if(U(this,OV,`f`))return;e===`end`&&(U(this,yV,`m`,MV).call(this),H(this,OV,!0,`f`),U(this,wV,`f`).call(this));let n=U(this,EV,`f`)[e];if(n&&(U(this,EV,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!U(this,jV,`f`)&&!n?.length&&Promise.reject(e),U(this,SV,`f`).call(this,e),U(this,TV,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!U(this,jV,`f`)&&!n?.length&&Promise.reject(e),U(this,SV,`f`).call(this,e),U(this,TV,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};bV=new WeakMap,xV=new WeakMap,SV=new WeakMap,CV=new WeakMap,wV=new WeakMap,TV=new WeakMap,EV=new WeakMap,DV=new WeakMap,OV=new WeakMap,kV=new WeakMap,AV=new WeakMap,jV=new WeakMap,yV=new WeakSet,MV=function(){for(let{signal:e,listener:t}of U(this,DV,`f`).splice(0))e.removeEventListener(`abort`,t)},NV=function(e){if(H(this,kV,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new KR),e instanceof KR)return H(this,AV,!0,`f`),this._emit(`abort`,e);if(e instanceof W)return this._emit(`error`,e);if(e instanceof Error){let t=new W(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new W(String(e)))};function FV(e){return typeof e.parse==`function`}var IV,LV,RV,zV,BV,VV,HV,UV,WV=10,GV=class extends PV{constructor(){super(...arguments),IV.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),vV(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(_V(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new W(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),U(this,IV,`m`,LV).call(this)}async finalMessage(){return await this.done(),U(this,IV,`m`,RV).call(this)}async finalFunctionToolCall(){return await this.done(),U(this,IV,`m`,zV).call(this)}async finalFunctionToolCallResult(){return await this.done(),U(this,IV,`m`,BV).call(this)}async totalUsage(){return await this.done(),U(this,IV,`m`,VV).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=U(this,IV,`m`,RV).call(this);t&&this._emit(`finalMessage`,t);let n=U(this,IV,`m`,LV).call(this);n&&this._emit(`finalContent`,n);let r=U(this,IV,`m`,zV).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=U(this,IV,`m`,BV).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,U(this,IV,`m`,VV).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),U(this,IV,`m`,HV).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(uV(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,...s}=t,c=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:l=WV,afterCompletion:u}=r||{},d=t.tools.map(e=>{if(cV(e)){if(!e.$callback)throw new W("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in t?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let m=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(c&&c!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(c)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(FV(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n)}else s=await o.function(a,n);let l=U(this,IV,`m`,UV).call(this,s);return{message:{role:i,tool_call_id:t,content:l},functionCalled:!0}};for(let i=0;i<l;++i){let i=await this._createChatCompletion(e,{...s,tool_choice:a,tools:p,messages:[...this.messages]},r),o=i.choices[0]?.message;if(!o)throw new W(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await u?.(i,n);return}if(c||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await m(e);if(t.message&&this._addMessage(t.message),c&&t.functionCalled){await u?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(m));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await u?.(i,n)}}};IV=new WeakSet,LV=function(){return U(this,IV,`m`,RV).call(this).content??null},RV=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(_V(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new W(`stream ended without producing a ChatCompletionMessage with role=assistant`)},zV=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(_V(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},BV=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(vV(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},VV=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},HV=function(e){if(e.n!=null&&e.n>1)throw new W(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},UV=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var KV=class e extends GV{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),_V(e)&&e.content&&this._emit(`content`,e.content)}},qV={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},JV=class extends Error{},YV=class extends Error{};function XV(e,t=qV.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return ZV(e.trim(),t)}var ZV=(e,t)=>{let n=e.length,r=0,i=e=>{throw new JV(`${e} at position ${r}`)},a=e=>{throw new YV(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||qV.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||qV.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||qV.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||qV.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||qV.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||qV.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(qV.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&qV.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(qV.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(qV.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(qV.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&qV.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(qV.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(qV.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&qV.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
195
195
|
\r `.includes(e[r]);)r++};return o()},QV=e=>XV(e,qV.ALL^qV.NUM),$V,eH,tH,nH,rH,iH,aH,oH,sH,cH,lH,uH,dH=class e extends GV{constructor(e){super(),$V.add(this),eH.set(this,void 0),tH.set(this,void 0),nH.set(this,void 0),H(this,eH,e,`f`),H(this,tH,[],`f`)}get currentChatCompletionSnapshot(){return U(this,nH,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),U(this,$V,`m`,rH).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)U(this,$V,`m`,aH).call(this,e);if(r.controller.signal?.aborted)throw new KR;return this._addChatCompletion(U(this,$V,`m`,cH).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),U(this,$V,`m`,rH).call(this),this._connected();let n=vB.fromReadableStream(e,this.controller),r;for await(let e of n)r&&r!==e.id&&this._addChatCompletion(U(this,$V,`m`,cH).call(this)),U(this,$V,`m`,aH).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new KR;return this._addChatCompletion(U(this,$V,`m`,cH).call(this))}[(eH=new WeakMap,tH=new WeakMap,nH=new WeakMap,$V=new WeakSet,rH=function(){this.ended||H(this,nH,void 0,`f`)},iH=function(e){let t=U(this,tH,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},U(this,tH,`f`)[e.index]=t,t)},aH=function(e){if(this.ended)return;let t=U(this,$V,`m`,uH).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=U(this,$V,`m`,iH).call(this,e);e.finish_reason&&(U(this,$V,`m`,sH).call(this,e),r.current_tool_call_index!=null&&U(this,$V,`m`,oH).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(U(this,$V,`m`,sH).call(this,e),r.current_tool_call_index!=null&&U(this,$V,`m`,oH).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},oH=function(e,t){if(U(this,$V,`m`,iH).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=U(this,eH,`f`)?.tools?.find(e=>aV(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:cV(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},sH=function(e){let t=U(this,$V,`m`,iH).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=U(this,$V,`m`,lH).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},cH=function(){if(this.ended)throw new W(`stream has ended, this shouldn't happen`);let e=U(this,nH,`f`);if(!e)throw new W(`request ended without sending any chunks`);return H(this,nH,void 0,`f`),H(this,tH,[],`f`),fH(e,U(this,eH,`f`))},lH=function(){let e=U(this,eH,`f`)?.response_format;return sV(e)?e:null},uH=function(e){var t,n,r,i;let a=U(this,nH,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=H(this,nH,{...s,choices:[]},`f`);for(let{delta:o,finish_reason:s,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||=a.choices[c]={finish_reason:s,index:c,message:{},logprobs:l,...u},l)if(!e.logprobs)e.logprobs=Object.assign({},l);else{let{content:r,refusal:i,...a}=l;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}if(s&&(e.finish_reason=s,U(this,eH,`f`)&&mV(U(this,eH,`f`)))){if(s===`length`)throw new rz;if(s===`content_filter`)throw new iz}if(Object.assign(e,u),!o)continue;let{content:d,refusal:f,function_call:p,role:m,tool_calls:h,...g}=o;if(Object.assign(e.message,g),f&&(e.message.refusal=(e.message.refusal||``)+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||``)+d,!e.message.refusal&&U(this,$V,`m`,lH).call(this)&&(e.message.parsed=e.message.content.trim()?QV(e.message.content):null)),h){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...o}of h){let s=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),a&&(s.function??={name:a.name??``,arguments:``}),a?.name&&(s.function.name=a.name),a?.arguments&&(s.function.arguments+=a.arguments,pV(U(this,eH,`f`),s)&&(s.function.parsed_arguments=QV(s.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new vB(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function fH(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return lV({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new W(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...l}=t,u=t.role;if(!u)throw new W(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new W(`missing function_call.arguments for choice ${r}`);if(!c)throw new W(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...l,role:u,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=i||{};if(o==null)throw new W(`missing choices[${r}].tool_calls[${n}].id\n${pH(e)}`);if(a==null)throw new W(`missing choices[${r}].tool_calls[${n}].type\n${pH(e)}`);if(l==null)throw new W(`missing choices[${r}].tool_calls[${n}].function.name\n${pH(e)}`);if(c==null)throw new W(`missing choices[${r}].tool_calls[${n}].function.arguments\n${pH(e)}`);return{...s,id:o,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function pH(e){return JSON.stringify(e)}var mH=class e extends dH{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},hH=class extends G{constructor(){super(...arguments),this.messages=new iV(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(K`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,jB,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return gV(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>uV(t,e))}runTools(e,t){return e.stream?mH.runTools(this._client,e,t):KV.runTools(this._client,e,t)}stream(e,t){return dH.createChatCompletion(this._client,e,t)}};hH.Messages=iV;var gH=class extends G{constructor(){super(...arguments),this.completions=new hH(this._client)}};gH.Completions=hH;var _H=class extends G{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(K`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,jB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},vH=class extends G{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,MB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},yH=class extends G{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(K`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,MB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,AB,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,AB,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},bH=class extends G{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}})}},xH=class extends G{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(K`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,MB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},SH=class extends G{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(K`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,NB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},CH=class extends G{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(K`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,MB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},wH=class extends G{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}})}},TH=class extends G{create(e,t,n){return this._client.post(K`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(K`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/groups/${e}/roles`,NB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(K`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},EH=class extends G{create(e,t,n){return this._client.post(K`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(K`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/groups/${e}/users`,NB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(K`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},DH=class extends G{constructor(){super(...arguments),this.users=new EH(this._client),this.roles=new TH(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(K`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,NB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};DH.Users=EH,DH.Roles=TH;var OH=class extends G{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(K`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/api_keys`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(K`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},kH=class extends G{list(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/certificates`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(K`/organization/projects/${e}/certificates/activate`,AB,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(K`/organization/projects/${e}/certificates/deactivate`,AB,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},AH=class extends G{retrieve(e,t){return this._client.get(K`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},jH=class extends G{retrieve(e,t){return this._client.get(K`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},MH=class extends G{retrieve(e,t){return this._client.get(K`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},NH=class extends G{listRateLimits(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/rate_limits`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},PH=class extends G{create(e,t,n){return this._client.post(K`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(K`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/projects/${e}/roles`,NB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(K`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},FH=class extends G{create(e,t,n){return this._client.post(K`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(K`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/service_accounts`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(K`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},IH=class extends G{create(e,t,n){return this._client.post(K`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(K`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/spend_alerts`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(K`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},LH=class extends G{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(K`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(K`/projects/${r}/groups/${e}/roles`,NB,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(K`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},RH=class extends G{constructor(){super(...arguments),this.roles=new LH(this._client)}create(e,t,n){return this._client.post(K`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(K`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/groups`,NB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(K`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};RH.Roles=LH;var zH=class extends G{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(K`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(K`/projects/${r}/users/${e}/roles`,NB,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(K`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},BH=class extends G{constructor(){super(...arguments),this.roles=new zH(this._client)}create(e,t,n){return this._client.post(K`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(K`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(K`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/projects/${e}/users`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(K`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};BH.Roles=zH;var VH=class extends G{constructor(){super(...arguments),this.users=new BH(this._client),this.serviceAccounts=new FH(this._client),this.apiKeys=new OH(this._client),this.rateLimits=new NH(this._client),this.modelPermissions=new MH(this._client),this.hostedToolPermissions=new jH(this._client),this.groups=new RH(this._client),this.roles=new PH(this._client),this.dataRetention=new AH(this._client),this.spendAlerts=new IH(this._client),this.certificates=new kH(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(K`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,MB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(K`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};VH.Users=BH,VH.ServiceAccounts=FH,VH.APIKeys=OH,VH.RateLimits=NH,VH.ModelPermissions=MH,VH.HostedToolPermissions=jH,VH.Groups=RH,VH.Roles=PH,VH.DataRetention=AH,VH.SpendAlerts=IH,VH.Certificates=kH;var HH=class extends G{create(e,t,n){return this._client.post(K`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(K`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/organization/users/${e}/roles`,NB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(K`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},UH=class extends G{constructor(){super(...arguments),this.roles=new HH(this._client)}retrieve(e,t){return this._client.get(K`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(K`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,MB,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(K`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};UH.Roles=HH;var WH=class extends G{constructor(){super(...arguments),this.auditLogs=new vH(this._client),this.adminAPIKeys=new _H(this._client),this.usage=new wH(this._client),this.invites=new xH(this._client),this.users=new UH(this._client),this.groups=new DH(this._client),this.roles=new SH(this._client),this.dataRetention=new bH(this._client),this.spendAlerts=new CH(this._client),this.certificates=new yH(this._client),this.projects=new VH(this._client)}};WH.AuditLogs=vH,WH.AdminAPIKeys=_H,WH.Usage=wH,WH.Invites=xH,WH.Users=UH,WH.Groups=DH,WH.Roles=SH,WH.DataRetention=bH,WH.SpendAlerts=CH,WH.Certificates=yH,WH.Projects=VH;var GH=class extends G{constructor(){super(...arguments),this.organization=new WH(this._client)}};GH.Organization=WH;var KH=Symbol(`brand.privateNullableHeaders`);function*qH(e){if(!e)return;if(KH in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():dz(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=dz(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var q=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of qH(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[KH]:!0,values:t,nulls:n}},JH=class extends G{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:q([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},YH=class extends G{create(e,t){return this._client.post(`/audio/transcriptions`,HB({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},XH=class extends G{create(e,t){return this._client.post(`/audio/translations`,HB({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},ZH=class extends G{constructor(){super(...arguments),this.transcriptions=new YH(this._client),this.translations=new XH(this._client),this.speech=new JH(this._client)}};ZH.Transcriptions=YH,ZH.Translations=XH,ZH.Speech=JH;var QH=class extends G{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,jB,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(K`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},$H=class extends G{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/assistants/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/assistants/${e}`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,jB,{query:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/assistants/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},eU=class extends G{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},tU=class extends G{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},nU=class extends G{constructor(){super(...arguments),this.sessions=new eU(this._client),this.transcriptionSessions=new tU(this._client)}};nU.Sessions=eU,nU.TranscriptionSessions=tU;var rU=class extends G{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(K`/chatkit/sessions/${e}/cancel`,{...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},iU=class extends G{retrieve(e,t){return this._client.get(K`/chatkit/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,MB,{query:e,...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/chatkit/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(K`/chatkit/threads/${e}/items`,MB,{query:t,...n,headers:q([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},aU=class extends G{constructor(){super(...arguments),this.sessions=new rU(this._client),this.threads=new iU(this._client)}};aU.Sessions=rU,aU.Threads=iU;var oU=class extends G{create(e,t,n){return this._client.post(K`/threads/${e}/messages`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(K`/threads/${r}/messages/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(K`/threads/${r}/messages/${e}`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/threads/${e}/messages`,jB,{query:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(K`/threads/${r}/messages/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},sU=class extends G{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(K`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(K`/threads/${r}/runs/${e}/steps`,jB,{query:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},cU=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},lU=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},uU,dU,fU,pU,mU,hU,gU,_U,vU,yU,bU,xU,SU,CU,wU,TU,EU,DU,OU,kU,AU,jU,MU,NU=class extends PV{constructor(){super(...arguments),uU.add(this),fU.set(this,[]),pU.set(this,{}),mU.set(this,{}),hU.set(this,void 0),gU.set(this,void 0),_U.set(this,void 0),vU.set(this,void 0),yU.set(this,void 0),bU.set(this,void 0),xU.set(this,void 0),SU.set(this,void 0),CU.set(this,void 0)}[(fU=new WeakMap,pU=new WeakMap,mU=new WeakMap,hU=new WeakMap,gU=new WeakMap,_U=new WeakMap,vU=new WeakMap,yU=new WeakMap,bU=new WeakMap,xU=new WeakMap,SU=new WeakMap,CU=new WeakMap,uU=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new dU;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=vB.fromReadableStream(e,this.controller);for await(let e of n)U(this,uU,`m`,wU).call(this,e);if(n.controller.signal?.aborted)throw new KR;return this._addRun(U(this,uU,`m`,TU).call(this))}toReadableStream(){return new vB(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new dU;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)U(this,uU,`m`,wU).call(this,e);if(a.controller.signal?.aborted)throw new KR;return this._addRun(U(this,uU,`m`,TU).call(this))}static createThreadAssistantStream(e,t,n){let r=new dU;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new dU;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return U(this,xU,`f`)}currentRun(){return U(this,SU,`f`)}currentMessageSnapshot(){return U(this,hU,`f`)}currentRunStepSnapshot(){return U(this,CU,`f`)}async finalRunSteps(){return await this.done(),Object.values(U(this,pU,`f`))}async finalMessages(){return await this.done(),Object.values(U(this,mU,`f`))}async finalRun(){if(await this.done(),!U(this,gU,`f`))throw Error(`Final run was not received.`);return U(this,gU,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)U(this,uU,`m`,wU).call(this,e);if(i.controller.signal?.aborted)throw new KR;return this._addRun(U(this,uU,`m`,TU).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)U(this,uU,`m`,wU).call(this,e);if(a.controller.signal?.aborted)throw new KR;return this._addRun(U(this,uU,`m`,TU).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(hz(t)&&hz(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!hz(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};dU=NU,wU=function(e){if(!this.ended)switch(H(this,xU,e,`f`),U(this,uU,`m`,OU).call(this,e),e.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:U(this,uU,`m`,MU).call(this,e);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:U(this,uU,`m`,DU).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:U(this,uU,`m`,EU).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},TU=function(){if(this.ended)throw new W(`stream has ended, this shouldn't happen`);if(!U(this,gU,`f`))throw Error(`Final run has not been received`);return U(this,gU,`f`)},EU=function(e){let[t,n]=U(this,uU,`m`,AU).call(this,e,U(this,hU,`f`));H(this,hU,t,`f`),U(this,mU,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=U(this,_U,`f`)){if(U(this,vU,`f`))switch(U(this,vU,`f`).type){case`text`:this._emit(`textDone`,U(this,vU,`f`).text,U(this,hU,`f`));break;case`image_file`:this._emit(`imageFileDone`,U(this,vU,`f`).image_file,U(this,hU,`f`));break}H(this,_U,n.index,`f`)}H(this,vU,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(U(this,_U,`f`)!==void 0){let t=e.data.content[U(this,_U,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,U(this,hU,`f`));break;case`text`:this._emit(`textDone`,t.text,U(this,hU,`f`));break}}U(this,hU,`f`)&&this._emit(`messageDone`,e.data),H(this,hU,void 0,`f`)}},DU=function(e){let t=U(this,uU,`m`,kU).call(this,e);switch(H(this,CU,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==U(this,yU,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(U(this,bU,`f`)&&this._emit(`toolCallDone`,U(this,bU,`f`)),H(this,yU,e.index,`f`),H(this,bU,t.step_details.tool_calls[e.index],`f`),U(this,bU,`f`)&&this._emit(`toolCallCreated`,U(this,bU,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:H(this,CU,void 0,`f`),e.data.step_details.type==`tool_calls`&&U(this,bU,`f`)&&(this._emit(`toolCallDone`,U(this,bU,`f`)),H(this,bU,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},OU=function(e){U(this,fU,`f`).push(e),this._emit(`event`,e)},kU=function(e){switch(e.event){case`thread.run.step.created`:return U(this,pU,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=U(this,pU,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=dU.accumulateDelta(t,n.delta);U(this,pU,`f`)[e.data.id]=r}return U(this,pU,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:U(this,pU,`f`)[e.data.id]=e.data;break}if(U(this,pU,`f`)[e.data.id])return U(this,pU,`f`)[e.data.id];throw Error(`No snapshot available`)},AU=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=U(this,uU,`m`,jU).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},jU=function(e,t){return dU.accumulateDelta(t,e)},MU=function(e){switch(H(this,SU,e.data,`f`),e.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:H(this,gU,e.data,`f`),U(this,bU,`f`)&&(this._emit(`toolCallDone`,U(this,bU,`f`)),H(this,bU,void 0,`f`));break;case`thread.run.cancelling`:break}};var PU=class extends G{constructor(){super(...arguments),this.steps=new sU(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(K`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(K`/threads/${r}/runs/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(K`/threads/${r}/runs/${e}`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/threads/${e}/runs`,jB,{query:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(K`/threads/${r}/runs/${e}/cancel`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return NU.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=q([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await vz(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return NU.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(K`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return NU.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};PU.Steps=sU;var FU=class extends G{constructor(){super(...arguments),this.runs=new PU(this._client),this.messages=new oU(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/threads/${e}`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/threads/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return NU.createThreadAssistantStream(e,this._client.beta.threads,t)}};FU.Runs=PU,FU.Messages=oU;var IU=class extends G{constructor(){super(...arguments),this.realtime=new nU(this._client),this.chatkit=new aU(this._client),this.assistants=new $H(this._client),this.threads=new FU(this._client)}};IU.Realtime=nU,IU.ChatKit=aU,IU.Assistants=$H,IU.Threads=FU;var LU=class extends G{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},RU=class extends G{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(K`/containers/${r}/files/${e}/content`,{...n,headers:q([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},zU=class extends G{constructor(){super(...arguments),this.content=new RU(this._client)}create(e,t,n){return this._client.post(K`/containers/${e}/files`,VB({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(K`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/containers/${e}/files`,jB,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(K`/containers/${r}/files/${e}`,{...n,headers:q([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};zU.Content=RU;var BU=class extends G{constructor(){super(...arguments),this.files=new zU(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,jB,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/containers/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};BU.Files=zU;var VU=class extends G{create(e,t,n){let{include:r,...i}=t;return this._client.post(K`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(K`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/conversations/${e}/items`,MB,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(K`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},HU=class extends G{constructor(){super(...arguments),this.items=new VU(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};HU.Items=VU;var UU=class extends G{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&hB(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(hB(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=cU(t)}),e)))}},WU=class extends G{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(K`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(K`/evals/${r}/runs/${e}/output_items`,jB,{query:i,...n,__security:{bearerAuth:!0}})}},GU=class extends G{constructor(){super(...arguments),this.outputItems=new WU(this._client)}create(e,t,n){return this._client.post(K`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(K`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/evals/${e}/runs`,jB,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(K`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(K`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};GU.OutputItems=WU;var KU=class extends G{constructor(){super(...arguments),this.runs=new GU(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,jB,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};KU.Runs=GU;var qU=class extends G{create(e,t){return this._client.post(`/files`,HB({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(K`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,jB,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(K`/files/${e}/content`,{...t,headers:q([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await vz(t),a=await this.retrieve(e),Date.now()-i>n)throw new JR({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},JU=class extends G{},YU=class extends G{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}})}},XU=class extends G{constructor(){super(...arguments),this.graders=new YU(this._client)}};XU.Graders=YU;var ZU=class extends G{create(e,t,n){return this._client.getAPIList(K`/fine_tuning/checkpoints/${e}/permissions`,AB,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(K`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/fine_tuning/checkpoints/${e}/permissions`,MB,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(K`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},QU=class extends G{constructor(){super(...arguments),this.permissions=new ZU(this._client)}};QU.Permissions=ZU;var $U=class extends G{list(e,t={},n){return this._client.getAPIList(K`/fine_tuning/jobs/${e}/checkpoints`,jB,{query:t,...n,__security:{bearerAuth:!0}})}},eW=class extends G{constructor(){super(...arguments),this.checkpoints=new $U(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(K`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,jB,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(K`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(K`/fine_tuning/jobs/${e}/events`,jB,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(K`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(K`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};eW.Checkpoints=$U;var tW=class extends G{constructor(){super(...arguments),this.methods=new JU(this._client),this.jobs=new eW(this._client),this.checkpoints=new QU(this._client),this.alpha=new XU(this._client)}};tW.Methods=JU,tW.Jobs=eW,tW.Checkpoints=QU,tW.Alpha=XU;var nW=class extends G{},rW=class extends G{constructor(){super(...arguments),this.graderModels=new nW(this._client)}};rW.GraderModels=nW;var iW=class extends G{createVariation(e,t){return this._client.post(`/images/variations`,HB({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,HB({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}})}},aW=class extends G{retrieve(e,t){return this._client.get(K`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,AB,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},oW=class extends G{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},sW=class extends G{accept(e,t,n){return this._client.post(K`/realtime/calls/${e}/accept`,{body:t,...n,headers:q([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(K`/realtime/calls/${e}/hangup`,{...t,headers:q([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(K`/realtime/calls/${e}/refer`,{body:t,...n,headers:q([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(K`/realtime/calls/${e}/reject`,{body:t,...n,headers:q([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},cW=class extends G{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},lW=class extends G{constructor(){super(...arguments),this.clientSecrets=new cW(this._client),this.calls=new sW(this._client)}};lW.ClientSecrets=cW,lW.Calls=sW;function uW(e,t){if(!t||!pW(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return _W(e,t)&&vW(t),t}return dW(e,t)}function dW(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:n?gW(t,e):null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?fW(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return _W(e,i)&&vW(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function fW(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function pW(e){return!!sV(e.text?.format)}function mW(e){return e?.$brand===`auto-parseable-tool`}function hW(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function gW(e,t){let n=hW(e.tools??[],t.name);return{...t,...t,parsed_arguments:mW(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function _W(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function vW(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}function yW(e,t){if(!t){if(e.type!==`response.created`)throw new W(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return bW(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&vW(t);break;case`response.output_item.done`:xW(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&vW(t);break;case`response.content_part.added`:{let n=xW(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&vW(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=xW(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)SW(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&vW(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new W(`missing content at index ${e.content_index}`);SW(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=xW(t,e.output_index);if(n.type===`message`){let r=SW(n.content,e.content_index);if(r.type!==`output_text`)throw new W(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=xW(t,e.output_index);if(n.type===`message`){let r=SW(n.content,e.content_index);if(r.type!==`output_text`)throw new W(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,vW(t)}break}case`response.output_text.annotation.added`:{let n=xW(t,e.output_index);if(n.type===`message`){let t=SW(n.content,e.content_index);if(t.type!==`output_text`)throw new W(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}case`response.refusal.delta`:{let n=xW(t,e.output_index);if(n.type===`message`){let t=SW(n.content,e.content_index);if(t.type!==`refusal`)throw new W(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}case`response.refusal.done`:{let n=xW(t,e.output_index);if(n.type===`message`){let t=SW(n.content,e.content_index);if(t.type!==`refusal`)throw new W(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=xW(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=xW(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=xW(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new W(`missing content at index ${e.content_index}`);let t=SW(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new W(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=xW(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new W(`missing content at index ${e.content_index}`);let t=SW(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new W(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=xW(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=xW(t,e.output_index);n.type===`reasoning`&&(SW(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}case`response.reasoning_summary_text.delta`:{let n=xW(t,e.output_index);if(n.type===`reasoning`){let t=SW(n.summary,e.summary_index);t.text+=e.delta}break}case`response.reasoning_summary_text.done`:{let n=xW(t,e.output_index);if(n.type===`reasoning`){let t=SW(n.summary,e.summary_index);t.text=e.text}break}case`response.custom_tool_call_input.delta`:{let n=xW(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=xW(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=xW(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=xW(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=xW(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=xW(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=xW(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=xW(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=xW(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=xW(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=xW(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=xW(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=xW(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=xW(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=xW(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=xW(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=xW(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=xW(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=xW(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=xW(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=xW(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=bW(e.response);break;case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`error`:break;default:CW(e)}return t}function bW(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&vW(t),t}function xW(e,t){let n=e.output[t];if(!n)throw new W(`missing output at index ${t}`);return n}function SW(e,t){let n=e[t];if(!n)throw new W(`missing content at index ${t}`);return n}function CW(e){throw new W(`Unhandled response stream event: ${JSON.stringify(e)}`)}var wW,TW,EW,DW,OW,kW,AW,jW=class e extends PV{constructor(e){super(),wW.add(this),TW.set(this,void 0),EW.set(this,void 0),DW.set(this,void 0),H(this,TW,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),U(this,wW,`m`,OW).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)U(this,wW,`m`,kW).call(this,e,i);if(r.controller.signal?.aborted)throw new KR;return U(this,wW,`m`,AW).call(this)}[(TW=new WeakMap,EW=new WeakMap,DW=new WeakMap,wW=new WeakSet,OW=function(){this.ended||H(this,EW,void 0,`f`)},kW=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=yW(e,U(this,EW,`f`));switch(H(this,EW,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new W(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new W(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new W(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new W(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e);break}},AW=function(){if(this.ended)throw new W(`stream has ended, this shouldn't happen`);let e=U(this,EW,`f`);if(!e)throw new W(`request ended without sending any events`);H(this,EW,void 0,`f`);let t=MW(e,U(this,TW,`f`));return H(this,DW,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=U(this,DW,`f`);if(!e)throw new W(`stream ended without producing a ChatCompletion`);return e}};function MW(e,t){return uW(e,t)}var NW=class extends G{list(e,t={},n){return this._client.getAPIList(K`/responses/${e}/input_items`,jB,{query:t,...n,__security:{bearerAuth:!0}})}},PW=class extends G{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},FW=class extends G{constructor(){super(...arguments),this.inputItems=new NW(this._client),this.inputTokens=new PW(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&vW(e),e))}retrieve(e,t={},n){return this._client.get(K`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&vW(e),e))}delete(e,t){return this._client.delete(K`/responses/${e}`,{...t,headers:q([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>dW(t,e))}stream(e,t){return jW.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(K`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};FW.InputItems=NW,FW.InputTokens=PW;var IW=class extends G{retrieve(e,t){return this._client.get(K`/skills/${e}/content`,{...t,headers:q([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},LW=class extends G{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(K`/skills/${r}/versions/${e}/content`,{...n,headers:q([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},RW=class extends G{constructor(){super(...arguments),this.content=new LW(this._client)}create(e,t={},n){return this._client.post(K`/skills/${e}/versions`,VB({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(K`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/skills/${e}/versions`,jB,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(K`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};RW.Content=LW;var zW=class extends G{constructor(){super(...arguments),this.content=new IW(this._client),this.versions=new RW(this._client)}create(e={},t){return this._client.post(`/skills`,VB({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(K`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,jB,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};zW.Content=IW,zW.Versions=RW;var BW=class extends G{create(e,t,n){return this._client.post(K`/uploads/${e}/parts`,HB({body:t,...n,__security:{bearerAuth:!0}},this._client))}},VW=class extends G{constructor(){super(...arguments),this.parts=new BW(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(K`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(K`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};VW.Parts=BW;var HW=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},UW=class extends G{create(e,t,n){return this._client.post(K`/vector_stores/${e}/file_batches`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(K`/vector_stores/${r}/file_batches/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(K`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(K`/vector_stores/${r}/file_batches/${e}/files`,jB,{query:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=q([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await vz(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await HW(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},WW=class extends G{create(e,t,n){return this._client.post(K`/vector_stores/${e}/files`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(K`/vector_stores/${r}/files/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(K`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(K`/vector_stores/${e}/files`,jB,{query:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(K`/vector_stores/${r}/files/${e}`,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=q([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await vz(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(K`/vector_stores/${r}/files/${e}/content`,AB,{...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},GW=class extends G{constructor(){super(...arguments),this.files=new WW(this._client),this.fileBatches=new UW(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(K`/vector_stores/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(K`/vector_stores/${e}`,{body:t,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,jB,{query:e,...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/vector_stores/${e}`,{...t,headers:q([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(K`/vector_stores/${e}/search`,AB,{body:t,method:`post`,...n,headers:q([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};GW.Files=WW,GW.FileBatches=UW;var KW=class extends G{create(e,t){return this._client.post(`/videos`,HB({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(K`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,MB,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(K`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,HB({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(K`/videos/${e}/content`,{query:t,...n,headers:q([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,HB({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,HB({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(K`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(K`/videos/${e}/remix`,VB({body:t,...n,__security:{bearerAuth:!0}},this._client))}},qW,JW,YW,XW=class extends G{constructor(){super(...arguments),qW.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");U(this,qW,`m`,JW).call(this,n);let i=q([t]).values,a=U(this,qW,`m`,YW).call(this,i,`webhook-signature`),o=U(this,qW,`m`,YW).call(this,i,`webhook-timestamp`),s=U(this,qW,`m`,YW).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new az(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new az(`Webhook timestamp is too old`);if(c>l+r)throw new az(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new az(`The given webhook signature does not match the expected signature`)}};qW=new WeakSet,JW=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},YW=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var ZW=Symbol.for(`openai.node.providerDefinitions.v1`),QW=globalThis,$W=QW[ZW],eG=$W??new WeakMap;$W||Object.defineProperty(QW,ZW,{value:eG});function tG(e){let t=eG.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var nG,rG,iG,aG,oG=`workload-identity-auth`,J=class{constructor(e={}){nG.add(this),iG.set(this,void 0),this.completions=new LU(this),this.chat=new gH(this),this.embeddings=new UU(this),this.files=new qU(this),this.images=new iW(this),this.audio=new ZH(this),this.moderations=new oW(this),this.models=new aW(this),this.fineTuning=new tW(this),this.graders=new rW(this),this.vectorStores=new GW(this),this.webhooks=new XW(this),this.beta=new IU(this),this.batches=new QH(this),this.uploads=new VW(this),this.admin=new GH(this),this.responses=new FW(this),this.realtime=new lW(this),this.conversations=new HU(this),this.evals=new KU(this),this.containers=new BU(this),this.skills=new zW(this),this.videos=new KW(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new W(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:lU(`OPENAI_BASE_URL`),apiKey:r=t?null:lU(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:lU(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:lU(`OPENAI_ORG_ID`)??null,project:o=t?null:lU(`OPENAI_PROJECT_ID`)??null,webhookSecret:s=lU(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:c,...l}=e,u=t?tG(t):void 0,d={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:s,workloadIdentity:c,provider:t,...l,baseURL:u?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&c)throw new W("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!u&&!r&&!i&&!c)throw new W("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&bz())throw new W(`It looks like you're running in a browser-like environment.
|
|
196
196
|
|
|
197
197
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
@@ -208,7 +208,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
208
208
|
`);case`array`:return e.items?`${AG(e.items,t)}[]`:`any[]`;default:return``}}function jG(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function MG(e){return`type`in e&&e.type!==`function`}function NG(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function PG(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function FG(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function IG(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function LG(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function RG(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function zG(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function BG(e,t){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`tool_call`?!1:!!(`isCustomTool`in e&&e.isCustomTool===!0||t&&`id`in e&&typeof e.id==`string`&&e.id in t)}function VG(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function HG(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var UG=Symbol(`Let zodToJsonSchema decide on which parser to use`),WG={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`},GG=e=>typeof e==`string`?{...WG,basePath:[`#`],definitions:{},name:e}:{...WG,basePath:[`#`],definitions:{},...e},KG=e=>`_def`in e?e._def:e;function qG(e){if(!e)return!0;for(let t in e)return!1;return!0}var JG=e=>{let t=GG(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[KG(n),{def:KG(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function YG(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function XG(e,t,n,r,i){e[t]=n,YG(e,t,r,i)}function ZG(){return{}}function QG(e,t){let n={type:`array`};return e.type?._def?.typeName!==L.ZodAny&&(n.items=RK(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&XG(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&XG(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(XG(n,`minItems`,e.exactLength.value,e.exactLength.message,t),XG(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function $G(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?XG(n,`minimum`,r.value,r.message,t):XG(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),XG(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?XG(n,`maximum`,r.value,r.message,t):XG(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),XG(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:XG(n,`multipleOf`,r.value,r.message,t);break}return n}function eK(){return{type:`boolean`}}function tK(e,t,n){return RK(e.type._def,t,n)}var nK=(e,t,n)=>RK(e.innerType._def,t,n);function rK(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>rK(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return iK(e,t)}}var iK=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:XG(n,`minimum`,r.value,r.message,t);break;case`max`:XG(n,`maximum`,r.value,r.message,t);break}return n};function aK(e,t,n){return{...RK(e.innerType._def,t,n),default:e.defaultValue()}}function oK(e,t,n){return t.effectStrategy===`input`?RK(e.schema._def,t,n):{}}function sK(e){return{type:`string`,enum:[...e.values]}}var cK=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function lK(e,t){let n=[RK(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),RK(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(cK(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function uK(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var dK,fK={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:()=>(dK===void 0&&(dK=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),dK),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function pK(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?mK(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:XG(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:XG(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:hK(n,`email`,i.message,t);break;case`format:idn-email`:hK(n,`idn-email`,i.message,t);break;case`pattern:zod`:gK(n,fK.email,i.message,t);break}break;case`url`:hK(n,`uri`,i.message,t);break;case`uuid`:hK(n,`uuid`,i.message,t);break;case`regex`:gK(n,i.regex,i.message,t);break;case`cuid`:gK(n,fK.cuid,i.message,t);break;case`cuid2`:gK(n,fK.cuid2,i.message,t);break;case`startsWith`:gK(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:gK(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:hK(n,`date-time`,i.message,t);break;case`date`:hK(n,`date`,i.message,t);break;case`time`:hK(n,`time`,i.message,t);break;case`duration`:hK(n,`duration`,i.message,t);break;case`length`:XG(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),XG(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:gK(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&hK(n,`ipv4`,i.message,t),i.version!==`v4`&&hK(n,`ipv6`,i.message,t);break;case`emoji`:gK(n,fK.emoji,i.message,t);break;case`ulid`:gK(n,fK.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:hK(n,`binary`,i.message,t);break;case`contentEncoding:base64`:XG(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:gK(n,fK.base64,i.message,t);break}break;case`nanoid`:gK(n,fK.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}var mK=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),hK=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):XG(e,`format`,t,n,r)},gK=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:_K(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):XG(e,`pattern`,_K(t,r),n,r)},_K=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
|
|
209
209
|
]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
|
|
210
210
|
]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function vK(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===L.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:RK(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:RK(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===L.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(pK(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===L.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function yK(e,t){return t.mapStrategy===`record`?vK(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[RK(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},RK(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function bK(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function xK(){return{not:{}}}function SK(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var CK={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function wK(e,t){if(t.target===`openApi3`)return TK(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in CK&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=CK[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return TK(e,t)}var TK=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>RK(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function EK(e,t,n){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:CK[e.innerType._def.typeName],nullable:!0}:{type:[CK[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let r=RK(e.innerType._def,{...t,currentPath:[...t.currentPath]},n);return r&&`$ref`in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=RK(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return r&&{anyOf:[r,{type:`null`}]}}function DK(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,YG(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?XG(n,`minimum`,r.value,r.message,t):XG(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),XG(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?XG(n,`maximum`,r.value,r.message,t):XG(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),XG(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:XG(n,`multipleOf`,r.value,r.message,t);break}return n}function OK(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:RK(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:RK(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function kK(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=RK(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw Error(`Zod field at \`${i.join(`/`)}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:OK(e,t)};return n.required.length||delete n.required,n}var AK=(e,t,n)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return RK(e.innerType._def,{...t,currentPath:t.currentPath},n);let r=RK(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]},n);return r?{anyOf:[{not:{}},r]}:{}},jK=(e,t,n)=>{if(t.pipeStrategy===`input`)return RK(e.in._def,t,n);if(t.pipeStrategy===`output`)return RK(e.out._def,t,n);let r=RK(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[r,RK(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,r?`1`:`0`]})].filter(e=>e!==void 0)}};function MK(e,t,n){return RK(e.type._def,t,n)}function NK(e,t){let n={type:`array`,uniqueItems:!0,items:RK(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&XG(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&XG(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function PK(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>RK(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:RK(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>RK(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function FK(){return{not:{}}}function IK(){return{}}var LK=(e,t,n)=>RK(e.innerType._def,t,n);function RK(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==UG)return i}if(r&&!n){let e=zK(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);try{let r=UK(e,e.typeName,t,n);return r&&WK(e,t,r),i.jsonSchema=r,r}finally{n&&r&&t.seen.set(e,r)}}var zK=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).map((e,t)=>t===0?e:VK(e)).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:HK(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},BK=`_x_`,VK=e=>{if(/^[A-Za-z0-9_-]*$/.test(e)&&!e.startsWith(BK))return e;let t=BK;for(let n=0;n<e.length;n++)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t},HK=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},UK=(e,t,n,r)=>{switch(t){case L.ZodString:return pK(e,n);case L.ZodNumber:return DK(e,n);case L.ZodObject:return kK(e,n);case L.ZodBigInt:return $G(e,n);case L.ZodBoolean:return eK();case L.ZodDate:return rK(e,n);case L.ZodUndefined:return FK();case L.ZodNull:return SK(n);case L.ZodArray:return QG(e,n);case L.ZodUnion:case L.ZodDiscriminatedUnion:return wK(e,n);case L.ZodIntersection:return lK(e,n);case L.ZodTuple:return PK(e,n);case L.ZodRecord:return vK(e,n);case L.ZodLiteral:return uK(e,n);case L.ZodEnum:return sK(e);case L.ZodNativeEnum:return bK(e);case L.ZodNullable:return EK(e,n,r);case L.ZodOptional:return AK(e,n,r);case L.ZodMap:return yK(e,n);case L.ZodSet:return NK(e,n);case L.ZodLazy:return RK(e.getter()._def,n,r);case L.ZodPromise:return MK(e,n,r);case L.ZodNaN:case L.ZodNever:return xK();case L.ZodEffects:return oK(e,n,r);case L.ZodAny:return ZG();case L.ZodUnknown:return IK();case L.ZodDefault:return aK(e,n,r);case L.ZodBranded:return tK(e,n,r);case L.ZodReadonly:return LK(e,n,r);case L.ZodCatch:return nK(e,n,r);case L.ZodPipeline:return jK(e,n,r);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(e=>void 0)(t)}},WK=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),GK=(e,t)=>{let n=JG(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=RK(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(qG(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=RK(KG(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};function KK(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return JK(t,[],t)}function qK(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(qK(t))return!0;for(let t of e.anyOf??[])if(qK(t))return!0;return!1}function JK(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!XK(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(XK(r))for(let[e,i]of Object.entries(r))JK(i,[...t,`$defs`,e],n);let i=e.definitions;if(XK(i))for(let[e,r]of Object.entries(i))JK(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(XK(o)){for(let[e,n]of Object.entries(o))if(!qK(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].join(`/`)}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,JK(r,[...t,`properties`,e],n)]))}let s=e.items;XK(s)&&(e.items=JK(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>JK(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=JK(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>JK(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&ZK(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=YK(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!XK(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,JK(e,t,n)}return e}function YK(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!XK(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function XK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ZK(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function QK(e,t){return GK(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function $K(e){return KK(Zg(e,{target:`draft-7`,override:({zodSchema:e,jsonSchema:t})=>{let n=e._zod.def;if(n.type===`union`&&`discriminator`in n&&Array.isArray(t.oneOf)){if(t.anyOf!==void 0)throw Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");t.anyOf=t.oneOf,delete t.oneOf}}}))}function eq(e){return`_zod`in e}function tq(e,t,n){return oV({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:eq(e)?$K(e):QK(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var nq=[`jsonSchema`,`functionCalling`,`jsonMode`];function rq(e,t){if(t!==void 0&&!nq.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${nq.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function iq(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function aq(e,t,n){if($g(e))return tq(e,t,n);if(Qg(e))return iq({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:ox(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>xf(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function oq(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var sq={"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 cq(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var lq=class extends EE{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model=`gpt-3.5-turbo`;modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return`openai`}static lc_name(){return`ChatOpenAI`}get callKeys(){return[...super.callKeys,`options`,`function_call`,`functions`,`tools`,`tool_choice`,`promptIndex`,`response_format`,`seed`,`reasoning`,`reasoning_effort`,`service_tier`]}lc_serializable=!0;get lc_secrets(){return{apiKey:`OPENAI_API_KEY`,organization:`OPENAI_ORGANIZATION`}}get lc_aliases(){return{apiKey:`openai_api_key`,modelName:`model`}}get lc_serializable_keys(){return`configuration.logprobs.topLogprobs.prefixMessages.supportsStrictToolCalling.modalities.audio.temperature.maxTokens.topP.frequencyPenalty.presencePenalty.n.logitBias.user.streaming.streamUsage.model.modelName.modelKwargs.stop.stopSequences.timeout.apiKey.cache.maxConcurrency.maxRetries.verbose.callbacks.tags.metadata.disableStreaming.zdrEnabled.reasoning.promptCacheKey.promptCacheRetention.verbosity`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??Pr(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??Pr(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion(`@langchain/openai`,`1.5.3`)}_getReasoningParams(e){if(!mG(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&t_(e.json_schema.schema)?aq(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let e=xG({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=TG(t.defaultHeaders),this.client=new J(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return FG(e)?HG(e.metadata.customTool):dT(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:EG(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>{if(MG(e)||FG(e))return e;if(NG(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return Sk(e)&&e.extras?.defer_loading===!0?{...t,defer_loading:!0}:t}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(yG(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=OG(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw fG(e)}})}get profile(){return sq[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let s=rq(this.model,t?.method);if(s===`jsonMode`){r=JT(i);let e=ox(i);n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:a??`extract`,...e}}})}else if(s===`jsonSchema`){let e=ox(i),o={name:a??`extract`,description:l_(e),schema:t_(i)?i:e,strict:t?.strict};if(n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:o},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:o.name,description:o.description,...e}}}),t_(i)||yb(i)){let e=JT(i);r=jx.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new kT}else{let e=a??`extract`,o=ox(i),s;t_(i)||yb(i)?s={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(s=i,e=i.name):(e=i.title??e,s={name:e,description:i.description??``,parameters:i}),n=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:s}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...t?.strict===void 0?{}:{strict:t.strict}}),r=YT(i,e)}return XT(n,r,o)}},uq={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=Ee({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=Te(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=Te(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=Ee({dataUrl:e.url}),n=vG(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,filename:n}}}if(e.source_type===`base64`){let t=vG(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:t}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},dq=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls,i=e.reasoning_content;switch(e.role){case`assistant`:{let a=[],o=[];for(let e of r??[])try{a.push(HT(e,{returnId:!0}))}catch(t){o.push(WT(e,t.message))}let s={function_call:e.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=t),i!==void 0&&(s.reasoning_content=i);let c={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(s.audio=e.audio),new $t({content:oq(e.content||``,t.choices?.[0]?.message),tool_calls:a,invalid_tool_calls:o,additional_kwargs:s,response_metadata:c,id:t.id})}default:return new rn(e.content||``,e.role??`unknown`)}},fq=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.reasoning_content!==void 0&&(o.reasoning_content=e.reasoning_content),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new pn({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new nn({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new vn({content:a,response_metadata:s});else if(i===`developer`)return new vn({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new ln({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new St({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new an({content:a,role:i,response_metadata:s})},pq=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=Sn(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=vG(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},mq=({message:e,model:t})=>{let n=yG(e);if(n===`system`&&mG(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`){let t={role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};return $t.isInstance(e)&&e.tool_calls?.length?t.tool_calls=e.tool_calls.map(UT):e.additional_kwargs.tool_calls!=null&&(t.tool_calls=e.additional_kwargs.tool_calls),t}else if(n===`tool`&&xt.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};else if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=pq(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},hq=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return mq({message:e});let n=yG(e);n===`system`&&mG(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>ye(e)?De(e,uq):typeof e==`object`&&e&&`type`in e&&e.type===`tool_use`?[]:e),i={role:n,content:r};return e.name!=null&&(i.name=e.name),e.additional_kwargs.function_call!=null&&(i.function_call=e.additional_kwargs.function_call),$t.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(UT):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),xt.isInstance(e)&&e.tool_call_id!=null&&(i.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[i,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:i}),gq=class extends lq{constructor(e,t){super(cq(e,t))}invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict,!(this.streaming||t?.streaming)&&e?.response_format?.type===`json_schema`&&n!==!1&&(n=!0);let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:jG(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),mG(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=hq({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:o,total_tokens:s,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),o&&(r.input_tokens=(r.input_tokens??0)+o),s&&(r.total_tokens=(r.total_tokens??0)+s),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(r.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(l?.audio_tokens!==null||l?.reasoning_tokens!==null)&&(r.output_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.reasoning_tokens!==null&&{reasoning:l?.reasoning_tokens}});let u=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},en(n.message)&&(n.message.usage_metadata=r),n.message=new $t(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(e,t,n){let r=hq({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a=await this.completionWithRetry(i,t),o=this.streamUsage??t.streamUsage;yield*kE(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=hq({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new Uu({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}},r=new Uu({message:new nn({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``});yield r,await n?.handleLLMNewToken(r.text??``,{prompt:0,completion:0},void 0,void 0,void 0,{chunk:r})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw fG(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return fq({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return dq({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},_q={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`},vq={azureOpenAIApiKey:`AZURE_OPENAI_API_KEY`},yq=[`azureOpenAIApiKey`,`azureOpenAIApiVersion`,`azureOpenAIBasePath`,`azureOpenAIEndpoint`,`azureOpenAIApiInstanceName`,`azureOpenAIApiDeploymentName`,`deploymentName`,`openAIApiKey`,`openAIApiVersion`];function bq(e,t){return typeof e==`string`?{model:e,deploymentName:e,azureOpenAIApiDeploymentName:e,...t??{}}:e??t}function xq(e){if(this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.openAIApiKey==`string`?e?.openAIApiKey:void 0)??(typeof e?.apiKey==`string`?e?.apiKey:void 0)??Pr(`AZURE_OPENAI_API_KEY`),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??Pr(`AZURE_OPENAI_API_INSTANCE_NAME`),this.azureOpenAIApiDeploymentName=e?.azureOpenAIApiDeploymentName??e?.deploymentName??Pr(`AZURE_OPENAI_API_DEPLOYMENT_NAME`),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??Pr(`AZURE_OPENAI_API_VERSION`),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??Pr(`AZURE_OPENAI_BASE_PATH`),this.azureOpenAIEndpoint=e?.azureOpenAIEndpoint??Pr(`AZURE_OPENAI_ENDPOINT`),this.azureADTokenProvider=e?.azureADTokenProvider,!this.azureOpenAIApiKey&&!this.apiKey&&!this.azureADTokenProvider)throw Error(`Azure OpenAI API key or Token Provider not found`)}function Sq(e){if(!this.client){let e={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL,azureOpenAIEndpoint:this.azureOpenAIEndpoint},t=xG(e),{apiKey:n,...r}=this.clientConfig,i={...r,baseURL:t,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(i.apiKey=e.azureOpenAIApiKey),i.baseURL||delete i.baseURL,i.defaultHeaders=TG(i.defaultHeaders,!0,`2.0.0`),this.client=new lG({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...i})}let t={...this.clientConfig,...e};return this.azureOpenAIApiKey&&(t.headers={"api-key":this.azureOpenAIApiKey,...t.headers},t.query={"api-version":this.azureOpenAIApiVersion,...t.query}),t}function Cq(e){let t=e;function n(e){return typeof e==`object`&&!!e}if(n(t)&&n(t.kwargs)){if(delete t.kwargs.azure_openai_base_path,delete t.kwargs.azure_openai_api_deployment_name,delete t.kwargs.azure_openai_api_key,delete t.kwargs.azure_openai_api_version,delete t.kwargs.azure_open_ai_base_path,!t.kwargs.azure_endpoint&&this.azureOpenAIEndpoint&&(t.kwargs.azure_endpoint=this.azureOpenAIEndpoint),!t.kwargs.azure_endpoint&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2&&e[0].startsWith(`http`)){let[n]=e;t.kwargs.azure_endpoint=n}}if(!t.kwargs.azure_endpoint&&this.azureOpenAIApiInstanceName&&(t.kwargs.azure_endpoint=`https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`),!t.kwargs.deployment_name&&this.azureOpenAIApiDeploymentName&&(t.kwargs.deployment_name=this.azureOpenAIApiDeploymentName),!t.kwargs.deployment_name&&this.azureOpenAIBasePath){let e=this.azureOpenAIBasePath.split(`/openai/deployments/`);if(e.length===2){let[,n]=e;t.kwargs.deployment_name=n}}t.kwargs.azure_endpoint&&t.kwargs.deployment_name&&t.kwargs.openai_api_base&&delete t.kwargs.openai_api_base,t.kwargs.azure_openai_api_instance_name&&t.kwargs.azure_endpoint&&delete t.kwargs.azure_openai_api_instance_name}return t}var wq=class extends gq{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,..._q}}get lc_secrets(){return{...super.lc_secrets,...vq}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...yq]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=bq(e,t);super(n),xq.call(this,n)}_getClientOptions(e){return Sq.call(this,e)}toJSON(){return Cq.call(this,super.toJSON())}},Tq=`__openai_function_call_ids__`,Eq=`__openai_custom_tool_call_ids__`;function Dq(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}function Oq(e){if(e.type===`url_citation`||e.type===`file_citation`||e.type===`container_file_citation`||e.type===`file_path`)return e;if(e.type===`citation`){let t=e;if(t.source===`url_citation`)return{type:`url_citation`,url:t.url??``,title:t.title??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_citation`)return{type:`file_citation`,file_id:t.file_id??``,filename:t.title??``,index:t.startIndex??0};if(t.source===`container_file_citation`)return{type:`container_file_citation`,file_id:t.file_id??``,filename:t.title??``,container_id:t.container_id??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_path`)return{type:`file_path`,file_id:t.file_id??``,index:t.startIndex??0}}return e.type===`non_standard`?e.value:e}var kq=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},Aq=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t=[],n=[],r=[],i=e.output.map(e=>{if(e.type===`function_call`&&`parsed_arguments`in e){let t={...e};return delete t.parsed_arguments,t}return e}),a={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:i,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let i of e.output)if(i.type===`message`)t.push(...i.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(o.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(Dq),...i.phase===null?{}:{phase:i.phase}}):e.type===`refusal`?(o.refusal=e.refusal,[]):e));else if(i.type===`function_call`){let e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{n.push(HT(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),r.push(WT(e,n))}o[Tq]??={},i.id&&(o[Tq][i.call_id]=i.id)}else if(i.type===`reasoning`){o.reasoning=i;let e=i.summary?.map(e=>e.text).filter(Boolean).join(``);e&&t.push({type:`reasoning`,reasoning:e})}else if(i.type===`custom_tool_call`){let e=LG(i);e?(n.push(e),o[Eq]??={},i.id&&i.call_id&&(o[Eq][i.call_id]=i.id)):r.push(WT(i,`Malformed custom tool call`))}else if(i.type===`computer_call`){let e=RG(i);e?n.push(e):r.push(WT(i,`Malformed computer call`))}else i.type===`image_generation_call`?(i.result&&t.push({type:`image`,mimeType:`image/png`,data:i.result,id:i.id,metadata:{status:i.status}}),o.tool_outputs??=[],o.tool_outputs.push(i)):(o.tool_outputs??=[],o.tool_outputs.push(i));return new $t({id:e.id,content:t,tool_calls:n,invalid_tool_calls:r,usage_metadata:kq(e.usage),additional_kwargs:o,response_metadata:a})},jq=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},Mq=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[Dq(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`){let n=`phase`in e.item?e.item.phase:void 0;n&&t.push({type:`text`,text:``,phase:n,index:0})}else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[Tq]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.added`&&e.item.type===`custom_tool_call`)i.push({type:`tool_call_chunk`,isCustomTool:!0,name:e.item.name,args:e.item.input,id:e.item.call_id,index:e.output_index}),o[Eq]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&[`web_search_call`,`file_search_call`,`code_interpreter_call`,`shell_call`,`local_shell_call`,`mcp_call`,`mcp_list_tools`,`mcp_approval_request`,`custom_tool_call`,`tool_search_call`,`tool_search_output`].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)s=e.response.id,a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`||e.type===`response.incomplete`){s=e.response.id;let t=Aq(e.response);if(r=kq(e.response.usage),e.response.text?.format?.type===`json_schema`&&t.text)try{o.parsed??=JSON.parse(t.text)}catch{}for(let[n,r]of Object.entries(e.response))n!==`id`&&(n===`output`?a[n]=t.response_metadata.output:a[n]=r)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index,...e.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});else if(e.type===`response.web_search_call.in_progress`||e.type===`response.web_search_call.searching`||e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.in_progress`||e.type===`response.file_search_call.searching`||e.type===`response.file_search_call.completed`||e.type===`response.image_generation_call.in_progress`||e.type===`response.image_generation_call.generating`||e.type===`response.image_generation_call.completed`){let[,t,r]=e.type.match(/^response\.(.*)\.([^.]+)$/)??[``,``,``];n={tool_outputs:{id:e.item_id,type:t,status:r}}}else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text,index:e.summary_index});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta,index:e.summary_index});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new Uu({text:t.map(e=>e.text).join(``),message:new nn({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},Nq=e=>{let t=$t.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=pG(()=>{try{let t=yG(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r,i=new Set,a=new Set,o=new Map,s=new Map;function*c(){if(!r)return;let e=r.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield r),r=void 0}let l=(e,t)=>{r||={type:`message`,role:n,content:[],...t?{phase:t}:{}},typeof r.content==`string`?r.content=r.content.length>0?[{type:`input_text`,text:r.content},...e]:[...e]:r.content.push(...e)},u=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},d=e=>{let t=pG(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},f=e=>{if(e.fileId){let t=gG(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=gG(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=vG(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,filename:t}}},p=e=>{let t=pG(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}];return{type:`reasoning`,...e.id?{id:e.id}:{},summary:n}},m=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:u(e.args)}),h=e=>{let t=u(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`){let e=pG(()=>{if(`extras`in n&&typeof n.extras==`object`&&n.extras!==null&&`phase`in n.extras)return n.extras.phase});l([{type:`input_text`,text:n.text}],e)}else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*c(),yield p(n);else if(n.type===`tool_call`){yield*c();let e=n.id??``;e&&(i.add(e),o.delete(e)),yield m(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=o.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),o.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*c();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield m(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*c(),yield h(n);else if(n.type!==`audio`)if(n.type===`file`){let e=f(n);e&&l([e])}else if(n.type===`image`){let e=d(n);e&&l([e])}else if(n.type===`video`){let e=f(n);e&&l([e])}else n.type===`text-plain`?n.text&&l([{type:`input_text`,text:n.text}]):n.type===`non_standard`&&t&&(yield*c(),yield n.value)}yield*c();for(let[e,t]of o){if(!e||i.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},Pq=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return Nq(e);let i=e.additional_kwargs,a=yG(e);if(a===`system`&&mG(n)&&(a=`developer`),a===`function`)throw Error(`Function messages are not supported in Responses API`);if(a===`tool`){let t=e;if(i?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(a===`assistant`){if(!t&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(e=>`type`in e))return r?.output;let n=[],a=i?.reasoning,o=!!a?.encrypted_content;if(a&&(!t||o)){let e=jq(a);n.push(e)}let{content:s}=e;if(i?.refusal&&(typeof s==`string`&&(s=[{type:`output_text`,text:s,annotations:[]}]),s=[...s,{type:`refusal`,refusal:i.refusal}]),typeof s==`string`||s.length>0){let r={type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:pG(()=>typeof s==`string`?s:s.flatMap(e=>{if(e.type===`text`){let t=e;return{type:`output_text`,text:t.text,annotations:(t.annotations??[]).map(Oq)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:pG(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[Tq],l=i?.[Eq];$t.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>BG(e,l)?{type:`custom_tool_call`,id:`call_id`in e&&typeof e.call_id==`string`?e.call_id:l?.[e.id??``]??``,call_id:e.id??``,input:e.args.input,name:e.name}:zG(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:c?.[e.id]}})):i?.tool_calls&&n.push(...i.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:c?.[e.id]}})));let u=r?.output?.length?r?.output:i.tool_outputs,d=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`,`shell_call`,`local_shell_call`];if(u!=null){let e=u?.filter(e=>d.includes(e.type));e.length>0&&n.push(...e)}return n}if(a===`user`||a===`system`||a===`developer`){if(typeof e.content==`string`)return{type:`message`,role:a,content:e.content};let t=[],n=e.content.flatMap(e=>{if(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),ye(e)){if(e.type===`file`){let t=gG(e);if(e.source_type===`url`)return{type:`input_file`,file_url:e.url,...t?{filename:t}:{}};if(e.source_type===`id`)return{type:`input_file`,file_id:e.id,...t?{filename:t}:{}};if(e.source_type===`base64`)return{type:`input_file`,file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:vG(e)}}return De(e,uq)}return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:pG(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:pG(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]});return n.length>0&&t.push({type:`message`,role:a,content:n}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*Fq(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=new Map,a=new Map,o=0,s=!1,c,l,u,d,f=new Set,p=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}},m=function*(){s||(s=!0,yield{event:`message-start`,id:c})},h=function*(e){if(f.has(e))return;let t=i.get(e);t&&(f.add(e),yield{event:`content-block-finish`,index:e,content:xE(t)})};for await(let t of e){if(t.type===`response.created`){c=t.response.id,yield*m(),yield{event:`provider`,provider:r,name:`response.created`,payload:{model:t.response.model,id:t.response.id}};continue}if(t.type===`response.output_text.delta`){yield*m();let{index:e,isNew:n}=p(`text:${t.output_index}:${t.content_index}`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let r=i.get(e);r.text=(r.text??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:t.delta}};continue}if(t.type===`response.reasoning_summary_text.delta`){yield*m();let{index:e,isNew:n}=p(`reasoning:${t.output_index}:${t.summary_index}`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let r=i.get(e);r.reasoning=(r.reasoning??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:t.delta}};continue}if(t.type===`response.output_item.added`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`custom_tool_call`,r=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:a,isNew:o}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index,...n?{isCustomTool:!0}:{}});if(o&&(yield{event:`content-block-start`,index:a,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index}}),r){let e=i.get(a);yield{event:`content-block-delta`,index:a,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:e.args}}}}continue}if(t.type===`response.function_call_arguments.delta`||t.type===`response.custom_tool_call_input.delta`){yield*m();let{index:e,isNew:n}=p(`tool:${t.output_index}`,{type:`tool_call_chunk`,args:``,index:t.output_index,...t.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});n&&(yield{event:`content-block-start`,index:e,content:{type:`tool_call_chunk`,args:``,index:t.output_index}});let r=i.get(e);r.args=(r.args??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...r.id==null?{}:{id:r.id},...r.name==null?{}:{name:r.name},args:r.args}}};continue}if(t.type===`response.output_item.done`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:r,isNew:a}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index});if(a)yield{event:`content-block-start`,index:r,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index}};else{let e=i.get(r);e.args=n,e.id=t.item.call_id,e.name=t.item.name}yield*h(r);continue}if(t.type===`response.completed`||t.type===`response.incomplete`){yield*m(),c=t.response.id,u=Iq(t.response.status,t.type),d={model_provider:r,id:t.response.id,model:t.response.model,status:t.response.status},n&&t.response.usage&&(l=kq(t.response.usage),yield{event:`usage`,usage:l});continue}t.type!==`response.image_generation_call.partial_image`&&(yield*m(),yield{event:`provider`,provider:r,name:t.type,payload:t})}s||(yield{event:`message-start`});for(let[e]of i)f.has(e)||(yield*h(e));yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function Iq(e,t){return t===`response.incomplete`?`length`:e===`completed`?`stop`:e===`incomplete`?`length`:`stop`}var Lq=class extends lq{constructor(e,t){super(cq(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:PG(e?.tool_choice)?e?.tool_choice:(()=>{let t=jG(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:Pq({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:Aq(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:Pq({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t),i=this.streamUsage??t.streamUsage;yield*Fq(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(r,t.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:Pq({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);try{for await(let e of r){if(t.signal?.aborted)return;let r=Mq(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}catch(e){throw fG(e)}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw fG(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(MG(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(FG(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(dT(r)){let e={};for(let[t,n]of Object.entries(r))t!==`type`&&t!==`function`&&(e[t]=n);n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...e})}else IG(r)&&n.push(VG(r));return n}},Rq=class extends Lq{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,..._q}}get lc_secrets(){return{...super.lc_secrets,...vq}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...yq]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=bq(e,t);super(n),xq.call(this,n)}_getClientOptions(e){return Sq.call(this,e)}toJSON(){return Cq.call(this,super.toJSON())}},zq=class e extends lq{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}fields;constructor(e,t){let n=cq(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Lq(n),this.completions=n?.completions??new gq(n)}_useResponsesApi(e){let t=e?.tools?.some(MG),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(IG)||e?.tools?.some(FG);return this.useResponsesApi||t||n||r||bG(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamChatModelEvents(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(t),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(t),n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}},Bq=class extends zq{azureOpenAIApiVersion;azureOpenAIApiKey;azureADTokenProvider;azureOpenAIApiInstanceName;azureOpenAIApiDeploymentName;azureOpenAIBasePath;azureOpenAIEndpoint;_llmType(){return`azure_openai`}get lc_aliases(){return{...super.lc_aliases,..._q}}get lc_secrets(){return{...super.lc_secrets,...vq}}get lc_serializable_keys(){return[...super.lc_serializable_keys,...yq]}getLsParams(e){let t=super.getLsParams(e);return t.ls_provider=`azure`,t}constructor(e,t){let n=bq(e,t);super({...n,completions:new wq(n),responses:new Rq(n)}),xq.call(this,n)}_getStructuredOutputMethod(e){let t={...e};return this.model.startsWith(`gpt-4o`)&&t?.method===void 0?`functionCalling`:super._getStructuredOutputMethod(t)}toJSON(){return Cq.call(this,super.toJSON())}};B({action:jA([B({type:UA(`screenshot`)}),B({type:UA(`click`),x:gA(),y:gA(),button:VA([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),B({type:UA(`double_click`),x:gA(),y:gA(),button:VA([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),B({type:UA(`drag`),path:OA(B({x:gA(),y:gA()}))}),B({type:UA(`keypress`),keys:OA(z())}),B({type:UA(`move`),x:gA(),y:gA()}),B({type:UA(`scroll`),x:gA(),y:gA(),scroll_x:gA(),scroll_y:gA()}),B({type:UA(`type`),text:z()}),B({type:UA(`wait`),duration:gA().optional()})])}),jA([B({type:UA(`exec`),command:OA(z()),env:zA(z(),z()).optional(),working_directory:z().optional(),timeout_ms:gA().optional(),user:z().optional()})]),B({commands:OA(z()).describe(`Array of shell commands to execute`),timeout_ms:gA().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:gA().optional().describe(`Optional maximum number of characters to return from each command`)}),jA([B({type:UA(`create_file`),path:z(),diff:z()}),B({type:UA(`update_file`),path:z(),diff:z()}),B({type:UA(`delete_file`),path:z()})]);function Vq(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(Vq):typeof t[e]==`object`&&t[e]!==null&&(t[e]=Vq(t[e])));return t}return e}function Hq(e){let{$schema:t,...n}=Vq(t_(e)||yb(e)?ox(e):e);return n}function Uq(e){let{$schema:t,...n}=Vq(e);return n}function Wq(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))Wq(i,t,[...n,e]);r.items&&Wq(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>Wq(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&Wq(r.additionalProperties,t,[...n,`additionalProperties`])}var Gq=`__gemini_function_call_thought_signatures__`,Kq=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,qq=e=>e();function Jq(e){return rn.isInstance(e)?e.role:e.type}function Yq(e){switch(e){case`supervisor`:case`ai`:case`model`:return`model`;case`system`:return`system`;case`human`:return`user`;case`tool`:case`function`:return`function`;default:throw Error(`Unknown / unsupported author: ${e}`)}}function Xq(e){if(`mimeType`in e&&`data`in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if(`mimeType`in e&&`fileUri`in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw Error(`Invalid media content`)}function Zq(e,t){return t.map(e=>en(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function Qq(e,t){if(`data`in e&&e.data!==void 0){let n=e.data instanceof Uint8Array?btoa(String.fromCharCode(...e.data)):e.data;return{inlineData:{mimeType:e.mimeType||t,data:n}}}if(`url`in e&&e.url!==void 0){let n=Ee({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mimeType||t,fileUri:e.url}}}throw`fileId`in e&&e.fileId!==void 0?Error(`ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead.`):Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(e)}`)}function $q(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=Ee({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=Ee({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=Ee({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function eJ(e,t){if(ye(e))return De(e,$q(t));if(e.type===`text`)return{text:e.text};if(e.type===`executableCode`)return{executableCode:e.executableCode};if(e.type===`codeExecutionResult`)return{codeExecutionResult:e.codeExecutionResult};if(e.type===`image_url`){if(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return Xq(e);else if(e.type===`image`)return Qq(e,`image/png`);else if(e.type===`video`)return Qq(e,`video/mp4`);else if(e.type===`audio`)return Qq(e,`audio/mpeg`);else if(e.type===`file`)return Qq(e,`application/octet-stream`);else if(e.type===`text-plain`)return`text`in e&&typeof e.text==`string`?{text:e.text}:Qq(e,`text/plain`);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(e.type===`thinking`){let t=e;return{text:t.thinking,thought:!0,...t.signature?{thoughtSignature:t.signature}:{}}}else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function tJ(e,t,n,r){if(wt(e)){let r=e.name??Zq(e,n);if(r===void 0)throw Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let i=Array.isArray(e.content)?e.content.map(e=>eJ(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let i=[],a=[];typeof e.content==`string`&&e.content&&a.push({text:e.content}),Array.isArray(e.content)&&a.push(...e.content.map(e=>eJ(e,t)).filter(e=>e!==void 0));let o=e.additional_kwargs?.[Gq];return en(e)&&e.tool_calls?.length&&(i=e.tool_calls.map(e=>{let t=qq(()=>{if(e.id){let t=o?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?Kq:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...a,...i]}function nJ(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!_t(a))throw Error(`Unsupported message input`);let s=Jq(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=Yq(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=tJ(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let d=c;(d===`function`||d===`system`&&!n)&&(d=`user`);let f={role:d,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function rJ(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r?.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:yr()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new $t({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[Gq]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function iJ(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:yr()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=``;o&&typeof o==`string`?c=o:Array.isArray(o)&&(c=o.find(e=>`text`in e)?.text??``);let l=[];a&&l.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let u=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new Uu({text:c,message:new nn({content:o||``,name:r?r.role:void 0,tool_call_chunks:l,additional_kwargs:{[Gq]:u},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function aJ(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(Sk(e)){let t=Hq(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(Wq(t,e.name),{name:e.name,description:e.description,parameters:t})}if(dT(e)){let t=Uq(e.function.parameters);return Wq(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function oJ(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}async function*sJ(e,t={}){let n=t.streamUsage??!0,r=new Map,i=new Map,a=0,o=!1,s,c=`stop`,l=(e,t)=>{let n=i.get(e);if(n!==void 0)return{index:n,isNew:!1};let o=a++;return i.set(e,o),r.set(o,{...t}),{index:o,isNew:!0}};for await(let i of e){o||(o=!0,yield{event:`message-start`}),n&&`usageMetadata`in i&&i.usageMetadata&&(s=oJ(i.usageMetadata,t.model??``),yield{event:`usage`,usage:s});let e=i.candidates?.[0];e?.finishReason&&(c=cJ(e.finishReason));let a=e?.content?.parts;if(!a)continue;let u=0;for(let e of a)if(`text`in e&&e.text)if(`thought`in e&&e.thought){let{index:t,isNew:n}=l(`reasoning`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`reasoning`,reasoning:``}});let i=r.get(t);i.reasoning=(i.reasoning??``)+e.text,yield{event:`content-block-delta`,index:t,delta:{type:`reasoning-delta`,reasoning:e.text}}}else{let{index:t,isNew:n}=l(`text`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:t,content:{type:`text`,text:``}});let i=r.get(t);i.text=(i.text??``)+e.text,yield{event:`content-block-delta`,index:t,delta:{type:`text-delta`,text:e.text}}}else if(`functionCall`in e&&e.functionCall){let t=`tool:${u}`,n=JSON.stringify(e.functionCall.args??{}),{index:i,isNew:a}=l(t,{type:`tool_call_chunk`,name:e.functionCall.name,args:``,index:u});a&&(yield{event:`content-block-start`,index:i,content:{type:`tool_call_chunk`,name:e.functionCall.name,args:``,index:u}});let o=r.get(i);o.args=n,yield{event:`content-block-delta`,index:i,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,name:o.name,args:o.args}}},u+=1}}for(let[e,t]of r)yield{event:`content-block-finish`,index:e,content:xE(t)};yield{event:`message-finish`,reason:c,...s?{usage:s}:{},responseMetadata:{model_provider:`google-genai`}}}function cJ(e){switch(e.toLowerCase()){case`max_tokens`:case`max-token`:case`max_token`:return`length`;case`safety`:case`recitation`:case`language`:case`blocklist`:case`prohibited_content`:case`prohibited-content`:case`spii`:case`image_safety`:case`image-safety`:case`image_prohibited_content`:case`image-prohibited-content`:case`image_recitation`:case`image-recitation`:return`content_filter`;default:return`stop`}}var lJ=class extends _T{static lc_name(){return`GoogleGenerativeAIToolsOutputParser`}lc_namespace=[`langchain`,`google_genai`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new yT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await a_(this.zodSchema,e);if(t.success)return t.data;throw new yT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},uJ;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(uJ||={});var dJ;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(dJ||={});var fJ;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(fJ||={});var pJ=[`user`,`model`,`function`,`system`],mJ;(function(e){e.HARM_CATEGORY_UNSPECIFIED=`HARM_CATEGORY_UNSPECIFIED`,e.HARM_CATEGORY_HATE_SPEECH=`HARM_CATEGORY_HATE_SPEECH`,e.HARM_CATEGORY_SEXUALLY_EXPLICIT=`HARM_CATEGORY_SEXUALLY_EXPLICIT`,e.HARM_CATEGORY_HARASSMENT=`HARM_CATEGORY_HARASSMENT`,e.HARM_CATEGORY_DANGEROUS_CONTENT=`HARM_CATEGORY_DANGEROUS_CONTENT`,e.HARM_CATEGORY_CIVIC_INTEGRITY=`HARM_CATEGORY_CIVIC_INTEGRITY`})(mJ||={});var hJ;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED=`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,e.BLOCK_LOW_AND_ABOVE=`BLOCK_LOW_AND_ABOVE`,e.BLOCK_MEDIUM_AND_ABOVE=`BLOCK_MEDIUM_AND_ABOVE`,e.BLOCK_ONLY_HIGH=`BLOCK_ONLY_HIGH`,e.BLOCK_NONE=`BLOCK_NONE`})(hJ||={});var gJ;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(gJ||={});var _J;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(_J||={});var vJ;(function(e){e.FINISH_REASON_UNSPECIFIED=`FINISH_REASON_UNSPECIFIED`,e.STOP=`STOP`,e.MAX_TOKENS=`MAX_TOKENS`,e.SAFETY=`SAFETY`,e.RECITATION=`RECITATION`,e.LANGUAGE=`LANGUAGE`,e.BLOCKLIST=`BLOCKLIST`,e.PROHIBITED_CONTENT=`PROHIBITED_CONTENT`,e.SPII=`SPII`,e.MALFORMED_FUNCTION_CALL=`MALFORMED_FUNCTION_CALL`,e.OTHER=`OTHER`})(vJ||={});var yJ;(function(e){e.TASK_TYPE_UNSPECIFIED=`TASK_TYPE_UNSPECIFIED`,e.RETRIEVAL_QUERY=`RETRIEVAL_QUERY`,e.RETRIEVAL_DOCUMENT=`RETRIEVAL_DOCUMENT`,e.SEMANTIC_SIMILARITY=`SEMANTIC_SIMILARITY`,e.CLASSIFICATION=`CLASSIFICATION`,e.CLUSTERING=`CLUSTERING`})(yJ||={});var bJ;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(bJ||={});var xJ;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(xJ||={});var SJ=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},CJ=class extends SJ{constructor(e,t){super(e),this.response=t}},wJ=class extends SJ{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},TJ=class extends SJ{},EJ=class extends SJ{},DJ=`https://generativelanguage.googleapis.com`,OJ=`v1beta`,kJ=`0.24.1`,AJ=`genai-js`,jJ;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(jJ||={});var MJ=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||OJ,t=`${this.requestOptions?.baseUrl||DJ}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function NJ(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${AJ}/${kJ}`),t.join(` `)}async function PJ(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,NJ(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new TJ(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new TJ(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new TJ(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function FJ(e,t,n,r,i,a){let o=new MJ(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},BJ(a)),{method:`POST`,headers:await PJ(o),body:i})}}async function IJ(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await FJ(e,t,n,r,i,a);return LJ(s,c,o)}async function LJ(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){RJ(t,e)}return r.ok||await zJ(r,e),r}function RJ(e,t){let n=e;throw n.name===`AbortError`?(n=new EJ(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof wJ||e instanceof TJ||(n=new SJ(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function zJ(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new wJ(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function BJ(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function VJ(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),GJ(e.candidates[0]))throw new CJ(`${KJ(e)}`,e);return HJ(e)}else if(e.promptFeedback)throw new CJ(`Text not available. ${KJ(e)}`,e);return``},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),GJ(e.candidates[0]))throw new CJ(`${KJ(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),UJ(e)[0]}else if(e.promptFeedback)throw new CJ(`Function call not available. ${KJ(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),GJ(e.candidates[0]))throw new CJ(`${KJ(e)}`,e);return UJ(e)}else if(e.promptFeedback)throw new CJ(`Function call not available. ${KJ(e)}`,e)},e}function HJ(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
|
|
211
|
-
`+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function UJ(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var WJ=[vJ.RECITATION,vJ.SAFETY,vJ.LANGUAGE];function GJ(e){return!!e.finishReason&&WJ.includes(e.finishReason)}function KJ(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];GJ(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function qJ(e){return this instanceof qJ?(this.v=e,this):new qJ(e)}function JJ(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof qJ?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var YJ=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function XJ(e){let[t,n]=$J(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:QJ(t),response:ZJ(n)}}async function ZJ(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return VJ(eY(t));t.push(r)}}function QJ(e){return JJ(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield qJ(t.read());if(n)break;yield yield qJ(VJ(e))}})}function $J(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new SJ(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(YJ),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new SJ(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(YJ)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new EJ(`Request aborted when reading from the stream`):new SJ(`Error reading from the stream`),t})}}})}function eY(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function tY(e,t,n,r){return XJ(await IJ(t,jJ.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function nY(e,t,n,r){return{response:VJ(await(await IJ(t,jJ.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function rY(e){if(e!=null){if(typeof e==`string`)return{role:`system`,parts:[{text:e}]};if(e.text)return{role:`system`,parts:[e]};if(e.parts)return e.role?e:{role:`system`,parts:e.parts}}}function iY(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return aY(t)}function aY(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new SJ(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new SJ(`No content is provided for sending chat message.`);return r?t:n}function oY(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new TJ(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=iY(e);n.contents=[t]}return{generateContentRequest:n}}function sY(e){let t;return t=e.contents?e:{contents:[iY(e)]},e.systemInstruction&&(t.systemInstruction=rY(e.systemInstruction)),t}function cY(e){return typeof e==`string`||Array.isArray(e)?{content:iY(e)}:e}var lY=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],uY={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function dY(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new SJ(`First content should be with role 'user', got ${e}`);if(!pJ.includes(e))throw new SJ(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(pJ)}`);if(!Array.isArray(r))throw new SJ(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new SJ(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of lY)t in e&&(i[t]+=1);let a=uY[e];for(let t of lY)if(!a.includes(t)&&i[t]>0)throw new SJ(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function fY(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var pY=`SILENT_ERROR`,mY=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(dY(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=iY(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>nY(this._apiKey,this.model,r,i)).then(e=>{if(fY(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=KJ(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=iY(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=tY(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(pY)}).then(e=>e.response).then(e=>{if(fY(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=KJ(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==pY&&console.error(e)}),a}};async function hY(e,t,n,r){return(await IJ(t,jJ.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function gY(e,t,n,r){return(await IJ(t,jJ.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function _Y(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await IJ(t,jJ.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var vY=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes(`/`)?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=rY(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=sY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return nY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=sY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return tY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new mY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=oY(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return hY(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=cY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return gY(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return _Y(this.apiKey,this.model,e,n)}},yY=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new SJ(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new vY(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new TJ("Cached content must contain a `name` field.");if(!e.model)throw new TJ("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new TJ(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new vY(this.apiKey,r,n)}};function bY(e,t){let n=xY(e);return{tools:n,toolConfig:CY(n,t)}}function xY(e){let t=[],n=[];return e.forEach(e=>{if(Sk(e)){let[n]=aJ([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(dT(e)){let{functionDeclarations:n}=SY(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function SY(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:Vq(e.function.parameters)}]}}function CY(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:bJ.ANY,auto:bJ.AUTO,none:bJ.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:bJ.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var wY={"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}},TY=class extends EE{static lc_name(){return`ChatGoogleGenerativeAI`}lc_serializable=!0;get lc_secrets(){return{apiKey:`GOOGLE_API_KEY`}}lc_namespace=[`langchain`,`chat_models`,`google_genai`];get lc_aliases(){return{apiKey:`google_api_key`}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;thinkingConfig;client;get _isMultimodalModel(){return this.model.includes(`vision`)||this.model.startsWith(`gemini-1.5`)||this.model.startsWith(`gemini-2`)||this.model.startsWith(`gemma-3-`)&&!this.model.startsWith(`gemma-3-1b`)||this.model.startsWith(`gemini-3`)}constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e;if(super(n),this._addVersion(`@langchain/google-genai`,`2.2.0`),this.model=n.model.replace(/^models\//,``),this.maxOutputTokens=n.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=n.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=n.topP??this.topP,this.topP&&this.topP<0)throw Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=n.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=n.stopSequences??this.stopSequences,this.apiKey=n.apiKey??Pr(`GOOGLE_API_KEY`),!this.apiKey)throw Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=n.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=n.streaming??this.streaming,this.json=n.json,this.thinkingConfig=n.thinkingConfig??this.thinkingConfig,this.client=new yY(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:`application/json`}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:n.apiVersion,baseUrl:n.baseUrl,customHeaders:n.customHeaders}),this.streamUsage=n.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new yY(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent==`boolean`?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model===`gemini-1.0-pro-001`||this.model.startsWith(`gemini-pro-vision`)||this.model.startsWith(`gemini-1.0-pro-vision`)?!1:this.model!==`gemini-pro`}getLsParams(e){return{ls_provider:`google_genai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return`googlegenerativeai`}bindTools(e,t){return this.withConfig({tools:bY(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?bY(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{},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}:{},...e?.responseSchema?{responseSchema:e.responseSchema,responseMimeType:`application/json`}:{}}}}_buildGenerateContentRequest(e,t){let n=nJ(e,this._isMultimodalModel,this.useSystemInstruction,this.model),r=n,i;return n[0]?.role===`system`&&([i,...r]=n),{...this.invocationParams(t),...i?{systemInstruction:i}:{},contents:r}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let r=await this.completionWithRetry(this._buildGenerateContentRequest(e,t)),i;`usageMetadata`in r.response&&(i=oJ(r.response.usageMetadata,this.model));let a=rJ(r.response,{usageMetadata:i});return a.generations?.length>0&&await n?.handleLLMNewToken(a.generations[0]?.text??``),a}async*_streamChatModelEvents(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a=this.streamUsage!==!1&&t.streamUsage!==!1;yield*sJ(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(i,t.signal),{streamUsage:a,model:this.model})}async*_streamResponseChunks(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a,o=0,s=0,c=0,l=0;for await(let e of i){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){a=oJ(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;a.input_tokens=Math.max(0,t-o),o=t;let n=e.usageMetadata.candidatesTokenCount??0;a.output_tokens=Math.max(0,n-s),s=n;let r=e.usageMetadata.totalTokenCount??0;a.total_tokens=Math.max(0,r-c),c=r}let r=iJ(e,{usageMetadata:a,index:l});l+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return wY[this.model]??{}}withStructuredOutput(e,t){let n=e,r=t?.name,i=t?.method,a=t?.includeRaw;if(i===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let o,s;if(i===`functionCalling`){let e=r??`extract`,t;if(t_(n)||yb(n)){let r=Hq(n);t={name:e,description:r.description??`A function available to call.`,parameters:r}}else typeof n.name==`string`&&typeof n.parameters==`object`&&n.parameters!=null?(t=n,t.parameters=Vq(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:Vq(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=YT(n,e,lJ)}else{let e=Hq(n);o=this.withConfig({responseSchema:e}),s=JT(n)}return XT(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},EY=class extends _T{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new yT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.serializableSchema!==void 0){let e=await this.serializableSchema[`~standard`].validate(t);if(e.issues)throw new yT(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.issues)}`,JSON.stringify(t,null,2));return e.value}if(this.zodSchema===void 0)return t;let n=await a_(this.zodSchema,t);if(n.success)return n.data;throw new yT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?DY(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function DY(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}function OY(e){if(e)return e===`any`||e===`required`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var kY=B({cache_control:dj().optional().nullable(),defer_loading:bA().optional(),input_examples:OA(wA()).optional(),allowed_callers:OA(wA()).optional()}),AY={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 jY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function MY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function NY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function PY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function FY(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`?!(!(`url`in e.source)||typeof e.source.url!=`string`):!1}var IY={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=Ee({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},LY=e=>e();function RY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function zY(e){function*t(){for(let t of e)RY(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function BY(e){return typeof e==`string`?e:VY(e)}function VY(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function HY(e){return(e??``).split(`;`)[0].toLowerCase()}function UY(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function WY(e,t){let n=UY(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=UY(t,`citations`);r!==void 0&&(e.citations=r);let i=UY(t,`context`);i!==void 0&&(e.context=i);let a=UY(t,`title`);return a!==void 0&&(e.title=a),e}function GY(e,t){let n=UY(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function KY(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function qY(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:zY(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=LY(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(WY({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=HY(n.mimeType);if(r===`application/pdf`||r===``){t.push(WY({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=HY(n.mimeType);if(r===``||r===`application/pdf`)t.push(WY({type:`document`,source:{type:`base64`,data:BY(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(WY({type:`document`,source:{type:`text`,data:BY(n.data),media_type:`text/plain`}},e));else if(KY(r))t.push(WY({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:BY(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(GY({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(GY({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=HY(n.mimeType)||`image/png`;KY(r)&&t.push(GY({type:`image`,source:{type:`base64`,data:BY(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(WY({type:`document`,source:{type:`text`,data:BY(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function JY(e){let t=Ee({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,`Example: data:image/png;base64,/9j/4AAQSk...`,`Example: https://example.com/image.jpg`].join(`
|
|
211
|
+
`+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function UJ(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var WJ=[vJ.RECITATION,vJ.SAFETY,vJ.LANGUAGE];function GJ(e){return!!e.finishReason&&WJ.includes(e.finishReason)}function KJ(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];GJ(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function qJ(e){return this instanceof qJ?(this.v=e,this):new qJ(e)}function JJ(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof qJ?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var YJ=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function XJ(e){let[t,n]=$J(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:QJ(t),response:ZJ(n)}}async function ZJ(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return VJ(eY(t));t.push(r)}}function QJ(e){return JJ(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield qJ(t.read());if(n)break;yield yield qJ(VJ(e))}})}function $J(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new SJ(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(YJ),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new SJ(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(YJ)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new EJ(`Request aborted when reading from the stream`):new SJ(`Error reading from the stream`),t})}}})}function eY(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function tY(e,t,n,r){return XJ(await IJ(t,jJ.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function nY(e,t,n,r){return{response:VJ(await(await IJ(t,jJ.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function rY(e){if(e!=null){if(typeof e==`string`)return{role:`system`,parts:[{text:e}]};if(e.text)return{role:`system`,parts:[e]};if(e.parts)return e.role?e:{role:`system`,parts:e.parts}}}function iY(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return aY(t)}function aY(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new SJ(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new SJ(`No content is provided for sending chat message.`);return r?t:n}function oY(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new TJ(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=iY(e);n.contents=[t]}return{generateContentRequest:n}}function sY(e){let t;return t=e.contents?e:{contents:[iY(e)]},e.systemInstruction&&(t.systemInstruction=rY(e.systemInstruction)),t}function cY(e){return typeof e==`string`||Array.isArray(e)?{content:iY(e)}:e}var lY=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],uY={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function dY(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new SJ(`First content should be with role 'user', got ${e}`);if(!pJ.includes(e))throw new SJ(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(pJ)}`);if(!Array.isArray(r))throw new SJ(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new SJ(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of lY)t in e&&(i[t]+=1);let a=uY[e];for(let t of lY)if(!a.includes(t)&&i[t]>0)throw new SJ(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function fY(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var pY=`SILENT_ERROR`,mY=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(dY(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=iY(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>nY(this._apiKey,this.model,r,i)).then(e=>{if(fY(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=KJ(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=iY(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=tY(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(pY)}).then(e=>e.response).then(e=>{if(fY(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=KJ(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==pY&&console.error(e)}),a}};async function hY(e,t,n,r){return(await IJ(t,jJ.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function gY(e,t,n,r){return(await IJ(t,jJ.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function _Y(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await IJ(t,jJ.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var vY=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,t.model.includes(`/`)?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=rY(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=sY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return nY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=sY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return tY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new mY(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=oY(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return hY(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=cY(e),r=Object.assign(Object.assign({},this._requestOptions),t);return gY(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return _Y(this.apiKey,this.model,e,n)}},yY=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new SJ(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new vY(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new TJ("Cached content must contain a `name` field.");if(!e.model)throw new TJ("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new TJ(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new vY(this.apiKey,r,n)}};function bY(e,t){let n=xY(e);return{tools:n,toolConfig:CY(n,t)}}function xY(e){let t=[],n=[];return e.forEach(e=>{if(Sk(e)){let[n]=aJ([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(dT(e)){let{functionDeclarations:n}=SY(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function SY(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:Vq(e.function.parameters)}]}}function CY(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:bJ.ANY,auto:bJ.AUTO,none:bJ.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:bJ.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var wY={"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}},TY=class extends EE{static lc_name(){return`ChatGoogleGenerativeAI`}lc_serializable=!0;get lc_secrets(){return{apiKey:`GOOGLE_API_KEY`}}lc_namespace=[`langchain`,`chat_models`,`google_genai`];get lc_aliases(){return{apiKey:`google_api_key`}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;thinkingConfig;client;get _isMultimodalModel(){return this.model.includes(`vision`)||this.model.startsWith(`gemini-1.5`)||this.model.startsWith(`gemini-2`)||this.model.startsWith(`gemma-3-`)&&!this.model.startsWith(`gemma-3-1b`)||this.model.startsWith(`gemini-3`)}constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e;if(super(n),this._addVersion(`@langchain/google-genai`,`2.2.0`),this.model=n.model.replace(/^models\//,``),this.maxOutputTokens=n.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=n.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=n.topP??this.topP,this.topP&&this.topP<0)throw Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=n.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=n.stopSequences??this.stopSequences,this.apiKey=n.apiKey??Pr(`GOOGLE_API_KEY`),!this.apiKey)throw Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=n.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=n.streaming??this.streaming,this.json=n.json,this.thinkingConfig=n.thinkingConfig??this.thinkingConfig,this.client=new yY(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:`application/json`}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:n.apiVersion,baseUrl:n.baseUrl,customHeaders:n.customHeaders}),this.streamUsage=n.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new yY(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent==`boolean`?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model!==`gemini-1.0-pro-001`&&!this.model.startsWith(`gemini-pro-vision`)&&!this.model.startsWith(`gemini-1.0-pro-vision`)&&this.model!==`gemini-pro`}getLsParams(e){return{ls_provider:`google_genai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return`googlegenerativeai`}bindTools(e,t){return this.withConfig({tools:bY(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?bY(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{},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}:{},...e?.responseSchema?{responseSchema:e.responseSchema,responseMimeType:`application/json`}:{}}}}_buildGenerateContentRequest(e,t){let n=nJ(e,this._isMultimodalModel,this.useSystemInstruction,this.model),r=n,i;return n[0]?.role===`system`&&([i,...r]=n),{...this.invocationParams(t),...i?{systemInstruction:i}:{},contents:r}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let r=await this.completionWithRetry(this._buildGenerateContentRequest(e,t)),i;`usageMetadata`in r.response&&(i=oJ(r.response.usageMetadata,this.model));let a=rJ(r.response,{usageMetadata:i});return a.generations?.length>0&&await n?.handleLLMNewToken(a.generations[0]?.text??``),a}async*_streamChatModelEvents(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a=this.streamUsage!==!1&&t.streamUsage!==!1;yield*sJ(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(i,t.signal),{streamUsage:a,model:this.model})}async*_streamResponseChunks(e,t,n){let r=this._buildGenerateContentRequest(e,t),i=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(r,{signal:t?.signal});return e}),a,o=0,s=0,c=0,l=0;for await(let e of i){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){a=oJ(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;a.input_tokens=Math.max(0,t-o),o=t;let n=e.usageMetadata.candidatesTokenCount??0;a.output_tokens=Math.max(0,n-s),s=n;let r=e.usageMetadata.totalTokenCount??0;a.total_tokens=Math.max(0,r-c),c=r}let r=iJ(e,{usageMetadata:a,index:l});l+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return wY[this.model]??{}}withStructuredOutput(e,t){let n=e,r=t?.name,i=t?.method,a=t?.includeRaw;if(i===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let o,s;if(i===`functionCalling`){let e=r??`extract`,t;if(t_(n)||yb(n)){let r=Hq(n);t={name:e,description:r.description??`A function available to call.`,parameters:r}}else typeof n.name==`string`&&typeof n.parameters==`object`&&n.parameters!=null?(t=n,t.parameters=Vq(n.parameters),e=n.name):t={name:e,description:n.description??``,parameters:Vq(n)};let i=[{functionDeclarations:[t]}];o=this.bindTools(i).withConfig({allowedFunctionNames:[e]}),s=YT(n,e,lJ)}else{let e=Hq(n);o=this.withConfig({responseSchema:e}),s=JT(n)}return XT(o,s,a,a?`StructuredOutputRunnable`:`ChatGoogleGenerativeAIStructuredOutput`)}},EY=class extends _T{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`output_parsers`];returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}async _validateResult(e){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new yT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.serializableSchema!==void 0){let e=await this.serializableSchema[`~standard`].validate(t);if(e.issues)throw new yT(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.issues)}`,JSON.stringify(t,null,2));return e.value}if(this.zodSchema===void 0)return t;let n=await a_(this.zodSchema,t);if(n.success)return n.data;throw new yT(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?DY(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function DY(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}function OY(e){if(e)return e===`any`||e===`required`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var kY=B({cache_control:dj().optional().nullable(),defer_loading:bA().optional(),input_examples:OA(wA()).optional(),allowed_callers:OA(wA()).optional()}),AY={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 jY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function MY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function NY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`compaction`}function PY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function FY(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`&&!(!(`url`in e.source)||typeof e.source.url!=`string`)}var IY={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=Ee({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},LY=e=>e();function RY(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function zY(e){function*t(){for(let t of e)RY(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function BY(e){return typeof e==`string`?e:VY(e)}function VY(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function HY(e){return(e??``).split(`;`)[0].toLowerCase()}function UY(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function WY(e,t){let n=UY(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=UY(t,`citations`);r!==void 0&&(e.citations=r);let i=UY(t,`context`);i!==void 0&&(e.context=i);let a=UY(t,`title`);return a!==void 0&&(e.title=a),e}function GY(e,t){let n=UY(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function KY(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function qY(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:zY(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=LY(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(WY({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=HY(n.mimeType);if(r===`application/pdf`||r===``){t.push(WY({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=HY(n.mimeType);if(r===``||r===`application/pdf`)t.push(WY({type:`document`,source:{type:`base64`,data:BY(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(WY({type:`document`,source:{type:`text`,data:BY(n.data),media_type:`text/plain`}},e));else if(KY(r))t.push(WY({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:BY(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(GY({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(GY({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=HY(n.mimeType)||`image/png`;KY(r)&&t.push(GY({type:`image`,source:{type:`base64`,data:BY(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(WY({type:`document`,source:{type:`text`,data:BY(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function JY(e){let t=Ee({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,`Example: data:image/png;base64,/9j/4AAQSk...`,`Example: https://example.com/image.jpg`].join(`
|
|
212
212
|
|
|
213
213
|
`))}if(n.protocol===`http:`||n.protocol===`https:`)return{type:`url`,url:e};throw Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,`Example: data:image/png;base64,/9j/4AAQSk...`,`Example: https://example.com/image.jpg`].join(`
|
|
214
214
|
|
|
@@ -216,7 +216,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
216
216
|
`):[]}};dZ=new WeakMap,fZ=new WeakMap,pZ.NEWLINE_CHARS=new Set([`
|
|
217
217
|
`,`\r`]),pZ.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function mZ(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function hZ(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var gZ={off:0,error:200,warn:300,info:400,debug:500},_Z=(e,t,n)=>{if(e){if(zX(gZ,e))return e;SZ(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gZ))}`)}};function vZ(){}function yZ(e,t,n){return!t||gZ[e]>gZ[n]?vZ:t[e].bind(t)}var bZ={error:vZ,warn:vZ,info:vZ,debug:vZ},xZ=new WeakMap;function SZ(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return bZ;let r=xZ.get(t);if(r&&r[0]===n)return r[1];let i={error:yZ(`error`,t,n),warn:yZ(`warn`,t,n),info:yZ(`info`,t,n),debug:yZ(`debug`,t,n)};return xZ.set(t,[n,i]),i}var CZ=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),wZ,TZ=class e{constructor(e,t,n){this.iterator=e,wZ.set(this,void 0),this.controller=t,Y(this,wZ,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?SZ(r):console;async function*o(){if(i)throw new Z("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of EZ(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=VX(e.data)??e.data,r=n?.error?.type;throw new xX(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(yX(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new pZ,n=nZ(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new Z("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(yX(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(wZ=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,X(this,wZ,`f`)),new e(()=>i(n),this.controller,X(this,wZ,`f`))]}toReadableStream(){let e=this,t;return eZ({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=cZ(JSON.stringify(n)+`
|
|
218
218
|
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*EZ(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new Z(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new Z(`Attempted to iterate over a response with no body`);let n=new OZ,r=new pZ,i=nZ(e.body);for await(let e of DZ(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*DZ(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?cZ(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=hZ(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var OZ=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
219
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=kZ(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function kZ(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function AZ(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return SZ(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):TZ.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:jZ(await n.json(),n):await n.text()})();return SZ(e).debug(`[${r}] response parsed`,CZ({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function jZ(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`request-id`),enumerable:!1})}var MZ,NZ=class e extends Promise{constructor(e,t,n=AZ){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,MZ.set(this,void 0),Y(this,MZ,e,`f`)}_thenUnwrap(t){return new e(X(this,MZ,`f`),this.responsePromise,async(e,n)=>jZ(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(X(this,MZ,`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)}};MZ=new WeakMap;var PZ,FZ=class{constructor(e,t,n,r){PZ.set(this,void 0),Y(this,PZ,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Z("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await X(this,PZ,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(PZ=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},IZ=class extends NZ{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await AZ(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},LZ=class extends FZ{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more
|
|
219
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=kZ(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function kZ(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function AZ(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return SZ(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):TZ.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:jZ(await n.json(),n):await n.text()})();return SZ(e).debug(`[${r}] response parsed`,CZ({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function jZ(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`request-id`),enumerable:!1})}var MZ,NZ=class e extends Promise{constructor(e,t,n=AZ){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,MZ.set(this,void 0),Y(this,MZ,e,`f`)}_thenUnwrap(t){return new e(X(this,MZ,`f`),this.responsePromise,async(e,n)=>jZ(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(X(this,MZ,`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)}};MZ=new WeakMap;var PZ,FZ=class{constructor(e,t,n,r){PZ.set(this,void 0),Y(this,PZ,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Z("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await X(this,PZ,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(PZ=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},IZ=class extends NZ{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await AZ(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},LZ=class extends FZ{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...LX(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...LX(this.options.query),after_id:e}}:null}},RZ=class extends FZ{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...LX(this.options.query),page:e}}:null}},zZ=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function BZ(e,t,n){return zZ(),new File(e,t??`unknown_file`,n)}function VZ(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}var HZ=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,UZ=async(e,t,n=!0)=>({...e,body:await KZ(e.body,t,n)}),WZ=new WeakMap;function GZ(e){let t=typeof e==`function`?e:e.fetch,n=WZ.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return WZ.set(t,r),r}var KZ=async(e,t,n=!0)=>{if(!await GZ(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>JZ(r,e,t,n))),r},qZ=e=>e instanceof Blob&&`name`in e,JZ=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,BZ([await n.blob()],VZ(n,r),i))}else if(HZ(n))e.append(t,BZ([await new Response(tZ(n)).blob()],VZ(n,r)));else if(qZ(n))e.append(t,BZ([n],VZ(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>JZ(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>JZ(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},YZ=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,XZ=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&YZ(e),ZZ=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function QZ(e,t,n){if(zZ(),e=await e,t||=VZ(e,!0),XZ(e))return e instanceof File&&t==null&&n==null?e:BZ([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(ZZ(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),BZ(await $Z(r),t,n)}let r=await $Z(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return BZ(r,t,n)}async function $Z(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(YZ(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(HZ(e))for await(let n of e)t.push(...await $Z(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${eQ(e)}`)}return t}function eQ(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var tQ=class{constructor(e){this._client=e}},nQ=Symbol.for(`brand.privateNullableHeaders`);function*rQ(e){if(!e)return;if(nQ in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():IX(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=IX(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var Q=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of rQ(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[nQ]:!0,values:t,nulls:n}};function iQ(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var aQ=Object.freeze(Object.create(null)),$=((e=iQ)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??aQ)??aQ)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new Z(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
220
220
|
`)}\n${a}\n${t}`)}return a})(iQ),oQ=class extends tQ{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/environments/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,RZ,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/environments/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/environments/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},sQ=Symbol(`anthropic.sdk.stainlessHelper`);function cQ(e){return typeof e==`object`&&!!e&&sQ in e}function lQ(e,t){let n=new Set;if(e)for(let t of e)cQ(t)&&n.add(t[sQ]);if(t){for(let e of t)if(cQ(e)&&n.add(e[sQ]),Array.isArray(e.content))for(let t of e.content)cQ(t)&&n.add(t[sQ])}return Array.from(n)}function uQ(e,t){let n=lQ(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function dQ(e){return cQ(e)?{"x-stainless-helper":e[sQ]}:{}}var fQ=class extends tQ{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,LZ,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}/content?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/files/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,UZ({body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},dQ(r.file),t?.headers])},this._client))}},pQ=class extends tQ{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/models/${e}?beta=true`,{...n,headers:Q([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,LZ,{query:r,...t,headers:Q([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},mQ=class extends tQ{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/user_profiles/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,RZ,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},hQ=class extends tQ{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/agents/${e}/versions?beta=true`,RZ,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},gQ=class extends tQ{constructor(){super(...arguments),this.versions=new hQ(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get($`/v1/agents/${e}?beta=true`,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/agents/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,RZ,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/agents/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};gQ.Versions=hQ;var _Q=class extends tQ{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post($`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:Q([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memories?beta=true`,RZ,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete($`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:Q([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},vQ=class extends tQ{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get($`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList($`/v1/memory_stores/${e}/memory_versions?beta=true`,RZ,{query:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post($`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:Q([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},yQ=class extends tQ{constructor(){super(...arguments),this.memories=new _Q(this._client),this.memoryVersions=new vQ(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post($`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,RZ,{query:r,...t,headers:Q([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete($`/v1/memory_stores/${e}?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post($`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:Q([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};yQ.Memories=_Q,yQ.MemoryVersions=vQ;var bQ={"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 xQ(e){return e?.output_format??e?.output_config?.format}function SQ(e,t,n){let r=xQ(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(t,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:CQ(e,t,n)}function CQ(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=wQ(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},"parsed_output",{value:i,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function wQ(e,t){let n=xQ(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new Z(`Failed to parse structured output: ${e}`)}}var TQ=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},EQ=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),EQ(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),EQ(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),EQ(e);break;case`delimiter`:return e=e.slice(0,e.length-1),EQ(e)}return e},DQ=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},OQ=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},kQ=e=>JSON.parse(OQ(DQ(EQ(TQ(e))))),AQ,jQ,MQ,NQ,PQ,FQ,IQ,LQ,RQ,zQ,BQ,VQ,HQ,UQ,WQ,GQ,KQ,qQ,JQ,YQ,XQ,ZQ,QQ,$Q,e$=`__json_buf`;function t$(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var n$=class e{constructor(e,t){AQ.add(this),this.messages=[],this.receivedMessages=[],jQ.set(this,void 0),MQ.set(this,null),this.controller=new AbortController,NQ.set(this,void 0),PQ.set(this,()=>{}),FQ.set(this,()=>{}),IQ.set(this,void 0),LQ.set(this,()=>{}),RQ.set(this,()=>{}),zQ.set(this,{}),BQ.set(this,!1),VQ.set(this,!1),HQ.set(this,!1),UQ.set(this,!1),WQ.set(this,void 0),GQ.set(this,void 0),KQ.set(this,void 0),YQ.set(this,e=>{if(Y(this,VQ,!0,`f`),yX(e)&&(e=new SX),e instanceof SX)return Y(this,HQ,!0,`f`),this._emit(`abort`,e);if(e instanceof Z)return this._emit(`error`,e);if(e instanceof Error){let t=new Z(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new Z(String(e)))}),Y(this,NQ,new Promise((e,t)=>{Y(this,PQ,e,`f`),Y(this,FQ,t,`f`)}),`f`),Y(this,IQ,new Promise((e,t)=>{Y(this,LQ,e,`f`),Y(this,RQ,t,`f`)}),`f`),X(this,NQ,`f`).catch(()=>{}),X(this,IQ,`f`).catch(()=>{}),Y(this,MQ,e,`f`),Y(this,KQ,t?.logger??console,`f`)}get response(){return X(this,WQ,`f`)}get request_id(){return X(this,GQ,`f`)}async withResponse(){Y(this,UQ,!0,`f`);let e=await X(this,NQ,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return Y(a,MQ,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},X(this,YQ,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{X(this,AQ,`m`,XQ).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)X(this,AQ,`m`,ZQ).call(this,e);if(i.controller.signal?.aborted)throw new SX;X(this,AQ,`m`,QQ).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(Y(this,WQ,e,`f`),Y(this,GQ,e?.headers.get(`request-id`),`f`),X(this,PQ,`f`).call(this,e),this._emit(`connect`))}get ended(){return X(this,BQ,`f`)}get errored(){return X(this,VQ,`f`)}get aborted(){return X(this,HQ,`f`)}abort(){this.controller.abort()}on(e,t){return(X(this,zQ,`f`)[e]||(X(this,zQ,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=X(this,zQ,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(X(this,zQ,`f`)[e]||(X(this,zQ,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Y(this,UQ,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){Y(this,UQ,!0,`f`),await X(this,IQ,`f`)}get currentMessage(){return X(this,jQ,`f`)}async finalMessage(){return await this.done(),X(this,AQ,`m`,qQ).call(this)}async finalText(){return await this.done(),X(this,AQ,`m`,JQ).call(this)}_emit(e,...t){if(X(this,BQ,`f`))return;e===`end`&&(Y(this,BQ,!0,`f`),X(this,LQ,`f`).call(this));let n=X(this,zQ,`f`)[e];if(n&&(X(this,zQ,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!X(this,UQ,`f`)&&!n?.length&&Promise.reject(e),X(this,FQ,`f`).call(this,e),X(this,RQ,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!X(this,UQ,`f`)&&!n?.length&&Promise.reject(e),X(this,FQ,`f`).call(this,e),X(this,RQ,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,X(this,AQ,`m`,qQ).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{X(this,AQ,`m`,XQ).call(this),this._connected(null);let t=TZ.fromReadableStream(e,this.controller);for await(let e of t)X(this,AQ,`m`,ZQ).call(this,e);if(t.controller.signal?.aborted)throw new SX;X(this,AQ,`m`,QQ).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(jQ=new WeakMap,MQ=new WeakMap,NQ=new WeakMap,PQ=new WeakMap,FQ=new WeakMap,IQ=new WeakMap,LQ=new WeakMap,RQ=new WeakMap,zQ=new WeakMap,BQ=new WeakMap,VQ=new WeakMap,HQ=new WeakMap,UQ=new WeakMap,WQ=new WeakMap,GQ=new WeakMap,KQ=new WeakMap,YQ=new WeakMap,AQ=new WeakSet,qQ=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},JQ=function(){if(this.receivedMessages.length===0)throw new Z(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new Z(`stream ended without producing a content block with type=text`);return e.join(` `)},XQ=function(){this.ended||Y(this,jQ,void 0,`f`)},ZQ=function(e){if(this.ended)return;let t=X(this,AQ,`m`,$Q).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:t$(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(SQ(t,X(this,MQ,`f`),{logger:X(this,KQ,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:Y(this,jQ,t,`f`);break;case`content_block_start`:case`message_delta`:break}},QQ=function(){if(this.ended)throw new Z(`stream has ended, this shouldn't happen`);let e=X(this,jQ,`f`);if(!e)throw new Z(`request ended without sending any chunks`);return Y(this,jQ,void 0,`f`),SQ(e,X(this,MQ,`f`),{logger:X(this,KQ,`f`)})},$Q=function(e){let t=X(this,jQ,`f`);if(e.type===`message_start`){if(t)throw new Z(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new Z(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&t$(n)){let r=n[e$]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,e$,{value:r,enumerable:!1,writable:!0}),r)try{i.input=kQ(r)}catch(e){let t=new Z(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);X(this,YQ,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new TZ(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},r$=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},i$=`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:
|
|
221
221
|
1. Task Overview
|
|
222
222
|
The user's core request and success criteria
|
|
@@ -251,11 +251,11 @@ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
251
251
|
`:``)+`{`+Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `)+`}`}return t}var k1={"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},A1=4096;function j1(e){return e?Object.entries(k1).find(([t])=>e.startsWith(t))?.[1]??A1:A1}function M1(e){return!!(e.tools&&e.tools.length>0)}function N1(e){for(let t of e.messages??[])if(typeof t.content!=`string`){for(let e of t.content??[])if(typeof e==`object`&&e&&e.type===`document`&&typeof e.citations==`object`&&e.citations?.enabled)return!0}return!1}function P1(e){return!!(e.thinking&&(e.thinking.type===`enabled`||e.thinking.type===`adaptive`))}function F1(e){return!!e.context_management?.edits?.some(e=>e.type===`compact_20260112`)}function I1(e){return`input_schema`in e}function L1(e){return typeof e==`object`&&!!e&&`type`in e&&(`name`in e||`mcp_server_name`in e)&&typeof e.type==`string`&&[`text_editor_`,`computer_`,`bash_`,`web_search_`,`web_fetch_`,`str_replace_editor_`,`str_replace_based_edit_tool_`,`code_execution_`,`memory_`,`tool_search_`,`mcp_toolset`].some(t=>typeof e.type==`string`&&e.type.startsWith(t))}function R1(e,t,...n){return Array.from(new Set([...e??[],...t??[],...n.flatMap(e=>Array.from(e))]))}function z1(e){if(typeof e.content==`string`)return e.content;if(Array.isArray(e.content)&&e.content.length>=1&&`input`in e.content[0])return typeof e.content[0].input==`string`?e.content[0].input:JSON.stringify(e.content[0].input);if(Array.isArray(e.content)&&e.content.length>=1&&`text`in e.content[0]&&typeof e.content[0].text==`string`)return e.content[0].text}var B1=class extends EE{static lc_name(){return`ChatAnthropic`}get lc_secrets(){return{anthropicApiKey:`ANTHROPIC_API_KEY`,apiKey:`ANTHROPIC_API_KEY`}}get lc_aliases(){return{modelName:`model`}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName=`claude-sonnet-4-5-20250929`;model=`claude-sonnet-4-5-20250929`;invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:`disabled`};contextManagement;outputConfig;inferenceGeo;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};if(super(n??{}),this._addVersion(`@langchain/anthropic`,`1.3.29`),this.anthropicApiKey=n?.apiKey??n?.anthropicApiKey??Pr(`ANTHROPIC_API_KEY`),!this.anthropicApiKey&&!n?.createClient)throw Error(`Anthropic API key not found`);this.clientOptions=n?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=n?.anthropicApiUrl,this.modelName=n?.model??n?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=n?.invocationKwargs??{},this.topP=n?.topP??this.topP,this.temperature=n?.temperature??this.temperature,this.topK=n?.topK??this.topK,this.maxTokens=n?.maxTokens??j1(this.model),this.stopSequences=n?.stopSequences??this.stopSequences,this.streaming=n?.streaming??!1,this.streamUsage=n?.streamUsage??this.streamUsage,this.thinking=n?.thinking??this.thinking,this.contextManagement=n?.contextManagement??this.contextManagement,this.outputConfig=n?.outputConfig??this.outputConfig,this.inferenceGeo=n?.inferenceGeo??this.inferenceGeo,this.betas=n?.betas??this.betas,this.createClient=n?.createClient??(e=>new w1(e))}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`anthropic`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(e=>{if(Sk(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(L1(e)||I1(e))return e;if(dT(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Sk(e))return{name:e.name,description:e.description,input_schema:t_(e.schema)?ox(e.schema):e.schema,...e.extras?kY.parse(e.extras):{}};throw Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(e,t){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...t})}invocationParams(e){let t=OY(e?.tool_choice),n=e?.tools?.reduce((e,t)=>{if(typeof t==`object`&&`type`in t&&t.type in AY){let n=AY[t.type];if(!e.includes(n))return[...e,n]}return e},[]),r=(()=>{let t={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!t.format&&(t.format=e.outputFormat),Object.keys(t).length>0?t:void 0})(),i=this.contextManagement?.edits?.some(e=>e.type===`compact_20260112`)?[`compact-2026-01-12`]:[],a=rX(this.model,r),o={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:t,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:R1(this.betas,e?.betas,n??[],i,a),output_config:r,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return iX({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(o,aX({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),o}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,t,n){let r=this.invocationParams(t),i=$Y(e),a={...r,...i,stream:!0},o=!M1(a)&&!N1(a)&&!P1(a)&&!F1(a),s=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal});for await(let e of s){if(t.signal?.aborted){s.controller.abort();return}let r=this.streamUsage??t.streamUsage,i=oX(e,{streamUsage:r,coerceContentToString:o});if(!i)continue;let{chunk:a}=i,c=z1(a),l=new Uu({message:new nn({content:a.content,additional_kwargs:a.additional_kwargs,tool_call_chunks:a.tool_call_chunks,usage_metadata:r?a.usage_metadata:void 0,response_metadata:a.response_metadata,id:a.id}),text:c??``});yield l,await n?.handleLLMNewToken(c??``,void 0,void 0,void 0,void 0,{chunk:l})}}async*_streamChatModelEvents(e,t,n){let r=this.invocationParams(t),i=$Y(e),a={...r,...i,stream:!0},o=await this.createStreamWithRetry(a,{headers:t.headers,signal:t.signal}),s=this.streamUsage??t.streamUsage;yield*fX(async function*(e,t){for await(let n of e){if(t?.aborted){e.controller?.abort();return}yield n}}(o,t.signal),{streamUsage:s??!0})}async _generateNonStreaming(e,t,n){let r=$Y(e),{content:i,...a}=await this.completionWithRetry({...t,stream:!1,...r},n),o=sX(i,a),{role:s,type:c,...l}=a;return{generations:o,llmOutput:l}}async _generate(e,t,n){if(t.signal?.throwIfAborted(),this.stopSequences&&t.stop)throw Error(`"stopSequence" parameter found in input and default params`);let r=this.invocationParams(t);if(r.stream){let r,i=this._streamResponseChunks(e,t,n);for await(let e of i)r=r===void 0?e:r.concat(e);if(r===void 0)throw Error(`No chunks returned from Anthropic API.`);return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(e,r,{signal:t.signal,headers:t.headers})}async createStreamWithRetry(e,t){if(!this.streamingClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.call(async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...r,betas:n,...this.invocationKwargs,stream:!0},t):await this.streamingClient.messages.create({...r,...this.invocationKwargs,stream:!0},t)}catch(e){throw uX(e)}})}async completionWithRetry(e,t){if(!this.batchClient){let e=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...e,apiKey:this.apiKey,maxRetries:0})}let{betas:n,...r}=e;return this.caller.callWithOptions({signal:t.signal??void 0},async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...r,...this.invocationKwargs,betas:n},t):await this.batchClient.messages.create({...r,...this.invocationKwargs},t)}catch(e){throw uX(e)}})}_llmType(){return`anthropic`}get profile(){return dX[this.model]??{}}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`functionCalling`;if(s===`jsonMode`&&(console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`),s=`jsonSchema`),s===`jsonSchema`){r=JT(i);let e=D1(ox(i));n=this.withConfig({outputVersion:`v0`,outputConfig:{format:{type:`json_schema`,schema:e}},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:e}})}else if(s===`functionCalling`){let e=a??`extract`,t;if(t_(i)||yb(i)){let n=ox(i);t=[{name:e,description:n.description??`A function available to call.`,input_schema:n}]}else typeof i.name==`string`&&typeof i.description==`string`&&typeof i.input_schema==`object`&&i.input_schema!=null?(t=[i],e=i.name):t=[{name:e,description:i.description??``,input_schema:i}];if(r=YT(i,e,EY),this.thinking?.type===`enabled`||this.thinking?.type===`adaptive`){let e="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(e),n=this.withConfig({outputVersion:`v0`,tools:t,ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:ox(i)}}),n=n.pipe(t=>{if(!t.tool_calls||t.tool_calls.length===0)throw Error(e);return t})}else n=this.withConfig({outputVersion:`v0`,tools:t,tool_choice:{type:`tool`,name:e},ls_structured_output_format:{kwargs:{method:`functionCalling`},schema:ox(i)}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected 'functionCalling' or 'jsonSchema'`);return XT(n,r,o,o?`StructuredOutputRunnable`:`ChatAnthropicStructuredOutput`)}},V1=class extends B1{};NA(`command`,[B({command:UA(`view`),path:z()}),B({command:UA(`create`),path:z(),file_text:z()}),B({command:UA(`str_replace`),path:z(),old_str:z(),new_str:z()}),B({command:UA(`insert`),path:z(),insert_line:gA(),insert_text:z()}),B({command:UA(`delete`),path:z()}),B({command:UA(`rename`),old_path:z(),new_path:z()})]),NA(`command`,[B({command:UA(`view`),path:z(),view_range:LA([gA(),gA()]).optional()}),B({command:UA(`str_replace`),path:z(),old_str:z(),new_str:z()}),B({command:UA(`create`),path:z(),file_text:z()}),B({command:UA(`insert`),path:z(),insert_line:gA(),new_str:z()})]);var H1=LA([gA(),gA()]),U1=B({action:UA(`screenshot`)}),W1=B({action:UA(`left_click`),coordinate:H1}),G1=B({action:UA(`right_click`),coordinate:H1}),K1=B({action:UA(`middle_click`),coordinate:H1}),q1=B({action:UA(`double_click`),coordinate:H1}),J1=B({action:UA(`triple_click`),coordinate:H1}),Y1=B({action:UA(`left_click_drag`),start_coordinate:H1,end_coordinate:H1}),X1=B({action:UA(`left_mouse_down`),coordinate:H1}),Z1=B({action:UA(`left_mouse_up`),coordinate:H1}),Q1=B({action:UA(`scroll`),coordinate:H1,scroll_direction:VA([`up`,`down`,`left`,`right`]),scroll_amount:gA()}),$1=B({action:UA(`type`),text:z()}),e0=B({action:UA(`key`),key:z()}),t0=B({action:UA(`mouse_move`),coordinate:H1}),n0=B({action:UA(`hold_key`),key:z()}),r0=B({action:UA(`wait`),duration:gA().optional()}),i0=B({action:UA(`zoom`),region:LA([gA(),gA(),gA(),gA()])});NA(`action`,[U1,W1,G1,K1,q1,J1,Y1,X1,Z1,Q1,$1,e0,t0,n0,r0]),NA(`action`,[U1,W1,G1,K1,q1,J1,Y1,X1,Z1,Q1,$1,e0,t0,n0,r0,i0]),jA([B({command:z().describe(`The bash command to run`)}),B({restart:UA(!0).describe(`Set to true to restart the bash session`)})]);function a0(e,t){return new nn({content:e.content??``,additional_kwargs:e.thinking&&e.thinking!==``?{reasoning_content:e.thinking}:{},tool_call_chunks:e.tool_calls?.map(e=>({name:e.function.name,args:JSON.stringify(e.function.arguments),type:`tool_call_chunk`,index:0,id:yr()})),response_metadata:{...t?.responseMetadata,model_provider:`ollama`},usage_metadata:t?.usageMetadata})}function o0(e){let t=e.match(/^data:.*?;base64,(.*)$/);return t?t[1]:``}function s0(e){if(typeof e.content==`string`){if(e.tool_calls?.length){let t=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));return[{role:`assistant`,content:e.content,tool_calls:t}]}return[{role:`assistant`,content:e.content}]}let t=e.content.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>({role:`assistant`,content:e.text})),n;if(e.content.find(e=>e.type===`tool_use`)&&e.tool_calls?.length){let t=e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:e.args}}));t&&(n={role:`assistant`,tool_calls:t,content:``})}else if(e.content.find(e=>e.type===`tool_use`)&&!e.tool_calls?.length)throw Error(`'tool_use' content type is not supported without tool calls.`);return[...t,...n?[n]:[]]}function c0(e){return typeof e.content==`string`?[{role:`user`,content:e.content}]:e.content.map(e=>{if(e.type===`text`)return{role:`user`,content:e.text};if(e.type===`image_url`){if(typeof e.image_url==`string`)return{role:`user`,content:``,images:[o0(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url==`string`)return{role:`user`,content:``,images:[o0(e.image_url.url)]}}throw Error(`Unsupported content type: ${e.type}`)})}function l0(e){if(typeof e.content==`string`)return[{role:`system`,content:e.content}];if(e.content.every(e=>e.type===`text`&&typeof e.text==`string`))return e.content.map(e=>({role:`system`,content:e.text}));throw Error(`Unsupported content type(s): ${e.content.map(e=>e.type).join(`, `)}`)}function u0(e){if(typeof e.content!=`string`)throw Error(`Non string tool message content is not supported`);return[{role:`tool`,content:e.content}]}function d0(e){return e.flatMap(e=>{if([`human`,`generic`].includes(e._getType()))return c0(e);if(e._getType()===`ai`)return s0(e);if(e._getType()===`system`)return l0(e);if(e._getType()===`tool`)return u0(e);throw Error(`Unsupported message type: ${e._getType()}`)})}var f0=typeof globalThis<`u`&&globalThis||typeof self<`u`&&self||typeof global<`u`&&global||{},p0={searchParams:`URLSearchParams`in f0,iterable:`Symbol`in f0&&`iterator`in Symbol,blob:`FileReader`in f0&&`Blob`in f0&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:`FormData`in f0,arrayBuffer:`ArrayBuffer`in f0};function m0(e){return e&&DataView.prototype.isPrototypeOf(e)}if(p0.arrayBuffer)var h0=[`[object Int8Array]`,`[object Uint8Array]`,`[object Uint8ClampedArray]`,`[object Int16Array]`,`[object Uint16Array]`,`[object Int32Array]`,`[object Uint32Array]`,`[object Float32Array]`,`[object Float64Array]`],g0=ArrayBuffer.isView||function(e){return e&&h0.indexOf(Object.prototype.toString.call(e))>-1};function _0(e){if(typeof e!=`string`&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e===``)throw TypeError(`Invalid character in header field name: "`+e+`"`);return e.toLowerCase()}function v0(e){return typeof e!=`string`&&(e=String(e)),e}function y0(e){var t={next:function(){var t=e.shift();return{done:t===void 0,value:t}}};return p0.iterable&&(t[Symbol.iterator]=function(){return t}),t}function b0(e){this.map={},e instanceof b0?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){if(e.length!=2)throw TypeError(`Headers constructor: expected name/value pair to be length 2, found`+e.length);this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}b0.prototype.append=function(e,t){e=_0(e),t=v0(t);var n=this.map[e];this.map[e]=n?n+`, `+t:t},b0.prototype.delete=function(e){delete this.map[_0(e)]},b0.prototype.get=function(e){return e=_0(e),this.has(e)?this.map[e]:null},b0.prototype.has=function(e){return this.map.hasOwnProperty(_0(e))},b0.prototype.set=function(e,t){this.map[_0(e)]=v0(t)},b0.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},b0.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),y0(e)},b0.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),y0(e)},b0.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),y0(e)},p0.iterable&&(b0.prototype[Symbol.iterator]=b0.prototype.entries);function x0(e){if(!e._noBody){if(e.bodyUsed)return Promise.reject(TypeError(`Already read`));e.bodyUsed=!0}}function S0(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function C0(e){var t=new FileReader,n=S0(t);return t.readAsArrayBuffer(e),n}function w0(e){var t=new FileReader,n=S0(t),r=/charset=([A-Za-z0-9_-]+)/.exec(e.type),i=r?r[1]:`utf-8`;return t.readAsText(e,i),n}function T0(e){for(var t=new Uint8Array(e),n=Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join(``)}function E0(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function D0(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e==`string`?this._bodyText=e:p0.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:p0.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:p0.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():p0.arrayBuffer&&p0.blob&&m0(e)?(this._bodyArrayBuffer=E0(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):p0.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||g0(e))?this._bodyArrayBuffer=E0(e):this._bodyText=e=Object.prototype.toString.call(e):(this._noBody=!0,this._bodyText=``),this.headers.get(`content-type`)||(typeof e==`string`?this.headers.set(`content-type`,`text/plain;charset=UTF-8`):this._bodyBlob&&this._bodyBlob.type?this.headers.set(`content-type`,this._bodyBlob.type):p0.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`))},p0.blob&&(this.blob=function(){var e=x0(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw Error(`could not read FormData body as blob`);return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return x0(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(p0.blob)return this.blob().then(C0);throw Error(`could not read as ArrayBuffer`)},this.text=function(){var e=x0(this);if(e)return e;if(this._bodyBlob)return w0(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(T0(this._bodyArrayBuffer));if(this._bodyFormData)throw Error(`could not read FormData body as text`);return Promise.resolve(this._bodyText)},p0.formData&&(this.formData=function(){return this.text().then(j0)}),this.json=function(){return this.text().then(JSON.parse)},this}var O0=[`CONNECT`,`DELETE`,`GET`,`HEAD`,`OPTIONS`,`PATCH`,`POST`,`PUT`,`TRACE`];function k0(e){var t=e.toUpperCase();return O0.indexOf(t)>-1?t:e}function A0(e,t){if(!(this instanceof A0))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);t||={};var n=t.body;if(e instanceof A0){if(e.bodyUsed)throw TypeError(`Already read`);this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new b0(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!n&&e._bodyInit!=null&&(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||`same-origin`,(t.headers||!this.headers)&&(this.headers=new b0(t.headers)),this.method=k0(t.method||this.method||`GET`),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal||function(){if(`AbortController`in f0)return new AbortController().signal}(),this.referrer=null,(this.method===`GET`||this.method===`HEAD`)&&n)throw TypeError(`Body not allowed for GET or HEAD requests`);if(this._initBody(n),(this.method===`GET`||this.method===`HEAD`)&&(t.cache===`no-store`||t.cache===`no-cache`)){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,`$1_=`+new Date().getTime());else{var i=/\?/;this.url+=(i.test(this.url)?`&`:`?`)+`_=`+new Date().getTime()}}}A0.prototype.clone=function(){return new A0(this,{body:this._bodyInit})};function j0(e){var t=new FormData;return e.trim().split(`&`).forEach(function(e){if(e){var n=e.split(`=`),r=n.shift().replace(/\+/g,` `),i=n.join(`=`).replace(/\+/g,` `);t.append(decodeURIComponent(r),decodeURIComponent(i))}}),t}function M0(e){var t=new b0;return e.replace(/\r?\n[\t ]+/g,` `).split(`\r`).map(function(e){return e.indexOf(`
|
|
252
252
|
`)===0?e.substr(1,e.length):e}).forEach(function(e){var n=e.split(`:`),r=n.shift().trim();if(r){var i=n.join(`:`).trim();try{t.append(r,i)}catch(e){console.warn(`Response `+e.message)}}}),t}D0.call(A0.prototype);function N0(e,t){if(!(this instanceof N0))throw TypeError(`Please use the "new" operator, this DOM object constructor cannot be called as a function.`);if(t||={},this.type=`default`,this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw RangeError(`Failed to construct 'Response': The status provided (0) is outside the range [200, 599].`);this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText===void 0?``:``+t.statusText,this.headers=new b0(t.headers),this.url=t.url||``,this._initBody(e)}D0.call(N0.prototype),N0.prototype.clone=function(){return new N0(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new b0(this.headers),url:this.url})},N0.error=function(){var e=new N0(null,{status:200,statusText:``});return e.ok=!1,e.status=0,e.type=`error`,e};var P0=[301,302,303,307,308];N0.redirect=function(e,t){if(P0.indexOf(t)===-1)throw RangeError(`Invalid status code`);return new N0(null,{status:t,headers:{location:e}})};var F0=f0.DOMException;try{new F0}catch{F0=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},F0.prototype=Object.create(Error.prototype),F0.prototype.constructor=F0}function I0(e,t){return new Promise(function(n,r){var i=new A0(e,t);if(i.signal&&i.signal.aborted)return r(new F0(`Aborted`,`AbortError`));var a=new XMLHttpRequest;function o(){a.abort()}a.onload=function(){var e={statusText:a.statusText,headers:M0(a.getAllResponseHeaders()||``)};i.url.indexOf(`file://`)===0&&(a.status<200||a.status>599)?e.status=200:e.status=a.status,e.url=`responseURL`in a?a.responseURL:e.headers.get(`X-Request-URL`);var t=`response`in a?a.response:a.responseText;setTimeout(function(){n(new N0(t,e))},0)},a.onerror=function(){setTimeout(function(){r(TypeError(`Network request failed`))},0)},a.ontimeout=function(){setTimeout(function(){r(TypeError(`Network request timed out`))},0)},a.onabort=function(){setTimeout(function(){r(new F0(`Aborted`,`AbortError`))},0)};function s(e){try{return e===``&&f0.location.href?f0.location.href:e}catch{return e}}if(a.open(i.method,s(i.url),!0),i.credentials===`include`?a.withCredentials=!0:i.credentials===`omit`&&(a.withCredentials=!1),`responseType`in a&&(p0.blob?a.responseType=`blob`:p0.arrayBuffer&&(a.responseType=`arraybuffer`)),t&&typeof t.headers==`object`&&!(t.headers instanceof b0||f0.Headers&&t.headers instanceof f0.Headers)){var c=[];Object.getOwnPropertyNames(t.headers).forEach(function(e){c.push(_0(e)),a.setRequestHeader(e,v0(t.headers[e]))}),i.headers.forEach(function(e,t){c.indexOf(t)===-1&&a.setRequestHeader(t,e)})}else i.headers.forEach(function(e,t){a.setRequestHeader(t,e)});i.signal&&(i.signal.addEventListener(`abort`,o),a.onreadystatechange=function(){a.readyState===4&&i.signal.removeEventListener(`abort`,o)}),a.send(i._bodyInit===void 0?null:i._bodyInit)})}I0.polyfill=!0,f0.fetch||(f0.fetch=I0,f0.Headers=b0,f0.Request=A0,f0.Response=N0);var L0=`11434`,R0=`http://127.0.0.1:${L0}`,z0=`0.6.3`,B0=Object.defineProperty,V0=(e,t,n)=>t in e?B0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H0=(e,t,n)=>(V0(e,typeof t==`symbol`?t:t+``,n),n),U0=class e extends Error{constructor(t,n){super(t),this.error=t,this.status_code=n,this.name=`ResponseError`,Error.captureStackTrace&&Error.captureStackTrace(this,e)}},W0=class{constructor(e,t,n){H0(this,`abortController`),H0(this,`itr`),H0(this,`doneCallback`),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if(`error`in e)throw Error(e.error);if(yield e,e.done||e.status===`success`){this.doneCallback();return}}throw Error(`Did not receive done or success response in stream.`)}},G0=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,n=null;if(e.headers.get(`content-type`)?.includes(`application/json`))try{n=await e.json(),t=n.error||t}catch{console.log(`Failed to parse error response as JSON`)}else try{console.log(`Getting text from response`),t=await e.text()||t}catch{console.log(`Failed to get text from error response`)}throw new U0(t,e.status)};function K0(){if(typeof window<`u`&&window.navigator){let e=navigator;return`userAgentData`in e&&e.userAgentData?.platform?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<`u`)return`${process.arch} ${process.platform} Node.js/${process.version}`;return``}function q0(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}else if(Array.isArray(e))return Object.fromEntries(e);else return e||{}}var J0=(e,t)=>e[t],Y0=async(e,t,n={})=>{let r={"Content-Type":`application/json`,Accept:`application/json`,"User-Agent":`ollama-js/${z0} (${K0()})`};n.headers=q0(n.headers);try{let e=new URL(t);if(e.protocol===`https:`&&e.hostname===`ollama.com`){let e=typeof process==`object`&&process!==null?J0({},`OLLAMA_API_KEY`):void 0;!(n.headers.authorization||n.headers.Authorization)&&e&&(n.headers.Authorization=`Bearer ${e}`)}}catch(e){console.error(`error parsing url`,e)}let i=Object.fromEntries(Object.entries(n.headers).filter(([e])=>!Object.keys(r).some(t=>t.toLowerCase()===e.toLowerCase())));return n.headers={...r,...i},e(t,n)},X0=async(e,t,n)=>{let r=await Y0(e,t,{headers:n?.headers});return await G0(r),r},Z0=async(e,t,n,r)=>{let i=await Y0(e,t,{method:`POST`,body:(e=>typeof e==`object`&&!!e&&!Array.isArray(e))(n)?JSON.stringify(n):n,signal:r?.signal,headers:r?.headers});return await G0(i),i},Q0=async(e,t,n,r)=>{let i=await Y0(e,t,{method:`DELETE`,body:JSON.stringify(n),headers:r?.headers});return await G0(i),i},$0=async function*(e){let t=new TextDecoder(`utf-8`),n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0});let a=n.split(`
|
|
253
253
|
`);n=a.pop()??``;for(let e of a)try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}}n+=t.decode();for(let e of n.split(`
|
|
254
|
-
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},e2=e=>{if(!e)return R0;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:L0;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},t2=Object.defineProperty,n2=(e,t,n)=>t in e?t2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,r2=(e,t,n)=>(n2(e,typeof t==`symbol`?t:t+``,n),n),i2=class{constructor(e){r2(this,`config`),r2(this,`fetch`),r2(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=e2(e?.host??R0)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await Z0(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new W0(e,$0(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await Z0(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Q0(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await Z0(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await X0(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Z0(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Z0(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Z0(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await X0(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await X0(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await Z0(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await Z0(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new i2;var a2=class extends EE{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.2.7`),this.baseUrl=n.baseUrl??Pr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new i2({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>Gj(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>Gj(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){t.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?au(r,i.message):i.message;let i=new $t({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r=this.invocationParams(t),i=d0(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new Uu({text:o,message:a0(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Uu({text:``,message:new nn({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=ox(i);t_(i)||yb(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:t_(i)||yb(i)?o:i}}),r=YT(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=JT(i);let e=ox(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return XT(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},o2=t=>e.includes(t),s2=e=>t.includes(e),c2=e=>{let{executeQuery:n,search:r,grep:i,readFile:a}=e;return[bj(async({query:e,limit:t,groupByProcess:n})=>{let i=t??10,a=n??!0,o;try{o=await r(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
254
|
+
`).filter(e=>e!==``))try{yield JSON.parse(e)}catch{console.warn(`invalid json: `,e)}},e2=e=>{if(!e)return R0;let t=e.includes(`://`);e.startsWith(`:`)&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let n=new URL(e),r=n.port;r||=t?n.protocol===`https:`?`443`:`80`:L0;let i=``;n.username&&(i=n.username,n.password&&(i+=`:${n.password}`),i+=`@`);let a=`${n.protocol}//${i}${n.hostname}:${r}${n.pathname}`;return a.endsWith(`/`)&&(a=a.slice(0,-1)),a},t2=Object.defineProperty,n2=(e,t,n)=>t in e?t2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,r2=(e,t,n)=>(n2(e,typeof t==`symbol`?t:t+``,n),n),i2=class{constructor(e){r2(this,`config`),r2(this,`fetch`),r2(this,`ongoingStreamedRequests`,[]),this.config={host:``,headers:e?.headers},e?.proxy||(this.config.host=e2(e?.host??R0)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,r=await Z0(this.fetch,n,t,{signal:e.signal,headers:this.config.headers});if(!r.body)throw Error(`Missing body`);let i=new W0(e,$0(r.body),()=>{let e=this.ongoingStreamedRequests.indexOf(i);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(i),i}return await(await Z0(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!=`string`){let t=new Uint8Array(e),n=``,r=t.byteLength;for(let e=0;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}return e}async generate(e){return e.images&&=await Promise.all(e.images.map(this.encodeImage.bind(this))),this.processStreamableRequest(`generate`,e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&=await Promise.all(t.images.map(this.encodeImage.bind(this)));return this.processStreamableRequest(`chat`,e)}async create(e){return this.processStreamableRequest(`create`,{...e})}async pull(e){return this.processStreamableRequest(`pull`,{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest(`push`,{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Q0(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:`success`}}async copy(e){return await Z0(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:`success`}}async list(){return await(await X0(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Z0(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Z0(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Z0(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await X0(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await X0(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw Error(`Query is required`);return await(await Z0(this.fetch,`https://ollama.com/api/web_search`,{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw Error(`URL is required`);return await(await Z0(this.fetch,`https://ollama.com/api/web_fetch`,{...e},{headers:this.config.headers})).json()}};new i2;var a2=class extends EE{static lc_name(){return`ChatOllama`}model=`llama3`;numa;numCtx;numBatch;numGpu;mainGpu;lowVram;f16Kv;logitsAll;vocabOnly;useMmap;useMlock;embeddingOnly;numThread;numKeep;seed;numPredict;topK;topP;tfsZ;typicalP;repeatLastN;temperature;repeatPenalty;presencePenalty;frequencyPenalty;mirostat;mirostatTau;mirostatEta;penalizeNewline;streaming;format;keepAlive;client;checkOrPullModel=!1;baseUrl=`http://127.0.0.1:11434`;think;constructor(e,t){let n=typeof e==`string`?{...t??{},model:e}:e??{};super(n),this._addVersion(`@langchain/ollama`,`1.2.7`),this.baseUrl=n.baseUrl??Pr(`OLLAMA_BASE_URL`)??this.baseUrl,this.client=new i2({fetch:n.fetch,host:this.baseUrl,headers:n.headers}),this.model=n.model??this.model,this.numa=n.numa,this.numCtx=n.numCtx,this.numBatch=n.numBatch,this.numGpu=n.numGpu,this.mainGpu=n.mainGpu,this.lowVram=n.lowVram,this.f16Kv=n.f16Kv,this.logitsAll=n.logitsAll,this.vocabOnly=n.vocabOnly,this.useMmap=n.useMmap,this.useMlock=n.useMlock,this.embeddingOnly=n.embeddingOnly,this.numThread=n.numThread,this.numKeep=n.numKeep,this.seed=n.seed,this.numPredict=n.numPredict,this.topK=n.topK,this.topP=n.topP,this.tfsZ=n.tfsZ,this.typicalP=n.typicalP,this.repeatLastN=n.repeatLastN,this.temperature=n.temperature,this.repeatPenalty=n.repeatPenalty,this.presencePenalty=n.presencePenalty,this.frequencyPenalty=n.frequencyPenalty,this.mirostat=n.mirostat,this.mirostatTau=n.mirostatTau,this.mirostatEta=n.mirostatEta,this.penalizeNewline=n.penalizeNewline,this.streaming=n.streaming,this.format=n.format,this.keepAlive=n.keepAlive,this.think=n.think,this.checkOrPullModel=n.checkOrPullModel??this.checkOrPullModel}_llmType(){return`ollama`}async pull(e,t){let{stream:n,insecure:r,logProgress:i}={stream:!0,...t};if(n)for await(let t of await this.client.pull({model:e,insecure:r,stream:n}))i&&console.log(t);else{let t=await this.client.pull({model:e,insecure:r});i&&console.log(t)}}bindTools(e,t){return this.withConfig({tools:e.map(e=>Gj(e)),...t})}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`ollama`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.options?.temperature??void 0,ls_max_tokens:t.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(e=>Gj(e)):void 0}}async checkModelExistsOnMachine(e){let{models:t}=await this.client.list();return!!t.find(t=>t.name===e||t.name===`${e}:latest`)}async _generate(e,t,n){t.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r;for await(let i of this._streamResponseChunks(e,t,n))r=r?au(r,i.message):i.message;let i=new $t({id:r?.id,content:r?.content??``,additional_kwargs:r?.additional_kwargs,tool_calls:r?.tool_calls,response_metadata:r?.response_metadata,usage_metadata:r?.usage_metadata});return{generations:[{text:typeof i.content==`string`?i.content:``,message:i}]}}async*_streamResponseChunks(e,t,n){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let r=this.invocationParams(t),i=d0(e),a={input_tokens:0,output_tokens:0,total_tokens:0},o=await this.client.chat({...r,messages:i,stream:!0}),s;for await(let e of o){if(t.signal?.aborted){this.client.abort();return}let{message:r,...i}=e;a.input_tokens+=i.prompt_eval_count??0,a.output_tokens+=i.eval_count??0,a.total_tokens=a.input_tokens+a.output_tokens,s=i;let o=this.think?r.thinking??r.content??``:r.content??``,c=new Uu({text:o,message:a0(r)});yield c,await n?.handleLLMNewToken(o,void 0,void 0,void 0,void 0,{chunk:c})}yield new Uu({text:``,message:new nn({content:``,response_metadata:{...s,model_provider:`ollama`},usage_metadata:a})})}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e},s=t?.method??`jsonSchema`;if(s===`functionCalling`){let e=a??`extract`,t,o=ox(i);t_(i)||yb(i)?t={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(t=i,e=i.name):t={name:e,description:i.description??``,parameters:i},n=this.bindTools([{type:`function`,function:t}]).withConfig({ls_structured_output_format:{kwargs:{method:s},schema:t_(i)||yb(i)?o:i}}),r=YT(i,e)}else if(s===`jsonMode`||s===`jsonSchema`){r=JT(i);let e=ox(i);n=this.withConfig({format:s===`jsonMode`?`json`:e,ls_structured_output_format:{kwargs:{method:s},schema:e}})}else throw TypeError(`Unrecognized structured output method '${s}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return XT(n,r,o,o?`StructuredOutputRunnable`:`ChatOllamaStructuredOutput`)}},o2=e=>i.includes(e),s2=e=>a.includes(e),c2=e=>{let{executeQuery:t,search:n,grep:r,readFile:i}=e;return[bj(async({query:e,limit:t,groupByProcess:r})=>{let i=t??10,a=r??!0,o;try{o=await n(e,{limit:i,enrich:!0})}catch{return`Search is not available. Please load a repository first.`}if(o.length===0)return`No code found matching "${e}". Try different terms or use grep for exact patterns.`;let s=o.slice(0,i).map((e,t)=>{let n=e.nodeId||``,r=e.name||e.filePath?.split(`/`).pop()||`Unknown`,i=e.label||`File`,a=e.filePath||``,o=e.startLine?` (lines ${e.startLine}-${e.endLine})`:``,s=e.sources?.join(`+`)||`hybrid`,c=e.score?` [score: ${e.score.toFixed(2)}]`:``,l=``;if(e.connections){let t=(e.connections.outgoing||[]).filter(e=>e?.name).slice(0,3),n=(e.connections.incoming||[]).filter(e=>e?.name).slice(0,3),r=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},i=t.map(e=>r(e,`out`)),a=n.map(e=>r(e,`in`));(i.length||a.length)&&(l=`\n Connections: ${[...i,...a].join(`, `)}`)}let u=e.cluster||`Unclustered`,d=(e.processes||[]).filter(e=>e.id&&e.label);return{idx:t+1,nodeId:n,name:r,label:i,filePath:a,location:o,sources:s,score:c,connections:l,clusterLabel:u,processes:d}}),c=(e,t)=>{let n=t?.step?` (step ${t.step}/${t.stepCount??`?`})`:``;return`[${e.idx}] ${e.label}: ${e.name}${e.score}${n}\n ID: ${e.nodeId}\n File: ${e.filePath}${e.location}\n Cluster: ${e.clusterLabel}\n Found by: ${e.sources}${e.connections}`};if(!a)return`Found ${o.length} matches:\n\n${s.map(e=>c(e)).join(`
|
|
255
255
|
|
|
256
256
|
`)}`;let l=new Map,u=`__no_process__`;for(let e of s){if(e.processes.length===0){l.has(u)||l.set(u,{label:`No process`,entries:[]}),l.get(u).entries.push({result:e});continue}for(let t of e.processes)l.has(t.id)||l.set(t.id,{label:t.label,stepCount:t.stepCount,entries:[]}),l.get(t.id).entries.push({result:e,step:t.step,stepCount:t.stepCount})}let d=Array.from(l.entries()).sort((e,t)=>{let n=e[1].entries.length;return t[1].entries.length-n}),f=[];f.push(`Found ${o.length} matches grouped by process:`),f.push(``);for(let[e,t]of d){let n=t.stepCount?`, ${t.stepCount} steps`:``,r=e===u?`NO PROCESS (${t.entries.length} matches)`:`PROCESS: ${t.label} (${t.entries.length} matches${n})`;f.push(r),t.entries.forEach(n=>{let r=n.step?{id:e,label:t.label,step:n.step,stepCount:n.stepCount}:void 0;f.push(c(n.result,r))}),f.push(``)}return f.join(`
|
|
257
|
-
`).trim()},{name:`search`,description:`Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context.`,schema:B({query:z().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:bA().optional().nullable().describe(`Group results by process (default: true)`),limit:gA().optional().nullable().describe(`Max results to return (default: 10)`)})}),bj(async({query:e,cypher:
|
|
258
|
-
`);return`Semantic search for "${e}" (${t.length} results):\n\n${
|
|
257
|
+
`).trim()},{name:`search`,description:`Search for code by keywords or concepts. Combines keyword matching and semantic understanding. Groups results by process with cluster context.`,schema:B({query:z().describe(`What you are looking for (e.g., "authentication middleware", "database connection")`),groupByProcess:bA().optional().nullable().describe(`Group results by process (default: true)`),limit:gA().optional().nullable().describe(`Max results to return (default: 10)`)})}),bj(async({query:e,cypher:r})=>{try{if(r.includes(`{{QUERY_VECTOR}}`)){if(!e)return`Error: Your Cypher contains {{QUERY_VECTOR}} but you didn't provide a 'query' to embed. Add a natural language query.`;try{let t=await n(e,{limit:10,mode:`semantic`});if(t.length===0)return`Semantic search returned no results. Embeddings may not be generated yet.`;let r=t.map((e,t)=>`[${t+1}] ${e.label||`File`}: ${e.name||e.filePath?.split(`/`).pop()||`?`} (score: ${(e.score??0).toFixed(3)})\n File: ${e.filePath||`n/a`}`).join(`
|
|
258
|
+
`);return`Semantic search for "${e}" (${t.length} results):\n\n${r}`}catch{return`Semantic search not available. Embeddings may not be generated. Use a non-vector Cypher query instead.`}}let i=await t(r);if(i.length===0)return`Query returned no results.`;let a=i[0],o=typeof a==`object`&&!Array.isArray(a)?Object.keys(a):[];if(o.length>0){let e=`| ${o.join(` | `)} |`,t=`|${o.map(()=>`---`).join(`|`)}|`,n=i.slice(0,50).map(e=>`| ${o.map(t=>{let n=e[t];if(n==null)return``;if(typeof n==`object`)return JSON.stringify(n);let r=String(n).replace(/\\/g,`\\\\`).replace(/\|/g,`\\|`);return r.length>60?r.slice(0,57)+`...`:r}).join(` | `)} |`).join(`
|
|
259
259
|
`),r=i.length>50?`\n\n_(${i.length-50} more rows)_`:``;return`**${i.length} results:**\n\n${e}\n${t}\n${n}${r}`}let s=i.slice(0,50).map((e,t)=>`[${t+1}] ${JSON.stringify(e)}`),c=i.length>50?`\n... (${i.length-50} more)`:``;return`${i.length} results:\n${s.join(`
|
|
260
260
|
`)}${c}`}catch(e){return`Cypher error: ${e instanceof Error?e.message:String(e)}\n\nCheck your query syntax. Node tables: File, Folder, Function, Class, Interface, Method, CodeElement. Relation: CodeRelation with type property (CONTAINS, DEFINES, IMPORTS, CALLS). Example: MATCH (f:File)-[:CodeRelation {type: 'IMPORTS'}]->(g:File) RETURN f, g`}},{name:`cypher`,description:`Execute a Cypher query against the code graph. Use for structural queries like finding callers, tracing imports, class inheritance, or custom traversals.
|
|
261
261
|
|
|
@@ -273,20 +273,20 @@ Example queries:
|
|
|
273
273
|
For semantic+graph queries, include {{QUERY_VECTOR}} placeholder and provide a 'query' parameter:
|
|
274
274
|
CALL QUERY_VECTOR_INDEX('CodeEmbedding', 'code_embedding_idx', {{QUERY_VECTOR}}, 10) YIELD node AS emb, distance
|
|
275
275
|
WITH emb, distance WHERE distance < 0.5
|
|
276
|
-
MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The Cypher query to execute`),query:z().optional().nullable().describe(`Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})`)})}),bj(async({pattern:e,fileFilter:t,caseSensitive:n,maxResults:
|
|
277
|
-
`),
|
|
276
|
+
MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The Cypher query to execute`),query:z().optional().nullable().describe(`Natural language query to embed (required if cypher contains {{QUERY_VECTOR}})`)})}),bj(async({pattern:e,fileFilter:t,caseSensitive:n,maxResults:i})=>{try{try{new RegExp(e,n?`g`:`gi`)}catch(t){return`Invalid regex: ${e}. Error: ${t instanceof Error?t.message:String(t)}`}let a=i??100,o=t?`(?=.*${t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}).*${e}`:e,s=await r(o,a);if(s.length===0)return`No matches for "${e}"${t?` in files matching "${t}"`:``}`;let c=s.map(e=>`${e.filePath}:${e.line}: ${e.text}`).join(`
|
|
277
|
+
`),l=s.length>=a?`\n\n(Showing first ${a} results)`:``;return`Found ${s.length} matches:\n\n${c}${l}`}catch(e){return`Grep error: ${e instanceof Error?e.message:String(e)}`}},{name:`grep`,description:`Search for exact text patterns across all files using regex. Use for finding specific strings, error messages, TODOs, variable names, etc.`,schema:B({pattern:z().describe(`Regex pattern to search for (e.g., "TODO", "console\\.log", "API_KEY")`),fileFilter:z().optional().nullable().describe(`Only search files containing this string (e.g., ".ts", "src/api")`),caseSensitive:bA().optional().nullable().describe(`Case-sensitive search (default: false)`),maxResults:gA().optional().nullable().describe(`Max results (default: 100)`)})}),bj(async({filePath:e})=>{try{let t=await i(e),n=5e4;return t.length>n?`File: ${e} (${t.split(`
|
|
278
278
|
`).length} lines, truncated)\n\n${t.slice(0,n)}\n\n... [truncated]`:`File: ${e} (${t.split(`
|
|
279
|
-
`).length} lines)\n\n${t}`}catch(t){let n=t instanceof Error?t.message:String(t);return n.includes(`not found`)||n.includes(`404`)?`File not found: "${e}". Use grep to search for the correct path.`:`Error reading file: ${n}`}},{name:`read`,description:`Read the full content of a file. Use to see source code after finding files via search or grep.`,schema:B({filePath:z().describe(`File path to read (can be partial like "src/utils.ts")`)})}),bj(async()=>{try{let[e,
|
|
279
|
+
`).length} lines)\n\n${t}`}catch(t){let n=t instanceof Error?t.message:String(t);return n.includes(`not found`)||n.includes(`404`)?`File not found: "${e}". Use grep to search for the correct path.`:`Error reading file: ${n}`}},{name:`read`,description:`Read the full content of a file. Use to see source code after finding files via search or grep.`,schema:B({filePath:z().describe(`File path to read (can be partial like "src/utils.ts")`)})}),bj(async()=>{try{let[e,n,r,i]=await Promise.all([t(`
|
|
280
280
|
MATCH (c:Community)
|
|
281
281
|
RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
|
|
282
282
|
ORDER BY c.symbolCount DESC
|
|
283
283
|
LIMIT 200
|
|
284
|
-
`),
|
|
284
|
+
`),t(`
|
|
285
285
|
MATCH (p:Process)
|
|
286
286
|
RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount, p.communities AS communities
|
|
287
287
|
ORDER BY p.stepCount DESC
|
|
288
288
|
LIMIT 200
|
|
289
|
-
`),
|
|
289
|
+
`),t(`
|
|
290
290
|
MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b)
|
|
291
291
|
MATCH (a)-[:CodeRelation {type: 'MEMBER_OF'}]->(c1:Community)
|
|
292
292
|
MATCH (b)-[:CodeRelation {type: 'MEMBER_OF'}]->(c2:Community)
|
|
@@ -294,28 +294,28 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
294
294
|
RETURN c1.label AS \`from\`, c2.label AS \`to\`, COUNT(*) AS calls
|
|
295
295
|
ORDER BY calls DESC
|
|
296
296
|
LIMIT 15
|
|
297
|
-
`),
|
|
297
|
+
`),t(`
|
|
298
298
|
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
299
299
|
RETURN p.label AS label, COUNT(r) AS steps
|
|
300
300
|
ORDER BY steps DESC
|
|
301
301
|
LIMIT 10
|
|
302
|
-
`)]),a=e.map(e=>{let t=Array.isArray(e)?e[1]:e.label,n=Array.isArray(e)?e[3]:e.symbolCount,r=Array.isArray(e)?e[2]:e.cohesion,i=Array.isArray(e)?e[4]:e.description,a=r==null?``:Number(r).toFixed(2);return`| ${t||``} | ${n??``} | ${a} | ${i??``} |`}),o=
|
|
303
|
-
`)}catch(e){return`Overview error: ${e instanceof Error?e.message:String(e)}`}},{name:`overview`,description:`Codebase map showing all clusters and processes, plus cross-cluster dependencies.`,schema:B({})}),bj(async({target:e,type:
|
|
302
|
+
`)]),a=e.map(e=>{let t=Array.isArray(e)?e[1]:e.label,n=Array.isArray(e)?e[3]:e.symbolCount,r=Array.isArray(e)?e[2]:e.cohesion,i=Array.isArray(e)?e[4]:e.description,a=r==null?``:Number(r).toFixed(2);return`| ${t||``} | ${n??``} | ${a} | ${i??``} |`}),o=n.map(e=>{let t=Array.isArray(e)?e[1]:e.label,n=Array.isArray(e)?e[3]:e.stepCount,r=Array.isArray(e)?e[2]:e.type,i=Array.isArray(e)?e[4]:e.communities,a=Array.isArray(i)?i.length:+!!i;return`| ${t||``} | ${n??``} | ${r??``} | ${a} |`}),s=r.map(e=>`- ${Array.isArray(e)?e[0]:e.from} -> ${Array.isArray(e)?e[1]:e.to} (${Array.isArray(e)?e[2]:e.calls} calls)`),c=i.map(e=>`- ${Array.isArray(e)?e[0]:e.label} (${Array.isArray(e)?e[1]:e.steps} steps)`);return[`CLUSTERS (${e.length} total):`,`| Cluster | Symbols | Cohesion | Description |`,`| --- | --- | --- | --- |`,...a,``,`PROCESSES (${n.length} total):`,`| Process | Steps | Type | Clusters |`,`| --- | --- | --- | --- |`,...o,``,`CLUSTER DEPENDENCIES:`,...s.length>0?s:[`- None found`],``,`CRITICAL PATHS:`,...c.length>0?c:[`- None found`]].join(`
|
|
303
|
+
`)}catch(e){return`Overview error: ${e instanceof Error?e.message:String(e)}`}},{name:`overview`,description:`Codebase map showing all clusters and processes, plus cross-cluster dependencies.`,schema:B({})}),bj(async({target:e,type:n})=>{let r=e.replace(/'/g,`''`),i=n??null,a=null,o=null,s=null,c=(e,t,n)=>Array.isArray(e)?e[t]:e[n];if(!i||i===`process`){let e=`
|
|
304
304
|
MATCH (p:Process)
|
|
305
305
|
WHERE p.id = '${r}' OR p.label = '${r}'
|
|
306
306
|
RETURN p.id AS id, p.label AS label, p.processType AS type, p.stepCount AS stepCount
|
|
307
307
|
LIMIT 1
|
|
308
|
-
|
|
308
|
+
`,n=await t(e);n.length>0&&(a=n[0],i=`process`)}if(!i||i===`cluster`){let e=`
|
|
309
309
|
MATCH (c:Community)
|
|
310
310
|
WHERE c.id = '${r}' OR c.label = '${r}' OR c.heuristicLabel = '${r}'
|
|
311
311
|
RETURN c.id AS id, c.label AS label, c.cohesion AS cohesion, c.symbolCount AS symbolCount, c.description AS description
|
|
312
312
|
LIMIT 1
|
|
313
|
-
|
|
313
|
+
`,n=await t(e);n.length>0&&(o=n[0],i=`cluster`)}if(!i||i===`symbol`){let e=`
|
|
314
314
|
MATCH (n)
|
|
315
315
|
WHERE n.name = '${r}' OR n.id = '${r}' OR n.filePath = '${r}'
|
|
316
316
|
RETURN n.id AS id, n.name AS name, n.filePath AS filePath, label(n) AS nodeType
|
|
317
317
|
LIMIT 5
|
|
318
|
-
|
|
318
|
+
`,n=await t(e);n.length>0&&(s=n[0],i=`symbol`)}if(!i)return`Could not find "${e}" as a symbol, cluster, or process. Try search first.`;if(i===`process`){let e=c(a,0,`id`),n=c(a,1,`label`),r=c(a,2,`type`),i=c(a,3,`stepCount`),o=`
|
|
319
319
|
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process {id: '${e.replace(/'/g,`''`)}'})
|
|
320
320
|
RETURN s.name AS name, s.filePath AS filePath, r.step AS step
|
|
321
321
|
ORDER BY r.step
|
|
@@ -325,8 +325,8 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
325
325
|
RETURN DISTINCT c.id AS id, c.label AS label, c.description AS description
|
|
326
326
|
ORDER BY c.label
|
|
327
327
|
LIMIT 20
|
|
328
|
-
`,[l,u]=await Promise.all([
|
|
329
|
-
`)}if(i===`cluster`){let e=c(o,0,`id`),
|
|
328
|
+
`,[l,u]=await Promise.all([t(o),t(s)]),d=l.map(e=>{let t=c(e,0,`name`),n=c(e,1,`filePath`);return`- ${c(e,2,`step`)}. ${t} (${n||`n/a`})`}),f=u.map(e=>{let t=c(e,1,`label`),n=c(e,2,`description`);return`- ${t}${n?` — ${n}`:``}`});return[`PROCESS: ${n}`,`Type: ${r||`n/a`}`,`Steps: ${i??l.length}`,``,`STEPS:`,...d.length>0?d:[`- None found`],``,`CLUSTERS TOUCHED:`,...f.length>0?f:[`- None found`]].join(`
|
|
329
|
+
`)}if(i===`cluster`){let e=c(o,0,`id`),n=c(o,1,`label`),r=c(o,2,`cohesion`),i=c(o,3,`symbolCount`),a=c(o,4,`description`),s=`
|
|
330
330
|
MATCH (c:Community {id: '${e.replace(/'/g,`''`)}'})<-[:CodeRelation {type: 'MEMBER_OF'}]-(m)
|
|
331
331
|
RETURN m.name AS name, m.filePath AS filePath, label(m) AS nodeType
|
|
332
332
|
LIMIT 50
|
|
@@ -336,27 +336,27 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
336
336
|
RETURN DISTINCT p.id AS id, p.label AS label, p.stepCount AS stepCount
|
|
337
337
|
ORDER BY p.stepCount DESC
|
|
338
338
|
LIMIT 20
|
|
339
|
-
`,[u,d]=await Promise.all([
|
|
340
|
-
`)}if(i===`symbol`){let
|
|
341
|
-
MATCH (n:${a} {id: '${String(
|
|
339
|
+
`,[u,d]=await Promise.all([t(s),t(l)]),f=u.map(e=>{let t=c(e,0,`name`),n=c(e,1,`filePath`);return`- ${c(e,2,`nodeType`)}: ${t} (${n||`n/a`})`}),p=d.map(e=>`- ${c(e,1,`label`)} (${c(e,2,`stepCount`)} steps)`);return[`CLUSTER: ${n}`,`Symbols: ${i??u.length}`,`Cohesion: ${r==null?`n/a`:Number(r).toFixed(2)}`,`Description: ${a||`n/a`}`,``,`TOP MEMBERS:`,...f.length>0?f:[`- None found`],``,`PROCESSES TOUCHING THIS CLUSTER:`,...p.length>0?p:[`- None found`]].join(`
|
|
340
|
+
`)}if(i===`symbol`){let n=c(s,0,`id`),r=c(s,1,`name`),i=c(s,2,`filePath`),a=c(s,3,`nodeType`);if(!o2(a))return`Unknown node type "${a}" for symbol "${e}".`;let o=`
|
|
341
|
+
MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
|
|
342
342
|
MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
343
343
|
RETURN c.label AS label, c.description AS description
|
|
344
344
|
LIMIT 1
|
|
345
345
|
`,l=`
|
|
346
|
-
MATCH (n:${a} {id: '${String(
|
|
346
|
+
MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
|
|
347
347
|
MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
348
348
|
RETURN p.label AS label, r.step AS step, p.stepCount AS stepCount
|
|
349
349
|
ORDER BY r.step
|
|
350
350
|
`,u=`
|
|
351
|
-
MATCH (n:${a} {id: '${String(
|
|
351
|
+
MATCH (n:${a} {id: '${String(n).replace(/'/g,`''`)}'})
|
|
352
352
|
OPTIONAL MATCH (n)-[r1:CodeRelation]->(dst)
|
|
353
353
|
OPTIONAL MATCH (src)-[r2:CodeRelation]->(n)
|
|
354
354
|
RETURN
|
|
355
355
|
collect(DISTINCT {name: dst.name, type: r1.type, confidence: r1.confidence}) AS outgoing,
|
|
356
356
|
collect(DISTINCT {name: src.name, type: r2.type, confidence: r2.confidence}) AS incoming
|
|
357
357
|
LIMIT 1
|
|
358
|
-
`,[d,f,p]=await Promise.all([
|
|
359
|
-
`)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:B({target:z().describe(`Name or ID of a symbol, cluster, or process`),type:VA([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),bj(async({target:e,direction:
|
|
358
|
+
`,[d,f,p]=await Promise.all([t(o),t(l),t(u)]),m=d.length>0?c(d[0],0,`label`):`Unclustered`,h=d.length>0?c(d[0],1,`description`):``,g=f.map(e=>`- ${c(e,0,`label`)} (step ${c(e,1,`step`)}/${c(e,2,`stepCount`)??`?`})`),_=`None`;if(p.length>0){let e=p[0],t=Array.isArray(e)?e[0]:e.outgoing||[],n=Array.isArray(e)?e[1]:e.incoming||[],r=(t||[]).filter(e=>e&&e.name).slice(0,5),i=(n||[]).filter(e=>e&&e.name).slice(0,5),a=(e,t)=>{let n=e.confidence?Math.round(e.confidence*100):100;return t===`out`?`-[${e.type} ${n}%]-> ${e.name}`:`<-[${e.type} ${n}%]- ${e.name}`},o=r.map(e=>a(e,`out`)),s=i.map(e=>a(e,`in`));(o.length||s.length)&&(_=[...o,...s].join(`, `))}return[`SYMBOL: ${a} ${r}`,`ID: ${n}`,`File: ${i||`n/a`}`,`Cluster: ${m}${h?` — ${h}`:``}`,``,`PROCESSES:`,...g.length>0?g:[`- None found`],``,`CONNECTIONS:`,_].join(`
|
|
359
|
+
`)}return`Unable to explore "${e}".`},{name:`explore`,description:`Deep dive on a symbol, cluster, or process. Shows membership, participation, and connections.`,schema:B({target:z().describe(`Name or ID of a symbol, cluster, or process`),type:VA([`symbol`,`cluster`,`process`]).optional().nullable().describe(`Optional target type (auto-detected if omitted)`)})}),bj(async({target:e,direction:n,maxDepth:o,relationTypes:s,includeTests:c,minConfidence:l})=>{let u=Math.min(o??3,10),d=c??!1,f=l??.7,p=e=>{if(!e)return!1;let t=e.toLowerCase();return t.includes(`.test.`)||t.includes(`.spec.`)||t.includes(`__tests__`)||t.includes(`__mocks__`)||t.endsWith(`.test.ts`)||t.endsWith(`.test.tsx`)||t.endsWith(`.spec.ts`)||t.endsWith(`.spec.tsx`)},m=s&&s.length>0?s.filter(e=>s2(e)):[`CALLS`,`IMPORTS`,`EXTENDS`,`IMPLEMENTS`];if(m.length===0)return`No valid relation types provided. Valid types: ${a.join(`, `)}`;let h=m.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),g=e.includes(`/`),_=e.replace(/'/g,`''`),v=g?`
|
|
360
360
|
MATCH (n)
|
|
361
361
|
WHERE n.filePath IS NOT NULL AND n.filePath CONTAINS '${_}'
|
|
362
362
|
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
@@ -366,9 +366,9 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
366
366
|
WHERE n.name = '${_}'
|
|
367
367
|
RETURN n.id AS id, label(n) AS nodeType, n.filePath AS filePath
|
|
368
368
|
LIMIT 10
|
|
369
|
-
`,y;try{y=await
|
|
369
|
+
`,y;try{y=await t(v)}catch(t){return`Error finding target "${e}": ${t}`}if(!y||y.length===0)return`Could not find "${e}" in the codebase. Try using the search tool first to find the exact name.`;let b=y.map(e=>Array.isArray(e)?e[2]:e.filePath).filter(Boolean);if(y.length>1&&!e.includes(`/`))return`⚠️ AMBIGUOUS TARGET: Multiple files named "${e}" found:\n\n${b.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
370
370
|
`)}\n\nPlease specify which file you mean by using a more specific path, e.g.:\n- impact("${b[0].split(`/`).slice(-3).join(`/`)}")\n- impact("${b[1]?.split(`/`).slice(-3).join(`/`)||b[0]}")`;let x=y[0];if(e.includes(`/`)&&y.length>1){let t=y.find(t=>{let n=Array.isArray(t)?t[2]:t.filePath;return n&&n.toLowerCase().includes(e.toLowerCase())});if(t)x=t;else return`⚠️ AMBIGUOUS TARGET: Could not uniquely match "${e}". Found:\n\n${b.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
371
|
-
`)}\n\nPlease use a more specific path.`}let ee=Array.isArray(x)?x[0]:x.id,te=Array.isArray(x)?x[1]:x.nodeType,S=Array.isArray(x)?x[2]:x.filePath,ne=te===`File`,re=[],ie=
|
|
371
|
+
`)}\n\nPlease use a more specific path.`}let ee=Array.isArray(x)?x[0]:x.id,te=Array.isArray(x)?x[1]:x.nodeType,S=Array.isArray(x)?x[2]:x.filePath,ne=te===`File`,re=[],ie=n===`upstream`?ne?`
|
|
372
372
|
MATCH (affected)-[r:CodeRelation]->(callee)
|
|
373
373
|
WHERE callee.filePath = '${(S||e).replace(/'/g,`''`)}'
|
|
374
374
|
AND r.type IN [${h}]
|
|
@@ -434,7 +434,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
434
434
|
r.confidence AS confidence,
|
|
435
435
|
r.reason AS reason
|
|
436
436
|
LIMIT 300
|
|
437
|
-
`;if(re.push(
|
|
437
|
+
`;if(re.push(t(ie).then(e=>e).catch(e=>[])),u>=2){let e=n===`upstream`?`
|
|
438
438
|
MATCH (target {id: '${ee.replace(/'/g,`''`)}'})
|
|
439
439
|
MATCH (a)-[r1:CodeRelation]->(target)
|
|
440
440
|
MATCH (affected)-[r2:CodeRelation]->(a)
|
|
@@ -472,7 +472,7 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
472
472
|
r2.confidence AS confidence,
|
|
473
473
|
r2.reason AS reason
|
|
474
474
|
LIMIT 200
|
|
475
|
-
`;re.push(
|
|
475
|
+
`;re.push(t(e).catch(e=>[]))}if(u>=3){let e=n===`upstream`?`
|
|
476
476
|
MATCH (target {id: '${ee.replace(/'/g,`''`)}'})
|
|
477
477
|
MATCH (a)-[r1:CodeRelation]->(target)
|
|
478
478
|
MATCH (b)-[r2:CodeRelation]->(a)
|
|
@@ -514,14 +514,14 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
514
514
|
r3.confidence AS confidence,
|
|
515
515
|
r3.reason AS reason
|
|
516
516
|
LIMIT 100
|
|
517
|
-
`;re.push(
|
|
518
|
-
`);return`No ${
|
|
517
|
+
`;re.push(t(e).catch(e=>[]))}let ae=await Promise.all(re),oe=new Map,se=[],ce=new Set;ae.forEach((e,t)=>{let n=t+1;e.forEach(e=>{let t=Array.isArray(e)?e[0]:e.id,r=Array.isArray(e)?e[3]:e.filePath;if(!(!d&&p(r))&&t&&!ce.has(t)){ce.add(t),oe.has(n)||oe.set(n,[]);let i={id:t,name:Array.isArray(e)?e[1]:e.name,nodeType:Array.isArray(e)?e[2]:e.nodeType,filePath:r,startLine:Array.isArray(e)?e[4]:e.startLine,edgeType:Array.isArray(e)?e[5]:e.edgeType||`CALLS`,confidence:Array.isArray(e)?e[6]:e.confidence??1,reason:Array.isArray(e)?e[7]:e.reason||``};oe.get(n).push(i),se.push(t)}})});let C=se.length;if(C===0){if(ne){let t=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=((S||e).split(`/`).pop()||e).replace(/\.[^/.]+$/,``);try{let a=(await r(`\\b${t(i)}\\b`,15)).filter(e=>e.filePath!==S);if(a.length>0){let t=a.map(e=>`${e.filePath}:${e.line}: ${e.text}`).join(`
|
|
518
|
+
`);return`No ${n} dependencies found for "${e}" (types: ${m.join(`, `)}), but textual references were detected (graph may be incomplete):\n\n${t}`}}catch{}}return`No ${n} dependencies found for "${e}" (types: ${m.join(`, `)}). This code appears to be ${n===`upstream`?`unused (not called by anything)`:`self-contained (no outgoing dependencies)`}.`}let le=oe.get(1)||[],ue=oe.get(2)||[],de=oe.get(3)||[],fe={high:0,medium:0,low:0};for(let e of oe.values())for(let t of e){let e=t.confidence??1;e>=.9?fe.high+=1:e>=.8?fe.medium+=1:fe.low+=1}let pe=se.slice(0,500),me=pe.map(e=>`'${e.replace(/'/g,`''`)}'`).join(`, `),he=[],ge=[];if(pe.length>0){let e=`
|
|
519
519
|
MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
|
|
520
520
|
WHERE s.id IN [${me}]
|
|
521
521
|
RETURN p.label AS label, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep, p.stepCount AS stepCount
|
|
522
522
|
ORDER BY hits DESC
|
|
523
523
|
LIMIT 20
|
|
524
|
-
`,
|
|
524
|
+
`,n=`
|
|
525
525
|
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
526
526
|
WHERE s.id IN [${me}]
|
|
527
527
|
RETURN c.label AS label, COUNT(DISTINCT s.id) AS hits
|
|
@@ -531,8 +531,8 @@ MATCH (n:Function {id: emb.nodeId}) RETURN n`,schema:B({cypher:z().describe(`The
|
|
|
531
531
|
MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
|
|
532
532
|
WHERE s.id IN [${r}]
|
|
533
533
|
RETURN DISTINCT c.label AS label
|
|
534
|
-
`:``,[a,o,s]=await Promise.all([
|
|
535
|
-
`),n=e.startLine-1;if(n<0||n>=t.length)return null;let r=t[n].trim();return r.length>80&&(r=r.slice(0,77)+`...`),r}catch{return null}};if(le.length>0){let t=
|
|
534
|
+
`:``,[a,o,s]=await Promise.all([t(e),t(n),i?t(i):Promise.resolve([])]),c=new Set;s.forEach(e=>{let t=Array.isArray(e)?e[0]:e.label;t&&c.add(t)}),he=a.map(e=>({label:Array.isArray(e)?e[0]:e.label,hits:Array.isArray(e)?e[1]:e.hits,minStep:Array.isArray(e)?e[2]:e.minStep,stepCount:Array.isArray(e)?e[3]:e.stepCount})),ge=o.map(e=>{let t=Array.isArray(e)?e[0]:e.label;return{label:t,hits:Array.isArray(e)?e[1]:e.hits,impact:c.has(t)?`direct`:`indirect`}})}let _e=le.length,ve=he.length,ye=ge.length,be=`LOW`;_e>=30||ve>=5||ye>=5||C>=200?be=`CRITICAL`:_e>=15||ve>=3||ye>=3||C>=100?be=`HIGH`:(_e>=5||C>=30)&&(be=`MEDIUM`);let xe=[`🔴 IMPACT: ${e} | ${n} | ${C} affected`,`Confidence: High ${fe.high} | Medium ${fe.medium} | Low ${fe.low}`,``,`AFFECTED PROCESSES:`,...he.length>0?he.map(e=>`- ${e.label} - BROKEN at step ${e.minStep??`?`} (${e.hits} symbols, ${e.stepCount??`?`} steps)`):[`- None found`],``,`AFFECTED CLUSTERS:`,...ge.length>0?ge.map(e=>`- ${e.label} (${e.impact}, ${e.hits} symbols)`):[`- None found`],``,`RISK: ${be}`,`- Direct callers: ${_e}`,`- Processes affected: ${ve}`,`- Clusters affected: ${ye}`,``],Se=e=>{let t=e.filePath?.split(`/`).pop()||``,n=e.startLine?`${t}:${e.startLine}`:t,r=Math.round((e.confidence??1)*100),i=r<80?`[fuzzy]`:``;return` ${e.nodeType}|${e.name}|${n}|${e.edgeType}|${r}%${i}`},Ce=async e=>{if(!e.filePath||!e.startLine)return null;try{let t=(await i(e.filePath)).split(`
|
|
535
|
+
`),n=e.startLine-1;if(n<0||n>=t.length)return null;let r=t[n].trim();return r.length>80&&(r=r.slice(0,77)+`...`),r}catch{return null}};if(le.length>0){let t=n===`upstream`?`d=1 (Directly DEPEND ON ${e}):`:`d=1 (${e} USES these):`;xe.push(t);for(let e of le.slice(0,15)){xe.push(Se(e));let t=await Ce(e);t&&xe.push(` ↳ "${t}"`)}le.length>15&&xe.push(` ... +${le.length-15} more`),xe.push(``)}if(ue.length>0){let t=n===`upstream`?`d=2 (Indirectly DEPEND ON ${e}):`:`d=2 (${e} USES these indirectly):`;xe.push(t),ue.slice(0,15).forEach(e=>xe.push(Se(e))),ue.length>15&&xe.push(` ... +${ue.length-15} more`),xe.push(``)}return de.length>0&&(xe.push(`d=3 (Deep impact/dependency):`),de.slice(0,5).forEach(e=>xe.push(Se(e))),de.length>5&&xe.push(` ... +${de.length-5} more`),xe.push(``)),xe.push(`✅ GRAPH ANALYSIS COMPLETE (trusted)`),xe.push(`⚠️ Optional: grep("${e}") for dynamic patterns`),xe.push(``),xe.join(`
|
|
536
536
|
`)},{name:`impact`,description:`Analyze the impact of changing a function, class, or file.
|
|
537
537
|
|
|
538
538
|
Use when users ask:
|
|
@@ -657,4 +657,4 @@ When generating diagrams:
|
|
|
657
657
|
|
|
658
658
|
BAD: A[User's Data] --> B(Process & Save)
|
|
659
659
|
GOOD: A["User Data"] --> B["Process and Save"]
|
|
660
|
-
`,y2=e=>{switch(e.provider){case`openai`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenAI API key is required but was not provided`);return new zq({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,...t.baseUrl?{baseURL:t.baseUrl}:{}},streaming:!0})}case`azure-openai`:{let t=e;return new Bq({azureOpenAIApiKey:t.apiKey,azureOpenAIApiInstanceName:b2(t.endpoint),azureOpenAIApiDeploymentName:t.deploymentName,azureOpenAIApiVersion:t.apiVersion??`2024-12-01-preview`,streaming:!0})}case`gemini`:{let t=e;return new TY({apiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxOutputTokens:t.maxTokens,streaming:!0})}case`anthropic`:{let t=e;return new V1({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0})}case`ollama`:{let t=e;return new a2({baseUrl:t.baseUrl??`http://localhost:11434`,model:t.model,temperature:t.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case`openrouter`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenRouter API key is required but was not provided`);return new zq({openAIApiKey:t.apiKey,apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://openrouter.ai/api/v1`},streaming:!0})}case`minimax`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`MiniMax API key is required but was not provided`);return new V1({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0,clientOptions:{baseURL:`https://api.minimax.io/anthropic`}})}case`glm`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`GLM API key is required but was not provided`);return new zq({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://api.z.ai/api/coding/paas/v4`},streaming:!0})}case`deepseek`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`DeepSeek API key is required but was not provided`);return new u2({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:`https://api.deepseek.com`},streaming:!0})}default:throw Error(`Unsupported provider: ${e.provider}`)}},b2=e=>{try{let t=new URL(e).hostname,n=t.match(/^([^.]+)\.openai\.azure\.com$/);return n?n[1]:t.split(`.`)[0]}catch{return e}},x2=(e,t,
|
|
660
|
+
`,y2=e=>{switch(e.provider){case`openai`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenAI API key is required but was not provided`);return new zq({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,...t.baseUrl?{baseURL:t.baseUrl}:{}},streaming:!0})}case`azure-openai`:{let t=e;return new Bq({azureOpenAIApiKey:t.apiKey,azureOpenAIApiInstanceName:b2(t.endpoint),azureOpenAIApiDeploymentName:t.deploymentName,azureOpenAIApiVersion:t.apiVersion??`2024-12-01-preview`,streaming:!0})}case`gemini`:{let t=e;return new TY({apiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxOutputTokens:t.maxTokens,streaming:!0})}case`anthropic`:{let t=e;return new V1({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0})}case`ollama`:{let t=e;return new a2({baseUrl:t.baseUrl??`http://localhost:11434`,model:t.model,temperature:t.temperature??.1,streaming:!0,numPredict:3e4,numCtx:32768})}case`openrouter`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`OpenRouter API key is required but was not provided`);return new zq({openAIApiKey:t.apiKey,apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://openrouter.ai/api/v1`},streaming:!0})}case`minimax`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`MiniMax API key is required but was not provided`);return new V1({anthropicApiKey:t.apiKey,model:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens??8192,streaming:!0,clientOptions:{baseURL:`https://api.minimax.io/anthropic`}})}case`glm`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`GLM API key is required but was not provided`);return new zq({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:t.baseUrl??`https://api.z.ai/api/coding/paas/v4`},streaming:!0})}case`deepseek`:{let t=e;if(!t.apiKey||t.apiKey.trim()===``)throw Error(`DeepSeek API key is required but was not provided`);return new u2({apiKey:t.apiKey,modelName:t.model,temperature:t.temperature??.1,maxTokens:t.maxTokens,configuration:{apiKey:t.apiKey,baseURL:`https://api.deepseek.com`},streaming:!0})}default:throw Error(`Unsupported provider: ${e.provider}`)}},b2=e=>{try{let t=new URL(e).hostname,n=t.match(/^([^.]+)\.openai\.azure\.com$/);return n?n[1]:t.split(`.`)[0]}catch{return e}},x2=(e,t,i,a=!1)=>BR({llm:y2(e),tools:c2(t),messageModifier:new _n(i?r(v2,i,a):a?`${v2}${n}`:v2)}),S2=(e,t)=>!!(e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`||t?.aborted),C2=e=>e.map(e=>e.role===`user`?new fn(e.content):e.role===`tool`?new xt({content:e.content,tool_call_id:e.toolCallId,...e.name?{name:e.name}:{}}):new $t({content:e.content,...typeof e.reasoningContent==`string`?{additional_kwargs:{reasoning_content:e.reasoningContent}}:{},...e.toolCalls?.length?{tool_calls:e.toolCalls}:{}})),w2=(e,t=0)=>{let n=[];for(let r of e.slice(t)){let e=r,t=e?._getType?.()||e?.type||e?.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`){let t=(e.additional_kwargs||e.kwargs)?.reasoning_content,r=p2(e.tool_calls);n.push({role:`assistant`,content:d2(e.content),...r?.length&&typeof t==`string`?{reasoningContent:t}:{},...r?.length?{toolCalls:r}:{}});continue}(t===`tool`||t===`ToolMessage`)&&n.push({role:`tool`,content:d2(e.content),toolCallId:String(e.tool_call_id??``),...typeof e.name==`string`?{name:e.name}:{}})}return n};async function*T2(e,t,n={}){try{let r=C2(t),i=await e.stream({messages:r},{streamMode:[`values`,`messages`],recursionLimit:50,signal:n.signal}),a=new Set,o=new Set,s=r.length,c=0,l=!1,u=null;for await(let e of i){if(n.signal?.aborted)break;let t,r;if(Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[t,r]=e:Array.isArray(e)&&e[0]?._getType?(t=`messages`,r=e):(t=`values`,r=e),t===`messages`){let[e]=Array.isArray(r)?r:[r];if(!e)continue;let t=e._getType?.()||e.type||e.constructor?.name||`unknown`;if(t===`ai`||t===`AIMessage`||t===`AIMessageChunk`){let t=e.content,n=e.tool_calls||[],r=``;if(typeof t==`string`?r=t:Array.isArray(t)&&(r=t.filter(e=>e.type===`text`||typeof e==`string`).map(e=>typeof e==`string`?e:e.text||``).join(``)),r&&r.length>0&&(!l||n.length>0||c>0?yield{type:`reasoning`,reasoning:r}:yield{type:`content`,content:r}),n.length>0){l=!0,c+=n.length;for(let e of n){let t=e.id||`tool-${Date.now()}-${Math.random().toString(36).slice(2)}`;if(!a.has(t)){a.add(t);let n;try{n=e.function?.arguments?JSON.parse(e.function.arguments):{}}catch{n={}}yield{type:`tool_call`,toolCall:{id:t,name:e.name||e.function?.name||`unknown`,args:e.args||n,status:`running`}}}}}}if(t===`tool`||t===`ToolMessage`){let t=e.tool_call_id||``;if(t&&!o.has(t)){o.add(t);let n=typeof e.content==`string`?e.content:JSON.stringify(e.content);yield{type:`tool_result`,toolCall:{id:t,name:e.name||`tool`,args:{},result:n,status:`completed`}},c=Math.max(0,c-1)}}}if(t===`values`&&r?.messages){let e=r.messages||[];n.captureHistory&&(u=e);for(let t=s;t<e.length;t++){let n=e[t],r=n._getType?.()||n.type||`unknown`;if((r===`ai`||r===`AIMessage`)&&!a.size){let e=n.tool_calls||[];for(let t of e){let e=t.id||`tool-${Date.now()}`;a.has(e)||(c++,a.add(e),yield{type:`tool_call`,toolCall:{id:e,name:t.name||`unknown`,args:t.args||{},status:`running`}})}}if(r===`tool`||r===`ToolMessage`){let e=n.tool_call_id||``;if(e&&!o.has(e)){o.add(e);let t=typeof n.content==`string`?n.content:JSON.stringify(n.content);yield{type:`tool_result`,toolCall:{id:e,name:n.name||`tool`,args:{},result:t,status:`completed`}},c=Math.max(0,c-1)}}}s=e.length}}if(n.signal?.aborted){yield{type:`cancelled`};return}yield{type:`done`,historyMessages:n.captureHistory&&u?w2(u,r.length):void 0}}catch(e){if(S2(e,n.signal)){yield{type:`cancelled`};return}yield{type:`error`,error:e instanceof Error?e.message:String(e)}}}export{x2 as createGraphRAGAgent,T2 as streamAgentResponse};
|