@arcgis/ai-components 5.2.0-next.104 → 5.2.0-next.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/agent-utils/LLMAgent.js +41 -40
  2. package/dist/agent-utils/middlewares/trace.js +5 -5
  3. package/dist/agents/runtime/skill/createSkillAgent.d.ts +31 -0
  4. package/dist/agents/runtime/skill/createSkillAgent.js +262 -0
  5. package/dist/agents/runtime/skill/loadAgentSkills.d.ts +16 -0
  6. package/dist/agents/runtime/skill/types.d.ts +28 -0
  7. package/dist/agents/runtime/skill/types.js +2 -0
  8. package/dist/agents/tools/filter/setFeatureEffect/adapter.js +20 -19
  9. package/dist/agents/tools/query/getStatistics/adapter.js +4 -3
  10. package/dist/agents/tools/query/getTopFeatures/adapter.js +4 -3
  11. package/dist/agents/tools/query/queryFeatures/adapter.js +4 -3
  12. package/dist/agents/tools/shared/resolveToolArtifact.d.ts +22 -0
  13. package/dist/agents/tools/shared/resolveToolArtifact.js +20 -0
  14. package/dist/agents/tools/shared/types.d.ts +22 -0
  15. package/dist/agents/tools/shared/types.js +6 -0
  16. package/dist/cdn/23C34FEU.js +2 -0
  17. package/dist/cdn/{NZSOJ726.js → 2AMUOR7X.js} +1 -1
  18. package/dist/cdn/2OHRNRNT.js +2 -0
  19. package/dist/cdn/2OUIRKTV.js +2 -0
  20. package/dist/cdn/2S6L3P4Q.js +2 -0
  21. package/dist/cdn/{C4FEETBZ.js → 2W7LK4HA.js} +1 -1
  22. package/dist/cdn/3IOP64NG.js +2 -0
  23. package/dist/cdn/3OH35VXS.js +2 -0
  24. package/dist/cdn/{5K5ZY267.js → 3SD47V7G.js} +1 -1
  25. package/dist/cdn/{7VAQUCBU.js → 3VCPN2KW.js} +1 -1
  26. package/dist/cdn/{LLUGJKAQ.js → 3XDT7MWI.js} +1 -1
  27. package/dist/cdn/{Y7XD7ZRD.js → 4ALF2CJY.js} +1 -1
  28. package/dist/cdn/{HAEFC2SJ.js → 5LMYUEK7.js} +1 -1
  29. package/dist/cdn/{655YIKL3.js → 6GODC6RU.js} +2 -2
  30. package/dist/cdn/{7VUSIGEM.js → 6RAWG2KQ.js} +1 -1
  31. package/dist/cdn/{GCVB5VG4.js → 6YZGKVYB.js} +1 -1
  32. package/dist/cdn/{VLLZ2FFU.js → 725MBCQF.js} +1 -1
  33. package/dist/cdn/74CVYM72.js +19 -0
  34. package/dist/cdn/{CP5BVGJU.js → 7EOS4SGJ.js} +1 -1
  35. package/dist/cdn/{5WYRJMBW.js → 7QIX4PZR.js} +1 -1
  36. package/dist/cdn/7UF3WRLO.js +72 -0
  37. package/dist/cdn/A7BKHIMA.js +2 -0
  38. package/dist/cdn/AFSBL4ZP.js +2 -0
  39. package/dist/cdn/{FG647IP6.js → AGQ5ADFU.js} +1 -1
  40. package/dist/cdn/{5ZFUGNRN.js → BQYF37UD.js} +1 -1
  41. package/dist/cdn/{4RDNI22D.js → BTTBKTFM.js} +4 -4
  42. package/dist/cdn/BVSK2GWP.js +2 -0
  43. package/dist/cdn/CFAC4FN3.js +2 -0
  44. package/dist/cdn/{HDACNIZF.js → D5EKX26R.js} +1 -1
  45. package/dist/cdn/EGN5BCHV.js +2 -0
  46. package/dist/cdn/{BXQ4I5HB.js → EJJFG5DE.js} +2 -2
  47. package/dist/cdn/{ZDV4K4WG.js → EOD5PNOL.js} +1 -1
  48. package/dist/cdn/{OE3GW5LE.js → ES6D4UD6.js} +1 -1
  49. package/dist/cdn/{K2R6XVK3.js → HB72YIII.js} +1 -1
  50. package/dist/cdn/{G2EGT3CF.js → HHBNLCJP.js} +1 -1
  51. package/dist/cdn/HLN5675C.js +2 -0
  52. package/dist/cdn/IFFOSSNB.js +2 -0
  53. package/dist/cdn/IO7DYFL2.js +2 -0
  54. package/dist/cdn/{IBZ2NEAO.js → IRSJXHRN.js} +1 -1
  55. package/dist/cdn/JD2TB7H4.js +2 -0
  56. package/dist/cdn/{ANRQWYU2.js → JKKU4K4C.js} +1 -1
  57. package/dist/cdn/{FUF3NAU7.js → JMNHFKGL.js} +1 -1
  58. package/dist/cdn/{22KHSDJI.js → JWZD3D5E.js} +1 -1
  59. package/dist/cdn/{HKOGIZDQ.js → KJLLN4P4.js} +18 -18
  60. package/dist/cdn/KZ73TZOB.js +2 -0
  61. package/dist/cdn/LEO3USHH.js +2 -0
  62. package/dist/cdn/LNIMGXB4.js +2 -0
  63. package/dist/cdn/MG2W2ZF3.js +2 -0
  64. package/dist/cdn/{NYJYRCGA.js → MSXMHRI7.js} +1 -1
  65. package/dist/cdn/MXAZE2VM.js +179 -0
  66. package/dist/cdn/{EWLXNGKH.js → OL7QBAGS.js} +15 -15
  67. package/dist/cdn/OMF6ITSG.js +2 -0
  68. package/dist/cdn/{Z5W4V7RC.js → OOGADOKQ.js} +1 -1
  69. package/dist/cdn/{KITIP6J2.js → OZ2CM3J2.js} +1 -1
  70. package/dist/cdn/{6YYPVU7H.js → P4GFYBBO.js} +1 -1
  71. package/dist/cdn/PK5KI2XF.js +2 -0
  72. package/dist/cdn/PWFUEBTT.js +2 -0
  73. package/dist/cdn/{HHUQXL3R.js → PYGX4HN7.js} +1 -1
  74. package/dist/cdn/RFVZ7KCG.js +66 -0
  75. package/dist/cdn/{YEZ3AMNX.js → RLB6TK6B.js} +1 -1
  76. package/dist/cdn/{WKTQVBFJ.js → RN6WMVZX.js} +1 -1
  77. package/dist/cdn/{WJXXOKGA.js → ROQGPAR5.js} +1 -1
  78. package/dist/cdn/RSJSRETN.js +2 -0
  79. package/dist/cdn/RSR66KB4.js +2 -0
  80. package/dist/cdn/{7SRLZQVC.js → RZIXMISL.js} +1 -1
  81. package/dist/cdn/{VOKXKU7M.js → S4LELUBK.js} +9 -9
  82. package/dist/cdn/{AI6DYOKR.js → S627D4K7.js} +1 -1
  83. package/dist/cdn/SL4Y7IRG.js +2 -0
  84. package/dist/cdn/STUBN3L5.js +2 -0
  85. package/dist/cdn/T2OYKP3V.js +2 -0
  86. package/dist/cdn/{C4JT4S5E.js → TBYDZN4H.js} +1 -1
  87. package/dist/cdn/{HHFNQR6Z.js → TEI6WXW7.js} +1 -1
  88. package/dist/cdn/{WGO5SER7.js → TFRWUAB6.js} +1 -1
  89. package/dist/cdn/U3ETGDT7.js +2 -0
  90. package/dist/cdn/{KWD2ECTM.js → UAG6GDUG.js} +1 -1
  91. package/dist/cdn/UHICISBZ.js +2 -0
  92. package/dist/cdn/{NNXISHCA.js → VMZZR7MY.js} +2 -2
  93. package/dist/cdn/WW4BEFDF.js +2 -0
  94. package/dist/cdn/XGCQS3N4.js +2 -0
  95. package/dist/cdn/{R2PQVY4O.js → XKH37FLY.js} +1 -1
  96. package/dist/cdn/XQ3NBBQ3.js +2 -0
  97. package/dist/cdn/{7BCQMK6D.js → XTCLJEID.js} +1 -1
  98. package/dist/cdn/{J6SZIQJA.js → Y7LGFSHO.js} +1 -1
  99. package/dist/cdn/ZFOG3KXV.js +2 -0
  100. package/dist/cdn/ZZZB3GES.js +14 -0
  101. package/dist/cdn/agent-utils/index.js +1 -1
  102. package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
  103. package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
  104. package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
  105. package/dist/cdn/index.js +1 -1
  106. package/dist/chunks/SKILL.js +5 -0
  107. package/dist/chunks/SKILL2.js +5 -0
  108. package/dist/chunks/SKILL3.js +22 -0
  109. package/dist/chunks/SKILL4.js +5 -0
  110. package/dist/chunks/adapter.js +137 -140
  111. package/dist/chunks/aiFactory.js +94 -0
  112. package/dist/chunks/arcgisKnowledgeGraph.js +14 -13
  113. package/dist/chunks/baseAgentState.js +2 -2
  114. package/dist/chunks/dataExplorationAgent.js +30 -0
  115. package/dist/chunks/generateLayerDescriptions.js +181 -268
  116. package/dist/chunks/helpAgent.js +37 -0
  117. package/dist/chunks/layerStylingGraph.js +91 -76
  118. package/dist/chunks/navigationAgent.js +40 -0
  119. package/dist/chunks/orchestrator.js +13 -12
  120. package/dist/chunks/requireAgentServices.js +11 -0
  121. package/dist/chunks/resolvePointGeometryFilter.js +11 -11
  122. package/dist/components/arcgis-assistant/customElement.d.ts +23 -3
  123. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +17 -6
  124. package/dist/components/arcgis-assistant-help-agent/customElement.js +3 -1
  125. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -0
  126. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -0
  127. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +18 -7
  128. package/dist/docs/api.json +1 -1
  129. package/dist/docs/docs.json +1 -1
  130. package/dist/docs/vscode.html-custom-data.json +1 -1
  131. package/dist/docs/web-types.json +1 -1
  132. package/dist/orchestrator/models/types.d.ts +1 -0
  133. package/dist/orchestrator/providers/arcgis/aiFactory.d.ts +15 -0
  134. package/dist/orchestrator/registry/agentRegistry.d.ts +33 -0
  135. package/dist/orchestrator/types/types.d.ts +17 -0
  136. package/dist/utils/index.d.ts +13 -3
  137. package/dist/utils/index.js +706 -82
  138. package/package.json +10 -6
  139. package/dist/cdn/2EY3BQQX.js +0 -2
  140. package/dist/cdn/2NDBI2VA.js +0 -156
  141. package/dist/cdn/4OGR5QKS.js +0 -2
  142. package/dist/cdn/5FL5BTTX.js +0 -66
  143. package/dist/cdn/5X7EG7D2.js +0 -2
  144. package/dist/cdn/6FCU2KJP.js +0 -2
  145. package/dist/cdn/7BJ4JKLG.js +0 -2
  146. package/dist/cdn/7HS5KX3J.js +0 -2
  147. package/dist/cdn/7UUYJTKT.js +0 -2
  148. package/dist/cdn/7V6OSTFC.js +0 -2
  149. package/dist/cdn/7VYYQ7BT.js +0 -2
  150. package/dist/cdn/ACJTJLZN.js +0 -2
  151. package/dist/cdn/AKD5UOVX.js +0 -2
  152. package/dist/cdn/C7LGDNB3.js +0 -14
  153. package/dist/cdn/CGJINV7H.js +0 -2
  154. package/dist/cdn/CJMUJXPL.js +0 -2
  155. package/dist/cdn/D2SS763Z.js +0 -2
  156. package/dist/cdn/FJO4KNOZ.js +0 -2
  157. package/dist/cdn/G3SF6U2U.js +0 -2
  158. package/dist/cdn/G6CR7JVM.js +0 -22
  159. package/dist/cdn/GL7BPKBN.js +0 -2
  160. package/dist/cdn/JO5ETMPS.js +0 -2
  161. package/dist/cdn/PUHRBGKB.js +0 -2
  162. package/dist/cdn/Q57QWN5W.js +0 -2
  163. package/dist/cdn/QUKNPVAF.js +0 -2
  164. package/dist/cdn/RBE55SWR.js +0 -2
  165. package/dist/cdn/SWH6ZHD4.js +0 -18
  166. package/dist/cdn/SZ2QSSB3.js +0 -2
  167. package/dist/cdn/T4RIGOXB.js +0 -2
  168. package/dist/cdn/W4JQDITQ.js +0 -36
  169. package/dist/cdn/XX6GHMNR.js +0 -2
  170. package/dist/cdn/YLVJA4ZE.js +0 -2
  171. package/dist/cdn/ZOEMBHRF.js +0 -2
  172. package/dist/cdn/ZRVZMPFN.js +0 -2
  173. package/dist/chunks/dataExplorationGraph.js +0 -254
  174. package/dist/chunks/helpGraph.js +0 -133
  175. package/dist/chunks/navigationGraph.js +0 -290
  176. package/dist/chunks/toolCallResponse.js +0 -33
@@ -1,8 +1,8 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{$ as It,J as ot,Na as oe,Oa as at,Qa as W,Ra as Ot,S as Et,U as rt,Ua as Le,Wa as be,Xa as De,Ya as Nt,_ as At,a as ft,aa as Rt,b as R,f as $,j as L,k as H,ta as je,wa as Pt,x as Ke,y as pt}from"./EWLXNGKH.js";import{$ as wt,Ab as Ct,Ac as st,Ba as yt,Bb as te,Cb as _t,K as Ze,Kb as F,Lb as de,Nb as xt,Qb as Pe,Sb as St,Vb as i,W as M,Wa as qe,Xb as tt,Za as B,Zb as Oe,_a as ce,ab as Ae,bb as Mt,bc as Te,c as ht,cc as Y,db as et,ea as T,fb as Tt,fc as ue,ha as Xe,hc as Ne,p as Ye,qa as Q,qb as Me,rb as Ie,ua as Qe,ub as Re,uc as nt,v as gt,va as z,wc as kt,yb as vt}from"./AI6DYOKR.js";import{Dd as U,s as bt}from"./MWYBF3F3.js";var $e=Symbol.for("AgentMiddleware");function E(e){return{[$e]:!0,name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools,streamTransformers:e.streamTransformers}}var ve=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},Ce=class extends Error{toolNames;constructor(e){super(`The model has called multiple tools: ${e.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=e}},me=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(o=>`
2
+ import{A as L,B as H,Na as oe,O as st,Oa as at,P as Rt,Qa as W,Ra as Ot,Ua as Le,Wa as be,Xa as De,Ya as Nt,a as tt,b as xt,c as St,d as kt,l as At,n as rt,r as It,s as R,ta as je,w as U,wa as Pt}from"./OL7QBAGS.js";import{$b as Y,A as Ke,Ac as Et,Ea as Xe,Fb as F,Gb as de,Ib as Ct,Lb as Pe,Nb as _t,O as M,Qb as i,Sb as Me,T as pt,Ta as Qe,Ub as et,Wa as $,Wb as Oe,Xa as ce,Za as Ae,_a as wt,_b as Te,ab as qe,ca as Q,cb as yt,cc as ue,e as ft,ec as Ne,ga as Ye,ha as z,mb as Ie,na as ht,oc as ot,pb as Re,ta as T,tb as Tt,vb as bt,wa as Ze,wb as te,xb as vt,ya as gt,yc as nt}from"./S627D4K7.js";import{Dd as B,s as Mt}from"./MWYBF3F3.js";var $e=Symbol.for("AgentMiddleware");function E(e){return{[$e]:!0,name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools,streamTransformers:e.streamTransformers}}var ve=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},Ce=class extends Error{toolNames;constructor(e){super(`The model has called multiple tools: ${e.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=e}},me=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(o=>`
3
3
  - ${o}`).join("")}.`),this.toolName=e,this.errors=t}},fe=class extends Error{"~brand"="ToolInvocationError";toolCall;toolError;constructor(e,t){let o=e instanceof Error?e:new Error(String(e)),n=JSON.stringify(t.args);super(`Error invoking tool '${t.name}' with kwargs ${n} with error: ${o.stack}
4
- Please fix the error and try again.`),this.toolCall=t,this.toolError=o}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="ToolInvocationError"}static[Symbol.hasInstance](e){return this.isInstance(e)}},ne=class jt extends Error{"~brand"="MiddlewareError";constructor(t,o){let n=t instanceof Error?t.message:String(t);super(n),this.name=t instanceof Error?t.name:`${o[0].toUpperCase()+o.slice(1)}Error`,t instanceof Error&&(this.cause=t)}static wrap(t,o){return Ke(t)?t:new jt(t,o)}static isInstance(t){return t instanceof Error&&"~brand"in t&&t["~brand"]==="MiddlewareError"}static[Symbol.hasInstance](t){return this.isInstance(t)}};function _e(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function pe(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_getModelInstance"in e&&typeof e._getModelInstance=="function"}var Lt=!0,vo=0,G=class it{schema;tool;options;constructor(t,o,n){this.schema=t,this.tool=o,this.options=n}get name(){return this.tool.function.name}static fromSchema(t,o){function n(a){return a??`extract-${++vo}`}if(Me(t)||Re(t)){let a=Oe(t),l={type:"function",function:{name:n(a.title),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new it(a,l,o)}let r;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?r=t:r={name:n(t.title),description:t.description??"",parameters:t.schema||t};let s=Oe(t);return new it(s,{type:"function",function:r},o)}parse(t){let o=new tt(this.schema).validate(t);if(!o.valid)throw new me(this.name,o.errors.map(n=>n.error));return t}},q=class Dt{_schemaType;schema;strict;constructor(t,o){if("schema"in t&&typeof t.schema=="object"&&t.schema!==null&&!("type"in t)){let n=t;this.schema=n.schema,this.strict=n.strict??Lt}else this.schema=t,this.strict=o??Lt}static fromSchema(t,o){let n=Oe(t);return new Dt(n,o)}parse(t){let o;if(typeof t.content=="string")o=t.content;else if(Array.isArray(t.content)){for(let n of t.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){o=n.text;break}}if(!(!o||o===""))try{let n=JSON.parse(o);return new tt(this.schema).validate(n).valid?n:void 0}catch{}}};function $t(e,t,o){if(!e)return[];if(typeof e=="object"&&e!==null&&"__responseFormatUndefined"in e)return[];if(Array.isArray(e)){if(e.every(r=>r instanceof G||r instanceof q))return e;if(e.every(r=>Me(r)))return e.map(r=>G.fromSchema(r,t));if(e.every(r=>F(r)))return e.map(r=>G.fromSchema(r,t));if(e.every(r=>typeof r=="object"&&r!==null&&!F(r)&&!Me(r)))return e.map(r=>G.fromSchema(r,t));throw new Error(`Invalid response format: list contains mixed types.
5
- All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(e instanceof G||e instanceof q)return[e];let n=Co(o);if(Me(e))return n?[q.fromSchema(e)]:[G.fromSchema(e,t)];if(F(e))return n?[q.fromSchema(e)]:[G.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return n?[q.fromSchema(e)]:[G.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function Co(e){return!e||!_e(e)||!("profile"in e)||typeof e.profile!="object"||!e.profile?!1:"structuredOutput"in e.profile&&e.profile.structuredOutput===!0}function _o(e,t){if(e.length<t.length||e.length>t.length+1)return!1;for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return!1;return!0}function xo(e){let t;try{t=JSON.parse(e)}catch{return!1}return!Array.isArray(t)||t.length===0?!1:t.every(o=>{if(o==null||typeof o!="object")return!1;let n=o;return typeof n.id=="string"&&"value"in n})}function So(e){if(e==null||typeof e!="object")return!1;let t=e;return t.type!=="constructor"||!Array.isArray(t.id)?!1:t.id[t.id.length-1]==="ToolMessage"}function ko(e){return M.isInstance(e)?e.content:So(e)?e.kwargs?.content:e}function ae(e){return()=>{let t=je.local(),o=new Map;function n(r,s,a){if(o.has(r))return;let l=typeof a=="string"?JSON.parse(a):a,u,m,c,h,d=new Promise((x,y)=>{u=x,m=y}),f=new Promise(x=>{c=x}),g=new Promise(x=>{h=x});o.set(r,{resolveOutput:u,rejectOutput:m,resolveStatus:c,resolveError:h}),t.push({name:s,callId:r,input:l,output:d,status:f,error:g})}return{__native:!0,init:()=>({toolCalls:t}),process(r){if(!_o(r.params.namespace,e))return!0;if(r.method==="messages"){let s=r.params.data;if(s.event==="content-block-finish"){let a=s.contentBlock??s.content_block;a?.type==="tool_call"&&n(String(a.id??""),String(a.name??""),a.args??a.input)}}if(r.method==="tools"){let s=r.params.data,a=s.tool_call_id;s.event==="tool-started"&&n(a,s.tool_name??"unknown",s.input);let l=a?o.get(a):void 0;if(l){if(s.event==="tool-finished")l.resolveOutput(ko(s.output)),l.resolveStatus("finished"),l.resolveError(void 0),o.delete(a);else if(s.event==="tool-error"){let u=s.message??"unknown error";if(xo(u))return!0;l.rejectOutput(new Error(u)),l.resolveStatus("error"),l.resolveError(u),o.delete(a)}}}return!0},finalize(){for(let r of o.values())r.resolveStatus("finished"),r.resolveError(void 0),r.resolveOutput(void 0);o.clear(),t.close()},fail(r){for(let s of o.values())s.resolveStatus("error"),s.resolveError(r instanceof Error?r.message:String(r)),s.rejectOutput(r);o.clear(),t.fail(r)}}}}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e){return e.join("\0")}function Bt(e,t){if(t.length>e.length)return!1;for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return!1;return!0}function he(e=[]){return()=>{let t=je.local(),o=new Map,n=new Map,r=new Map,s=new Map,a=e.length;function l(d,f){let g=xe(d);if(o.has(g))return;let x=(Z(f)&&Z(f.metadata)?f.metadata:void 0)?.lc_agent_name;o.set(g,typeof x=="string"?x:void 0)}function u(d){if(!Z(d))return;let f=d.id;if(typeof f!="string")return;let g=d.input,x;if(Z(g)&&Z(g.tool_call)){let y=g.tool_call.id;typeof y=="string"&&(x=y)}else if(Array.isArray(g)){for(let y of g)if(Z(y)&&typeof y.id=="string"){x=y.id;break}}x!=null&&n.set(f,x)}function m(d){let f=r.get(xe(d));if(typeof f=="string"&&f.length>0)return{type:"toolCall",tool_call_id:f};let g=d[d.length-1],x=g.indexOf(":");if(x===-1)return;let y=g.slice(x+1);if(y.length===0)return;let w=n.get(y);if(!(typeof w!="string"||w.length===0))return{type:"toolCall",tool_call_id:w}}function c(d){if(d.length!==a+1||!Bt(d,e))return;let f=xe(d);if(s.has(f))return;let g=o.get(f);if(typeof g!="string"||g.length===0)return;let x=Pt(d),y=x.init(),w=ae(d)(),O=w.init(),A=he(d)(),N=A.init(),K,j,b=new Promise((J,le)=>{K=J,j=le});s.set(f,{key:f,path:d,name:g,messages:x,toolCall:w,nested:A,resolveOutput:K,rejectOutput:j,latestValues:void 0,done:!1}),t.push({name:g,cause:m(d),output:b,messages:y.messages,toolCalls:O.toolCalls,subagents:N.subagents})}function h(d,f){d.done||(d.done=!0,f.type==="resolve"?d.resolveOutput(d.latestValues):d.rejectOutput(f.error),d.messages.finalize?.(),d.toolCall.finalize?.(),d.nested.finalize?.())}return{__native:!0,init:()=>({subagents:t}),process(d){let f=d.params.namespace,g=d.params.data,x=d.method==="tasks"&&Z(g)&&"result"in g;d.method==="tools"&&Z(g)&&g.event==="tool-started"&&typeof g.tool_call_id=="string"&&g.tool_call_id.length>0&&r.set(xe(f),g.tool_call_id),d.method==="tasks"&&!x&&(l(f,g),u(g),c(f));for(let y of s.values())if(!y.done&&Bt(f,y.path)&&(y.messages.process(d),y.toolCall.process(d),y.nested.process(d),xe(f)===y.key)){if(d.method==="values"&&Z(g))y.latestValues=g;else if(d.method==="lifecycle"&&Z(g)){let w=g.event;w==="completed"||w==="interrupted"?h(y,{type:"resolve"}):w==="failed"&&h(y,{type:"reject",error:new Error(`Subagent ${y.name} failed`)})}}return!0},finalize(){for(let d of s.values())h(d,{type:"resolve"});t.close()},fail(d){for(let f of s.values())h(f,{type:"reject",error:d});t.fail(d)}}}}var lt=Symbol.for("langgraph-zod");lt in globalThis||(globalThis[lt]=new WeakSet);function Ut(e){let t=globalThis[lt];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){let o=this;return{metadata(n){return De(o,{jsonSchemaExtra:n})},reducer(n,r){return De(o,{default:Pe(o),reducer:{schema:r,fn:n}})}}}}),t.add(e))}try{Ut(i.ZodType.prototype),Ut(U.ZodType.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var zt=class extends bt{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let o=t[0];if(o&&!o?.default){let n=Pe(e);n!=null&&(o.default=n)}return super.add(e,...t)}},Eo=new zt(be);function Ft(e=!0,t,o=[]){let n={jumpTo:new at},r={},s={},a=l=>{if(W.isInstance(l)){for(let[m,c]of Object.entries(l.fields))if(!(m in n)){if(n[m]=c,m.startsWith("_"))continue;oe.isInstance(c)?(r[m]=c.inputSchema||c.valueSchema,s[m]=c.valueSchema):(r[m]=c,s[m]=c)}return}let u=de(l);for(let[m,c]of Object.entries(u)){let h=m.startsWith("_");if(!(m in n)){if(Ie(c)){let d=be.get(c);if(d?.reducer){d.reducer.schema?(n[m]=new oe(c,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),h||(r[m]=d.reducer.schema,s[m]=c)):(n[m]=new oe(c,{reducer:d.reducer.fn}),h||(r[m]=c,s[m]=c));continue}}n[m]=c,h||(r[m]=c,s[m]=c)}}};t&&(W.isInstance(t)||F(t))&&a(t);for(let l of o)l.stateSchema&&(W.isInstance(l.stateSchema)||F(l.stateSchema))&&a(l.stateSchema);return e&&(s.structuredResponse=new at),{state:new W({messages:Le,...n}),input:new W({messages:Le,...r}),output:new W({messages:Le,...s})}}var ct=/<name>(.*?)<\/name>/s,dt=/<content>(.*?)<\/content>/s;function Ao(e,t){if(W.isInstance(e)){let o={};for(let n of Object.keys(e.fields))n in t&&(o[n]=t[n]);return o}if(Re(e))return te(e,t);throw new Error(`Invalid state schema type: ${typeof e}`)}function Ht(e){if(!T.isInstance(e)||Xe.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content=="string")return new T({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let o=[],n=0;for(let r of e.content)typeof r=="string"?(n+=1,o.push(`<name>${t}</name><content>${r}</content>`)):typeof r=="object"&&"type"in r&&r.type==="text"?(n+=1,o.push({...r,text:`<name>${t}</name><content>${r.text}</content>`})):o.push(r);return n||o.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new T({...e.lc_kwargs,content:o,name:void 0})}function Gt(e){if(!T.isInstance(e)||!e.content)return e;let t=[],o;if(Array.isArray(e.content))t=e.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let r=n.text.match(ct),s=n.text.match(dt);return r&&(!s||s[1]==="")?(o=r[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let r=n.text.match(ct),s=n.text.match(dt);return!r||!s?n:(o=r[1],{...n,text:s[1]})}return n});else{let n=e.content,r=n.match(ct),s=n.match(dt);if(!r||!s)return e;o=r[1],t=s[1]}return new T({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:o})}function ie(e){return Te.isRunnable(e)}function Wt(e){return _e(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}var ut=(e,t,o={})=>{if(Wt(e))return e.bindTools(t,o);if(Y.isRunnableBinding(e)&&Wt(e.bound)){let n=e.bound.bindTools(t,o);return Y.isRunnableBinding(n)?new Y({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new Y({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Be(e){if(typeof e=="function")return;let t=e;if(ue.isRunnableSequence(t)&&(t=t.steps.find(o=>Y.isRunnableBinding(o))||t),!pe(t)){if(Y.isRunnableBinding(t)){let o=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,n=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(o||n)throw new ve}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new ve}}function ge(e){return!!(T.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function Jt(e){if(e==null)return new z("");if(z.isInstance(e))return e;if(typeof e=="string")return new z({content:[{type:"text",text:e}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof e}`)}async function Vt(e,t,o={}){let n=ut(e,t,o);if(n)return n;if(pe(e)){let r=ut(await e._getModelInstance(),t,o);if(r)return r}if(ue.isRunnableSequence(e)){let r=e.steps.findIndex(s=>Y.isRunnableBinding(s)||_e(s)||pe(s));if(r>=0){let s=ut(e.steps[r],t,o);if(s){let a=e.steps.slice();return a.splice(r,1,s),ue.from(a)}}}throw new Error(`llm ${e} must define bindTools method.`)}function Io(e){if(e.length===0)return;if(e.length===1)return e[0];function t(n,r){return async(s,a)=>n(s,async u=>r(u,a))}let o=e[e.length-1];for(let n=e.length-2;n>=0;n--)o=t(e[n],o);return o}function Kt(e){let t=e.filter(o=>o.wrapToolCall);if(t.length!==0)return Io(t.map(o=>{let n=o.wrapToolCall;return async(s,a)=>{let l=s.state,u=new Set,m=async c=>{let h={...l,...c.state};try{return await a({...c,state:h})}catch(d){throw u.add(d),d}};try{let c=await n({...s,state:{messages:l.messages,...o.stateSchema?Ao(o.stateSchema,{...l}):{}}},m);if(!M.isInstance(c)&&!H(c))throw new Error(`Invalid response from "wrapToolCall" in middleware "${o.name}": expected ToolMessage or Command, got ${typeof c}`);return c}catch(c){throw u.has(c)?c:ne.wrap(c,o.name)}}}))}var Ro=["tags","metadata","runName","maxConcurrency","recursionLimit","configurable"];function Yt(e){let t={};for(let o of Ro){let n=e[o];n!==void 0&&(t[o]=n)}return t}async function Zt(e,t){let o={};for(let n of e){if(!n.stateSchema)continue;let r;if(W.isInstance(n.stateSchema)){let l={};for(let[u,m]of Object.entries(n.stateSchema.fields))oe.isInstance(m)?l[u]=m.inputSchema||m.valueSchema:l[u]=m;r=U.object(l)}else if(F(n.stateSchema))r=n.stateSchema;else continue;let s=await vt(St(r,l=>l.startsWith("_")),t);if(s.success){Object.assign(o,s.data);continue}let a=s.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
4
+ Please fix the error and try again.`),this.toolCall=t,this.toolError=o}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="ToolInvocationError"}static[Symbol.hasInstance](e){return this.isInstance(e)}},ne=class jt extends Error{"~brand"="MiddlewareError";constructor(t,o){let n=t instanceof Error?t.message:String(t);super(n),this.name=t instanceof Error?t.name:`${o[0].toUpperCase()+o.slice(1)}Error`,t instanceof Error&&(this.cause=t)}static wrap(t,o){return st(t)?t:new jt(t,o)}static isInstance(t){return t instanceof Error&&"~brand"in t&&t["~brand"]==="MiddlewareError"}static[Symbol.hasInstance](t){return this.isInstance(t)}};function _e(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function pe(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_getModelInstance"in e&&typeof e._getModelInstance=="function"}var Lt=!0,vo=0,G=class it{schema;tool;options;constructor(t,o,n){this.schema=t,this.tool=o,this.options=n}get name(){return this.tool.function.name}static fromSchema(t,o){function n(a){return a??`extract-${++vo}`}if(Me(t)||Re(t)){let a=Oe(t),l={type:"function",function:{name:n(a.title),strict:!1,description:a.description??"Tool for extracting structured output from the model's response.",parameters:a}};return new it(a,l,o)}let r;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?r=t:r={name:n(t.title),description:t.description??"",parameters:t.schema||t};let s=Oe(t);return new it(s,{type:"function",function:r},o)}parse(t){let o=new et(this.schema).validate(t);if(!o.valid)throw new me(this.name,o.errors.map(n=>n.error));return t}},q=class Dt{_schemaType;schema;strict;constructor(t,o){if("schema"in t&&typeof t.schema=="object"&&t.schema!==null&&!("type"in t)){let n=t;this.schema=n.schema,this.strict=n.strict??Lt}else this.schema=t,this.strict=o??Lt}static fromSchema(t,o){let n=Oe(t);return new Dt(n,o)}parse(t){let o;if(typeof t.content=="string")o=t.content;else if(Array.isArray(t.content)){for(let n of t.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){o=n.text;break}}if(!(!o||o===""))try{let n=JSON.parse(o);return new et(this.schema).validate(n).valid?n:void 0}catch{}}};function $t(e,t,o){if(!e)return[];if(typeof e=="object"&&e!==null&&"__responseFormatUndefined"in e)return[];if(Array.isArray(e)){if(e.every(r=>r instanceof G||r instanceof q))return e;if(e.every(r=>Me(r)))return e.map(r=>G.fromSchema(r,t));if(e.every(r=>F(r)))return e.map(r=>G.fromSchema(r,t));if(e.every(r=>typeof r=="object"&&r!==null&&!F(r)&&!Me(r)))return e.map(r=>G.fromSchema(r,t));throw new Error(`Invalid response format: list contains mixed types.
5
+ All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(e instanceof G||e instanceof q)return[e];let n=Co(o);if(Me(e))return n?[q.fromSchema(e)]:[G.fromSchema(e,t)];if(F(e))return n?[q.fromSchema(e)]:[G.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return n?[q.fromSchema(e)]:[G.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function Co(e){return!e||!_e(e)||!("profile"in e)||typeof e.profile!="object"||!e.profile?!1:"structuredOutput"in e.profile&&e.profile.structuredOutput===!0}function _o(e,t){if(e.length<t.length||e.length>t.length+1)return!1;for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return!1;return!0}function xo(e){let t;try{t=JSON.parse(e)}catch{return!1}return!Array.isArray(t)||t.length===0?!1:t.every(o=>{if(o==null||typeof o!="object")return!1;let n=o;return typeof n.id=="string"&&"value"in n})}function So(e){if(e==null||typeof e!="object")return!1;let t=e;return t.type!=="constructor"||!Array.isArray(t.id)?!1:t.id[t.id.length-1]==="ToolMessage"}function ko(e){return M.isInstance(e)?e.content:So(e)?e.kwargs?.content:e}function ae(e){return()=>{let t=je.local(),o=new Map;function n(r,s,a){if(o.has(r))return;let l=typeof a=="string"?JSON.parse(a):a,u,m,c,h,d=new Promise((x,y)=>{u=x,m=y}),f=new Promise(x=>{c=x}),g=new Promise(x=>{h=x});o.set(r,{resolveOutput:u,rejectOutput:m,resolveStatus:c,resolveError:h}),t.push({name:s,callId:r,input:l,output:d,status:f,error:g})}return{__native:!0,init:()=>({toolCalls:t}),process(r){if(!_o(r.params.namespace,e))return!0;if(r.method==="messages"){let s=r.params.data;if(s.event==="content-block-finish"){let a=s.contentBlock??s.content_block;a?.type==="tool_call"&&n(String(a.id??""),String(a.name??""),a.args??a.input)}}if(r.method==="tools"){let s=r.params.data,a=s.tool_call_id;s.event==="tool-started"&&n(a,s.tool_name??"unknown",s.input);let l=a?o.get(a):void 0;if(l){if(s.event==="tool-finished")l.resolveOutput(ko(s.output)),l.resolveStatus("finished"),l.resolveError(void 0),o.delete(a);else if(s.event==="tool-error"){let u=s.message??"unknown error";if(xo(u))return!0;l.rejectOutput(new Error(u)),l.resolveStatus("error"),l.resolveError(u),o.delete(a)}}}return!0},finalize(){for(let r of o.values())r.resolveStatus("finished"),r.resolveError(void 0),r.resolveOutput(void 0);o.clear(),t.close()},fail(r){for(let s of o.values())s.resolveStatus("error"),s.resolveError(r instanceof Error?r.message:String(r)),s.rejectOutput(r);o.clear(),t.fail(r)}}}}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e){return e.join("\0")}function Bt(e,t){if(t.length>e.length)return!1;for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return!1;return!0}function he(e=[]){return()=>{let t=je.local(),o=new Map,n=new Map,r=new Map,s=new Map,a=e.length;function l(d,f){let g=xe(d);if(o.has(g))return;let x=(Z(f)&&Z(f.metadata)?f.metadata:void 0)?.lc_agent_name;o.set(g,typeof x=="string"?x:void 0)}function u(d){if(!Z(d))return;let f=d.id;if(typeof f!="string")return;let g=d.input,x;if(Z(g)&&Z(g.tool_call)){let y=g.tool_call.id;typeof y=="string"&&(x=y)}else if(Array.isArray(g)){for(let y of g)if(Z(y)&&typeof y.id=="string"){x=y.id;break}}x!=null&&n.set(f,x)}function m(d){let f=r.get(xe(d));if(typeof f=="string"&&f.length>0)return{type:"toolCall",tool_call_id:f};let g=d[d.length-1],x=g.indexOf(":");if(x===-1)return;let y=g.slice(x+1);if(y.length===0)return;let w=n.get(y);if(!(typeof w!="string"||w.length===0))return{type:"toolCall",tool_call_id:w}}function c(d){if(d.length!==a+1||!Bt(d,e))return;let f=xe(d);if(s.has(f))return;let g=o.get(f);if(typeof g!="string"||g.length===0)return;let x=Pt(d),y=x.init(),w=ae(d)(),O=w.init(),A=he(d)(),N=A.init(),K,j,b=new Promise((J,le)=>{K=J,j=le});s.set(f,{key:f,path:d,name:g,messages:x,toolCall:w,nested:A,resolveOutput:K,rejectOutput:j,latestValues:void 0,done:!1}),t.push({name:g,cause:m(d),output:b,messages:y.messages,toolCalls:O.toolCalls,subagents:N.subagents})}function h(d,f){d.done||(d.done=!0,f.type==="resolve"?d.resolveOutput(d.latestValues):d.rejectOutput(f.error),d.messages.finalize?.(),d.toolCall.finalize?.(),d.nested.finalize?.())}return{__native:!0,init:()=>({subagents:t}),process(d){let f=d.params.namespace,g=d.params.data,x=d.method==="tasks"&&Z(g)&&"result"in g;d.method==="tools"&&Z(g)&&g.event==="tool-started"&&typeof g.tool_call_id=="string"&&g.tool_call_id.length>0&&r.set(xe(f),g.tool_call_id),d.method==="tasks"&&!x&&(l(f,g),u(g),c(f));for(let y of s.values())if(!y.done&&Bt(f,y.path)&&(y.messages.process(d),y.toolCall.process(d),y.nested.process(d),xe(f)===y.key)){if(d.method==="values"&&Z(g))y.latestValues=g;else if(d.method==="lifecycle"&&Z(g)){let w=g.event;w==="completed"||w==="interrupted"?h(y,{type:"resolve"}):w==="failed"&&h(y,{type:"reject",error:new Error(`Subagent ${y.name} failed`)})}}return!0},finalize(){for(let d of s.values())h(d,{type:"resolve"});t.close()},fail(d){for(let f of s.values())h(f,{type:"reject",error:d});t.fail(d)}}}}var lt=Symbol.for("langgraph-zod");lt in globalThis||(globalThis[lt]=new WeakSet);function Ut(e){let t=globalThis[lt];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){let o=this;return{metadata(n){return De(o,{jsonSchemaExtra:n})},reducer(n,r){return De(o,{default:Pe(o),reducer:{schema:r,fn:n}})}}}}),t.add(e))}try{Ut(i.ZodType.prototype),Ut(B.ZodType.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var zt=class extends Mt{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let o=t[0];if(o&&!o?.default){let n=Pe(e);n!=null&&(o.default=n)}return super.add(e,...t)}},Eo=new zt(be);function Ft(e=!0,t,o=[]){let n={jumpTo:new at},r={},s={},a=l=>{if(W.isInstance(l)){for(let[m,c]of Object.entries(l.fields))if(!(m in n)){if(n[m]=c,m.startsWith("_"))continue;oe.isInstance(c)?(r[m]=c.inputSchema||c.valueSchema,s[m]=c.valueSchema):(r[m]=c,s[m]=c)}return}let u=de(l);for(let[m,c]of Object.entries(u)){let h=m.startsWith("_");if(!(m in n)){if(Ie(c)){let d=be.get(c);if(d?.reducer){d.reducer.schema?(n[m]=new oe(c,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),h||(r[m]=d.reducer.schema,s[m]=c)):(n[m]=new oe(c,{reducer:d.reducer.fn}),h||(r[m]=c,s[m]=c));continue}}n[m]=c,h||(r[m]=c,s[m]=c)}}};t&&(W.isInstance(t)||F(t))&&a(t);for(let l of o)l.stateSchema&&(W.isInstance(l.stateSchema)||F(l.stateSchema))&&a(l.stateSchema);return e&&(s.structuredResponse=new at),{state:new W({messages:Le,...n}),input:new W({messages:Le,...r}),output:new W({messages:Le,...s})}}var ct=/<name>(.*?)<\/name>/s,dt=/<content>(.*?)<\/content>/s;function Ao(e,t){if(W.isInstance(e)){let o={};for(let n of Object.keys(e.fields))n in t&&(o[n]=t[n]);return o}if(Re(e))return te(e,t);throw new Error(`Invalid state schema type: ${typeof e}`)}function Ht(e){if(!T.isInstance(e)||Ze.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content=="string")return new T({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let o=[],n=0;for(let r of e.content)typeof r=="string"?(n+=1,o.push(`<name>${t}</name><content>${r}</content>`)):typeof r=="object"&&"type"in r&&r.type==="text"?(n+=1,o.push({...r,text:`<name>${t}</name><content>${r.text}</content>`})):o.push(r);return n||o.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new T({...e.lc_kwargs,content:o,name:void 0})}function Gt(e){if(!T.isInstance(e)||!e.content)return e;let t=[],o;if(Array.isArray(e.content))t=e.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let r=n.text.match(ct),s=n.text.match(dt);return r&&(!s||s[1]==="")?(o=r[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let r=n.text.match(ct),s=n.text.match(dt);return!r||!s?n:(o=r[1],{...n,text:s[1]})}return n});else{let n=e.content,r=n.match(ct),s=n.match(dt);if(!r||!s)return e;o=r[1],t=s[1]}return new T({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:o})}function ie(e){return Te.isRunnable(e)}function Wt(e){return _e(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}var ut=(e,t,o={})=>{if(Wt(e))return e.bindTools(t,o);if(Y.isRunnableBinding(e)&&Wt(e.bound)){let n=e.bound.bindTools(t,o);return Y.isRunnableBinding(n)?new Y({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new Y({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Be(e){if(typeof e=="function")return;let t=e;if(ue.isRunnableSequence(t)&&(t=t.steps.find(o=>Y.isRunnableBinding(o))||t),!pe(t)){if(Y.isRunnableBinding(t)){let o=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,n=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(o||n)throw new ve}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new ve}}function ge(e){return!!(T.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function Jt(e){if(e==null)return new z("");if(z.isInstance(e))return e;if(typeof e=="string")return new z({content:[{type:"text",text:e}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof e}`)}async function Vt(e,t,o={}){let n=ut(e,t,o);if(n)return n;if(pe(e)){let r=ut(await e._getModelInstance(),t,o);if(r)return r}if(ue.isRunnableSequence(e)){let r=e.steps.findIndex(s=>Y.isRunnableBinding(s)||_e(s)||pe(s));if(r>=0){let s=ut(e.steps[r],t,o);if(s){let a=e.steps.slice();return a.splice(r,1,s),ue.from(a)}}}throw new Error(`llm ${e} must define bindTools method.`)}function Io(e){if(e.length===0)return;if(e.length===1)return e[0];function t(n,r){return async(s,a)=>n(s,async u=>r(u,a))}let o=e[e.length-1];for(let n=e.length-2;n>=0;n--)o=t(e[n],o);return o}function Kt(e){let t=e.filter(o=>o.wrapToolCall);if(t.length!==0)return Io(t.map(o=>{let n=o.wrapToolCall;return async(s,a)=>{let l=s.state,u=new Set,m=async c=>{let h={...l,...c.state};try{return await a({...c,state:h})}catch(d){throw u.add(d),d}};try{let c=await n({...s,state:{messages:l.messages,...o.stateSchema?Ao(o.stateSchema,{...l}):{}}},m);if(!M.isInstance(c)&&!H(c))throw new Error(`Invalid response from "wrapToolCall" in middleware "${o.name}": expected ToolMessage or Command, got ${typeof c}`);return c}catch(c){throw u.has(c)?c:ne.wrap(c,o.name)}}}))}var Ro=["tags","metadata","runName","maxConcurrency","recursionLimit","configurable"];function Yt(e){let t={};for(let o of Ro){let n=e[o];n!==void 0&&(t[o]=n)}return t}async function Zt(e,t){let o={};for(let n of e){if(!n.stateSchema)continue;let r;if(W.isInstance(n.stateSchema)){let l={};for(let[u,m]of Object.entries(n.stateSchema.fields))oe.isInstance(m)?l[u]=m.inputSchema||m.valueSchema:l[u]=m;r=B.object(l)}else if(F(n.stateSchema))r=n.stateSchema;else continue;let s=await Tt(_t(r,l=>l.startsWith("_")),t);if(s.success){Object.assign(o,s.data);continue}let a=s.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
6
6
  `);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
7
7
  ${a}
8
8
 
@@ -21,11 +21,11 @@ To fix this, either:
21
21
  agent.invoke({
22
22
  messages: [...],
23
23
  ${s.error.issues[0]?.path.join(".")}: "value"
24
- })`)}return o}function Xt(e){let t={messages:U.custom(()=>[]),structuredResponse:U.any().optional()};if(!e)return U.object(t);let o;if(W.isInstance(e)){o={};for(let[r,s]of Object.entries(e.fields))oe.isInstance(s)?o[r]=s.inputSchema||s.valueSchema:o[r]=s}else if(F(e))o=de(e);else return U.object(t);let n={...t};for(let[r,s]of Object.entries(o))r.startsWith("_")?n[r]=s.optional():n[r]=s;return U.object(n)}function Qt(e){if(F(e))return xt(e);if(W.isInstance(e)){let t={};for(let[o,n]of Object.entries(e.fields)){let r;oe.isInstance(n)?r=n.inputSchema||n.valueSchema:r=n,t[o]=Ie(r)?r.optional():U.any().optional()}return U.object(t)}return U.object({})}function V(e){if(e){if(["model_request","tools",R].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return R;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function Ue(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}function Oo({apiKey:e,configuration:t={}}){let o=Rt({baseURL:t.baseURL,providerPath:"v1"});return{apiKey:e??t.apiKey??o.apiKey??(Ye("LANGSMITH_GATEWAY_API_KEY")||Ye("LANGSMITH_API_KEY")),configuration:{...t,baseURL:o.baseURL??`${It}/v1`},useResponsesApi:!0}}var Fe={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},langsmith:{package:"@langchain/openai",className:"ChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},eo=Object.keys(Fe);async function No(e,t){let o;if(t)o=Fe[t];else{let n=Object.entries(Fe).find(([,r])=>r.className===e);o=n?n[1]:void 0}if(o)try{return(await import(o.package))[o.className]}catch(n){let r=n;if("code"in r&&r.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in r&&typeof r.message=="string"){let s=(r.message.startsWith("Error: ")?r.message.slice(7):r.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function jo(e,t,o={}){let n=t||Lo(e);if(!n)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let r=Fe[n];if(!r){let l=eo.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
24
+ })`)}return o}function Xt(e){let t={messages:B.custom(()=>[]),structuredResponse:B.any().optional()};if(!e)return B.object(t);let o;if(W.isInstance(e)){o={};for(let[r,s]of Object.entries(e.fields))oe.isInstance(s)?o[r]=s.inputSchema||s.valueSchema:o[r]=s}else if(F(e))o=de(e);else return B.object(t);let n={...t};for(let[r,s]of Object.entries(o))r.startsWith("_")?n[r]=s.optional():n[r]=s;return B.object(n)}function Qt(e){if(F(e))return Ct(e);if(W.isInstance(e)){let t={};for(let[o,n]of Object.entries(e.fields)){let r;oe.isInstance(n)?r=n.inputSchema||n.valueSchema:r=n,t[o]=Ie(r)?r.optional():B.any().optional()}return B.object(t)}return B.object({})}function V(e){if(e){if(["model_request","tools",R].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return R;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function Ue(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}function Oo({apiKey:e,configuration:t={}}){let o=kt({baseURL:t.baseURL,providerPath:"v1"});return{apiKey:e??t.apiKey??o.apiKey??(Xe("LANGSMITH_GATEWAY_API_KEY")||Xe("LANGSMITH_API_KEY")),configuration:{...t,baseURL:o.baseURL??`${St}/v1`},useResponsesApi:!0}}var Fe={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},langsmith:{package:"@langchain/openai",className:"ChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},eo=Object.keys(Fe);async function No(e,t){let o;if(t)o=Fe[t];else{let n=Object.entries(Fe).find(([,r])=>r.className===e);o=n?n[1]:void 0}if(o)try{return(await import(o.package))[o.className]}catch(n){let r=n;if("code"in r&&r.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in r&&typeof r.message=="string"){let s=(r.message.startsWith("Error: ")?r.message.slice(7):r.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function jo(e,t,o={}){let n=t||Lo(e);if(!n)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let r=Fe[n];if(!r){let l=eo.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
25
25
 
26
- Supported model providers are: ${l}`)}let{modelProvider:s,...a}=o;return new(await No(r.className,n))({model:e,...a,...n==="langsmith"?Oo(a):{}})}function Lo(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("gpt-5")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?"openai":e.startsWith("claude")?"anthropic":e.startsWith("command")?"cohere":e.startsWith("accounts/fireworks")?"fireworks":e.startsWith("gemini")?"google-vertexai":e.startsWith("amazon.")?"bedrock":e.startsWith("mistral")?"mistralai":e.startsWith("sonar")||e.startsWith("pplx")?"perplexity":void 0}var qt=class ze extends rt{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(t){super(t),this._defaultConfig=t.defaultConfig??{},t.configurableFields==="any"?this._configurableFields="any":this._configurableFields=t.configurableFields??["model","modelProvider"],t.configPrefix?this._configPrefix=t.configPrefix.endsWith("_")?t.configPrefix:`${t.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=t.queuedMethodOperations??this._queuedMethodOperations,this._profile=t.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(t){let o=this._getCacheKey(t),n=this._modelInstanceCache.get(o);if(n)return n;let r={...this._defaultConfig,...this._modelParams(t)},s=await jo(r.model,r.modelProvider,r);for(let[a,l]of Object.entries(this._queuedMethodOperations))a in s&&typeof s[a]=="function"&&(s=await s[a](...l));return this._modelInstanceCache.set(o,s),s}async _generate(t,o,n){return(await this._getModelInstance(o))._generate(t,o??{},n)}bindTools(t,o){let n={...this._queuedMethodOperations};return n.bindTools=[t,o],new ze({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(t,...o)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[t,...o],new ze({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(t){let o=t?.configurable??{},n={};for(let[r,s]of Object.entries(o))if(r.startsWith(this._configPrefix)){let a=this._removePrefix(r,this._configPrefix);n[a]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([r])=>this._configurableFields.includes(r)))),n}_removePrefix(t,o){return t.startsWith(o)?t.slice(o.length):t}withConfig(t){let o={...t||{}},n=this._modelParams(o),r=Object.fromEntries(Object.entries(o).filter(([s])=>s!=="configurable"));return r.configurable=Object.fromEntries(Object.entries(o.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new Y({config:o,bound:new ze({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(t,o){let n=await this._getModelInstance(o),r=ce(o);return n.invoke(t,r)}async stream(t,o){let n=new Tt({generator:await(await this._getModelInstance(o)).stream(t,o),config:o});return await n.setup,et.fromAsyncGenerator(n)}async batch(t,o,n){return super.batch(t,o,n)}async*transform(t,o){let n=await this._getModelInstance(o),r=ce(o);yield*n.transform(t,r)}async*streamLog(t,o,n){let r=await this._getModelInstance(o),s=ce(o);yield*r.streamLog(t,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(t,o,n){if(o?.version==="v1"||o?.version==="v2"){let a=this,l=o;async function*u(){let m=await a._getModelInstance(l),c={...ce(l),version:l.version,...l.encoding!==void 0?{encoding:l.encoding}:{}},h;l.version==="v1"&&l.encoding==="text/event-stream"||l.version==="v1"||l.version==="v2"&&l.encoding,h=m.streamEvents(t,c,n);for await(let d of h)yield d}return et.fromAsyncGenerator(u())}let r=this;async function*s(){let a=await r._getModelInstance(o),l=ce(o);yield*a.streamEvents(t,l)}return new Et(s())}get profile(){if(this._profile)return this._profile;let t=this._getCacheKey({});return this._modelInstanceCache.get(t)?.profile??{}}_getCacheKey(t){let o=t??{};if(o.configurable){let{configurable:n}=o,r={};for(let[s,a]of Object.entries(n))s.startsWith("__pregel_")||(r[s]=a);o={...o,configurable:r}}return JSON.stringify(o)}};async function ee(e,t){let{configurableFields:o,configPrefix:n,modelProvider:r,profile:s,...a}={configPrefix:"",...t??{}};if(r===void 0&&e?.includes(":")){let[c,...h]=e.split(":"),d=h.length===0?[c]:[c,h.join(":")];eo.includes(d[0])&&([r,e]=d)}let l=Array.isArray(o)?[...o]:o;!e&&l===void 0&&(l=["model","modelProvider"]),n&&l===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...a},m;return l===void 0?m=new qt({defaultConfig:{...u,model:e,modelProvider:r},configPrefix:n,profile:s}):(e&&(u.model=e),r&&(u.modelProvider=r),m=new qt({defaultConfig:u,configPrefix:n,configurableFields:l,profile:s})),await m._getModelInstance(),m}var we=class extends Te{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){let o=B(this.config,t),n=await qe.runWithConfig(o,async()=>this.func(e,o));return Te.isRunnable(n)&&this.recurse?await qe.runWithConfig(o,async()=>n.invoke(e,o)):(this.#e=n,n)}};function to(e,t){let o,n;if(t==="inline")o=Ht,n=Gt;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function r(s){return s.map(o)}return ue.from([Ne.from(r),e,Ne.from(n)])}function Do(e){return T.isInstance(e)||H(e)||typeof e=="object"&&e!==null&&"structuredResponse"in e&&"messages"in e}var P="model_request",oo=class extends we{#e;#o;constructor(e){super({name:e.name??"model",func:(t,o)=>this.#t(t,o)}),this.#e=e,this.#o=e.systemMessage}async#r(e,t=this.#e.responseFormat){if(!t)return;let o;pe(e)?o=await e._getModelInstance():typeof e!="string"&&(o=e);let n=$t(t,void 0,o);if(n.length!==0)return n.every(r=>r instanceof q)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(r=>r instanceof G).reduce((r,s)=>(r[s.name]=s,r),{})}}async#t(e,t){let o=e.messages.at(-1);if(o&&M.isInstance(o)&&o.name&&this.#e.shouldReturnDirect.has(o.name))return[new L({update:{messages:[]}})];let{response:n,lastAiMessage:r,collectedCommands:s}=await this.#a(e,t);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:m}=n;return{messages:[...e.messages,...m],structuredResponse:u}}let a=[],l=T.isInstance(n)?n:r;return l&&(l.name=this.name,l.lc_kwargs.name=this.name,this.#c(e,l)?a.push(new L({update:{messages:[new T({content:"Sorry, need more steps to process this request.",name:this.name,id:l.id})]}})):a.push(new L({update:{messages:[l]}}))),H(n)&&!s.includes(n)&&a.push(n),a.push(...s),a}#s(){if(typeof this.#e.model=="string")return ee(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(e,t,o={}){let n=await this.#s(),r=t,s=this.#o,a=null,l=[],u=async d=>{Be(d.model);let f=await this.#r(d.model,d.responseFormat),g=await this.#d(d.model,d,f),x=[...s.text===""?[]:[s],...d.messages],y=Ue(this.#e.signal,t.signal),w=await Mt(g.invoke(x,{...t,signal:y}),y);if(a=w,f?.type==="native"){let N=f.strategy.parse(w);if(N)return{structuredResponse:N,messages:[w]};if(!w.tool_calls||w.tool_calls.length===0)throw new me(typeof f.strategy.schema?.title=="string"?f.strategy.schema.title:"providerStrategy",["Model output did not satisfy the provided response schema."]);return w}if(!f||!w.tool_calls)return w;let O=w.tool_calls.filter(N=>N.name in f.tools);if(O.length===0)return w;if(O.length>1)return this.#i(w,O,f);let A=f.tools[O[0].name]?.options?.toolMessageContent;return this.#l(w,O[0],f,A??o.lastMessage)},m=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let d=m.length-1;d>=0;d--){let f=m[d],g=Array.isArray(f)?f[0]:f;if(g.wrapModelCall){let x=c,y=g;c=async w=>{let O=s,A=y.contextSchema?te(y.contextSchema,r?.context||{}):r?.context,N=Object.freeze({context:A,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal}),K={...w,state:{...g.stateSchema?te(Qt(g.stateSchema),e):{},messages:e.messages},runtime:N},j=async b=>{s=O;let J=b.tools??[],le=new Map(this.#e.toolClasses.filter(ie).map(_=>[_.name,_])),Ee=J.filter(_=>ie(_)&&!le.has(_.name)),ye=J.filter(_=>{if(!ie(_))return!1;let v=le.get(_.name);return v!=null&&v!==_});if(Ee.length>0&&!this.#e.middleware?.some(_=>_.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${y.name}": ${Ee.map(_=>_.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(ye.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${y.name}": ${ye.map(_=>_.name).join(", ")}. This is not supported.`);let p=b,C=b.systemPrompt!==s.text,I=b.systemMessage!==s;if(C&&I)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");C&&(s=new z({content:[{type:"text",text:b.systemPrompt}]}),p={...b,systemPrompt:s.text,systemMessage:s}),I&&(s=new z({...b.systemMessage}),p={...b,systemPrompt:s.text,systemMessage:s});let k=await x(p);return H(k)&&a?(l.includes(k)||l.push(k),a):k};if(!y.wrapModelCall)return j(K);try{let b=await y.wrapModelCall(K,j);if(!Do(b))throw new Error(`Invalid response from "wrapModelCall" in middleware "${y.name}": expected AIMessage or Command, got ${typeof b}`);return T.isInstance(b)?a=b:H(b)&&l.push(b),b}catch(b){throw ne.wrap(b,y.name)}}}}s=this.#o;let h={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:r?.context,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal})};return{response:await c(h),lastAiMessage:a,collectedCommands:l}}#i(e,t,o){let n=new Ce(t.map(r=>r.name));return this.#n(n,e,t[0],o)}#l(e,t,o,n){let r=o.tools[t.name];try{let s=r.parse(t.args);return{structuredResponse:s,messages:[e,new M({tool_call_id:t.id??"",content:JSON.stringify(s),name:t.name}),new T(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#n(s,e,t,o)}}async#n(e,t,o,n){let r=Object.values(n.tools).at(0)?.options?.handleError,s=o.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(r===!1)throw e;if(r===void 0||typeof r=="boolean"&&r||Array.isArray(r)&&r.some(a=>a instanceof Ce))return new L({update:{messages:[t,new M({content:e.message,tool_call_id:s})]},goto:P});if(typeof r=="string")return new L({update:{messages:[t,new M({content:r,tool_call_id:s})]},goto:P});if(typeof r=="function"){let a=await r(e);if(typeof a!="string")throw new Error("Error handler must return a string.");return new L({update:{messages:[t,new M({content:a,tool_call_id:s})]},goto:P})}return new L({update:{messages:[t,new M({content:e.message,tool_call_id:s})]},goto:P})}#c(e,t){let o=T.isInstance(t)&&t.tool_calls?.every(r=>this.#e.shouldReturnDirect.has(r.name)),n="remainingSteps"in e?e.remainingSteps:void 0;return!!(n&&(n<1&&o||n<2&&ge(e.messages.at(-1))))}async#d(e,t,o){let n={},r=Object.values(o&&"tools"in o?o.tools:{}),s=[...t?.tools??this.#e.toolClasses,...r.map(u=>u.tool)],a=t?.toolChoice||(r.length>0?"any":void 0);if(o?.type==="native"){let u=t?.modelSettings?.strict??o?.strategy?.strict??!0,m={name:o.strategy.schema?.name??"extract",description:_t(o.strategy.schema),schema:o.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:m},outputConfig:{format:{type:"json_schema",schema:o.strategy.schema}},responseSchema:o.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:o.strategy.schema},strict:t?.modelSettings?.strict})}let l=await Vt(e,s,{...n,...t?.modelSettings,tool_choice:a});return this.#e.includeAgentName==="inline"?to(l,this.#e.includeAgentName):l}getState(){let e=super.getState();return{messages:[],...e&&!H(e)?e:{}}}};var no=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(", ")}].`,D="tools",ro=e=>Array.isArray(e)&&e.every(Ze.isInstance),$o=e=>typeof e=="object"&&e!=null&&"messages"in e&&ro(e.messages),Bo=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function Uo(e,t){return fe.isInstance(e)?new M({content:e.message,tool_call_id:t.id,name:t.name}):new M({content:`${e}
27
- Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var so=class extends we{options;tools;trace=!1;signal;handleToolErrors=Uo;wrapToolCall;constructor(e,t){let{name:o,tags:n,handleToolErrors:r,signal:s,wrapToolCall:a}=t??{};super({name:o,tags:n,func:(l,u)=>this.run(l,u)}),this.options=t,this.tools=e,this.handleToolErrors=r??this.handleToolErrors,this.signal=s,this.wrapToolCall=a}#e(e,t,o){if(pt(e)||this.signal?.aborted)throw e;let n=e,r=o;if(o){let s=e;for(;ne.isInstance(s);)s=s.cause;fe.isInstance(s)&&(n=s,r=!1)}if(r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw n;if(typeof this.handleToolErrors=="function"){let s=this.handleToolErrors(n,t);if(s&&M.isInstance(s))return s;throw n}else if(this.handleToolErrors)return new M({name:t.name,content:`${n}
28
- Please fix your mistakes.`,tool_call_id:t.id});throw n}async runTool(e,t,o){let n=t,r={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===e.name),a=async u=>{let{toolCall:m,tool:c}=u,h=c??this.tools.find(f=>f.name===m.name);if(h===void 0){let f=this.tools.map(g=>g.name);return new M({content:no(m.name,f),tool_call_id:m.id,name:m.name,status:"error"})}let d=h;try{let f=await d.invoke({...m,type:"tool_call"},{...t,config:t,toolCallId:m.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Ue(this.signal,t.signal)});return M.isInstance(f)||H(f)?f:new M({name:d.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:m.id})}catch(f){throw f instanceof wt?new fe(f,m):f}},l={toolCall:e,tool:s,state:o,runtime:r};if(this.wrapToolCall)try{return await this.wrapToolCall(l,a)}catch(u){return this.#e(u,e,!0)}if(!s){let u=this.tools.map(m=>m.name);return new M({content:no(e.name,u),tool_call_id:e.id,name:e.name,status:"error"})}try{return await a(l)}catch(u){return this.#e(u,e,!1)}}async run(e,t){let o;if(Bo(e)){let{lg_tool_call:s,jumpTo:a,...l}=e;o=[await this.runTool(e.lg_tool_call,t,l)]}else{let s;if(ro(e))s=e;else if($o(e))s=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),l;for(let u=s.length-1;u>=0;u-=1){let m=s[u];if(T.isInstance(m)){l=m;break}}if(!T.isInstance(l))throw new Error("ToolNode only accepts AIMessages as input.");o=await Promise.all(l.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,t,e))??[])}if(!o.some(H))return Array.isArray(e)?o:{messages:o};let n=[],r=null;for(let s of o)H(s)?s.graph===L.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>zo(a))?r?r.goto.push(...s.goto):r=new L({graph:L.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(e)?[s]:{messages:[s]});return r&&n.push(r),n}};function zo(e){return e instanceof $}function Se(e,t){let n=0;if(t&&t.length>0){let r=0;for(let s of t){let a=st(s)?At(s):s;r+=JSON.stringify(a).length}n+=r}for(let r of e){let s;typeof r.content=="string"?s=r.content:Array.isArray(r.content)?s=r.content.map(a=>typeof a=="string"?a:a.type==="text"&&"text"in a?a.text:"").join(""):s="",T.isInstance(r)&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0&&(s+=JSON.stringify(r.tool_calls)),M.isInstance(r)&&(s+=r.tool_call_id??""),n+=s.length}return Math.ceil(n/4)}function X(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function re(e){return typeof e=="function"?e:e.hook}var Fo=class{},Wo=class{},se=class extends we{constructor(e){super(e)}async invokeMiddleware(e,t){let o={};if(this.middleware.contextSchema&&F(this.middleware.contextSchema)){let u=de(this.middleware.contextSchema);if(u){let m={},c=t?.context||{};for(let h of Object.keys(u))h in c&&(m[h]=c[h]);o=te(this.middleware.contextSchema,m)}}let n={...e,messages:e.messages},r={context:o,store:t?.store,configurable:t?.configurable,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new Wo,{...r,context:Object.freeze(Object.assign(new Fo,o))})));if(!s)return{jumpTo:void 0};let a,l;if(this.name?.startsWith("BeforeAgentNode_")?(a=X(this.middleware.beforeAgent),l="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=X(this.middleware.beforeModel),l="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=X(this.middleware.afterAgent),l="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=X(this.middleware.afterModel),l="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:l?`no ${l} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:Xt(this.middleware.stateSchema)}}};var ao=class extends se{middleware;lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(e){super({name:`BeforeAgentNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.beforeAgent)(e,t)}};var io=class extends se{middleware;lc_namespace=["langchain","agents","beforeModelNodes"];constructor(e){super({name:`BeforeModelNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.beforeModel)(e,t)}};var lo=class extends se{middleware;lc_namespace=["langchain","agents","afterModelNodes"];constructor(e){super({name:`AfterModelNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.afterModel)(e,t)}};var co=class extends se{middleware;lc_namespace=["langchain","agents","afterAgentNodes"];constructor(e){super({name:`AfterAgentNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.afterAgent)(e,t)}};var uo=class mo{options;#e;#o="v2";#r;#t;constructor(t,o){if(this.options=t,this.#t=B(o??{},{metadata:{ls_integration:"langchain_create_agent"},configurable:{ls_agent_type:"root"}}),t.name&&(this.#t=B(this.#t,{metadata:{lc_agent_name:t.name}})),this.#o=t.version??this.#o,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Be(t.model);let n=this.options.middleware?.filter(p=>p.tools).flatMap(p=>p.tools)??[],r=[...t.tools??[],...n],s=new Set(r.filter(ie).filter(p=>"returnDirect"in p&&p.returnDirect).map(p=>p.name)),a=!!this.options.middleware?.some(p=>p.wrapModelCall),{state:l,input:u,output:m}=Ft(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new Nt(l,{input:u,output:m,context:this.options.contextSchema}),h=[],d=[],f=[],g=[],x=[];this.#r=new oo({model:this.options.model,systemMessage:Jt(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:r,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:x});let y=new Set,w=this.options.middleware??[];for(let p=0;p<w.length;p++){let C,I,k,_,v=w[p];if(y.has(v.name))throw new Error(`Middleware ${v.name} is defined multiple times`);if(y.add(v.name),v.beforeAgent){C=new ao(v);let S=`${v.name}.before_agent`;h.push({index:p,name:S,allowed:X(v.beforeAgent)}),c.addNode(S,C,C.nodeOptions)}if(v.beforeModel){I=new io(v);let S=`${v.name}.before_model`;d.push({index:p,name:S,allowed:X(v.beforeModel)}),c.addNode(S,I,I.nodeOptions)}if(v.afterModel){k=new lo(v);let S=`${v.name}.after_model`;f.push({index:p,name:S,allowed:X(v.afterModel)}),c.addNode(S,k,k.nodeOptions)}if(v.afterAgent){_=new co(v);let S=`${v.name}.after_agent`;g.push({index:p,name:S,allowed:X(v.afterAgent)}),c.addNode(S,_,_.nodeOptions)}v.wrapModelCall&&x.push(v)}c.addNode(P,this.#r);let O=w.some(p=>p.wrapToolCall),A=r.filter(ie);if(A.length>0||O){let p=new so(A,{signal:this.options.signal,wrapToolCall:Kt(w)});c.addNode(D,p)}let N;h.length>0?N=h[0].name:d.length>0?N=d[0].name:N=P;let K=d.length>0?d[0].name:P,j=g.length>0?g[g.length-1].name:R;c.addEdge(ft,N);let b=A.length>0||O;for(let p=0;p<h.length;p++){let C=h[p],I=C.name,k=p===h.length-1?K:h[p+1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._.map(S=>S===R?j:S)]));c.addConditionalEdges(I,this.#c(A,k,j,b),v)}else c.addEdge(I,k)}for(let p=0;p<d.length;p++){let C=d[p],I=C.name,k=p===d.length-1?P:d[p+1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));c.addConditionalEdges(I,this.#d(A,k,b),v)}else c.addEdge(I,k)}let J=f.at(-1);if(f.length>0&&J)c.addEdge(P,J.name);else{let p=this.#s(A,!1,b).map(C=>C===R?j:C);p.length===1?c.addEdge(P,p[0]):c.addConditionalEdges(P,this.#i(j),p)}for(let p=f.length-1;p>0;p--){let C=f[p],I=C.name,k=f[p-1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));c.addConditionalEdges(I,this.#n(A,C.allowed,k,b),v)}else c.addEdge(I,k)}if(f.length>0){let p=f[0],C=p.name,I=this.#s(A,!0,b).filter(v=>v!=="tools"||b),k=!!(p.allowed&&p.allowed.length>0),_=I.map(v=>v===R?j:v);c.addConditionalEdges(C,this.#l(A,k,j,b),_)}for(let p=g.length-1;p>0;p--){let C=g[p],I=C.name,k=g[p-1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));c.addConditionalEdges(I,this.#n(A,C.allowed,k,b),v)}else c.addEdge(I,k)}if(g.length>0){let p=g[0],C=p.name;if(p.allowed&&p.allowed.length>0){let I=p.allowed.map(_=>V(_)).filter(_=>_!=="tools"||b),k=Array.from(new Set([R,...I]));c.addConditionalEdges(C,this.#n(A,p.allowed,R,b),k)}else c.addEdge(C,R)}if(b){let p=K;s.size>0?c.addConditionalEdges(D,this.#a(s,j,p),[p,j]):c.addEdge(D,p)}let le=(this.options.middleware??[]).flatMap(p=>p.streamTransformers??[]),Ee=[ae([]),he([]),...le,...this.options.streamTransformers??[]];this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description,transformers:Ee});let ye=Yt(this.#t);Object.keys(ye).length>0&&(this.#e=this.#e.withConfig(ye))}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(t){this.#e.checkpointer=t}get store(){return this.#e.store}set store(t){this.#e.store=t}withConfig(t){return new mo(this.options,B(this.#t,t))}#s(t,o=!1,n=t.length>0){let r=[];return n&&r.push(D),o&&r.push(P),r.push(R),r}#a(t,o,n){return r=>{let s=r.messages,a=s[s.length-1];return M.isInstance(a)&&a.name&&t.has(a.name)?this.options.responseFormat?n:o:n}}#i(t=R){return o=>{let n=o.messages.at(-1);if(!T.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return t;if(this.#o==="v1")return D;let r=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return r.length===0?t:r.map(s=>new $(D,{...o,lg_tool_call:s}))}}#l(t,o,n,r=t.length>0){let s=!!this.options.responseFormat;return a=>{let l=a,u=l.messages,m=u.at(-1);if(T.isInstance(m)&&(!m.tool_calls||m.tool_calls.length===0))return n;if(o&&l.jumpTo){let w=V(l.jumpTo);return w===R?n:w==="tools"?r?new $(D,{...a,jumpTo:void 0}):n:new $(P,{...a,jumpTo:void 0})}let c=u.filter(M.isInstance),h=u.filter(T.isInstance).at(-1),d=h?.tool_calls?.filter(w=>!c.some(O=>O.tool_call_id===w.id));if(d&&d.length>0)return this.#o==="v1"?D:d.map(w=>new $(D,{...a,lg_tool_call:w}));let f=h?.tool_calls?.some(w=>w.name.startsWith("extract-"));if(d&&d.length===0&&!f&&s)return P;if(!T.isInstance(m)||!m.tool_calls||m.tool_calls.length===0)return n;let g=m.tool_calls.every(w=>w.name.startsWith("extract-")),x=m.tool_calls.some(w=>!w.name.startsWith("extract-"));if(g||!x)return n;if(this.#o==="v1")return D;let y=m.tool_calls.filter(w=>!w.name.startsWith("extract-"));return y.length===0?n:y.map(w=>new $(D,{...a,lg_tool_call:w}))}}#n(t,o,n,r=t.length>0){let s=new Set(o.map(a=>V(a)));return a=>{let l=a;if(l.jumpTo){let u=V(l.jumpTo);if(u===R&&s.has(R))return R;if(u==="tools"&&s.has("tools"))return r?new $(D,{...a,jumpTo:void 0}):R;if(u==="model_request"&&s.has("model_request"))return new $(P,{...a,jumpTo:void 0})}return n}}#c(t,o,n,r=t.length>0){return s=>{let a=s;if(!a.jumpTo)return o;let l=V(a.jumpTo);return l===R?n:l==="tools"?r?new $(D,{...s,jumpTo:void 0}):n:new $(P,{...s,jumpTo:void 0})}}#d(t,o,n=t.length>0){return r=>{let s=r;if(!s.jumpTo)return o;let a=V(s.jumpTo);return a===R?R:a==="tools"?n?new $(D,{...r,jumpTo:void 0}):R:new $(P,{...r,jumpTo:void 0})}}async#u(t,o){if(!this.options.middleware||this.options.middleware.length===0||t instanceof L||!t)return t;let n=await Zt(this.options.middleware,t),r={...(await this.#e.getState(o).catch(()=>({values:{}}))).values,...t};if(!r)return r;for(let[s,a]of Object.entries(n))s in r||(r[s]=a);return r}async invoke(t,o){let n=B(this.#t,o),r=await this.#u(t,n);return this.#e.invoke(r,n)}async stream(t,o){let n=B(this.#t,o),r=await this.#u(t,n);return this.#e.stream(r,n)}streamEvents(t,o,n){if(o?.version!=="v3"||n!=null){let r=B(this.#t,o),s=o?.version==="v1"||o?.version==="v2"?o.version:"v2";return this.#e.streamEvents(t,{...r,version:s},n)}return(async()=>{let{transformers:r,version:s,...a}=o??{},l=B(this.#t,a),u=await this.#u(t,l);return await this.#e.streamEvents(u,{...l,version:"v3",transformers:r})})()}async drawMermaidPng(t){let o=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(o)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,o){return this.#e.getState(t,o)}getStateHistory(t,o){return this.#e.getStateHistory(t,o)}getSubgraphs(t,o){return this.#e.getSubgraphs(t,o)}getSubgraphsAsync(t,o){return this.#e.getSubgraphsAsync(t,o)}updateState(t,o,n){return this.#e.updateState(t,o,n)}get builder(){return this.#e.builder}};function Vo(e){return new uo(e)}var Yo=i.function().args(i.custom()).returns(i.union([i.boolean(),i.promise(i.boolean())])),Zo=i.function().args(i.custom(),i.custom(),i.custom()).returns(i.union([i.string(),i.promise(i.string())])),Xo=["approve","edit","reject"],Qo=i.enum(Xo),qo=i.object({allowedDecisions:i.array(Qo),description:i.union([i.string(),Zo]).optional(),argsSchema:i.record(i.any()).optional(),when:Yo.optional()}),qa=i.object({interruptOn:i.record(i.union([i.boolean(),qo])).optional(),descriptionPrefix:i.string().default("Tool execution requires approval")});var We="nostream",He=i.object({maxRetries:i.number().min(0).default(2),retryOn:i.union([i.function().args(i.instanceof(Error)).returns(i.boolean()),i.array(i.custom())]).default(()=>e=>gt(e)??!0),backoffFactor:i.number().min(0).default(2),initialDelayMs:i.number().min(0).default(1e3),maxDelayMs:i.number().min(0).default(6e4),jitter:i.boolean().default(!0)});var Ge=`<role>
26
+ Supported model providers are: ${l}`)}let{modelProvider:s,...a}=o;return new(await No(r.className,n))({model:e,...a,...n==="langsmith"?Oo(a):{}})}function Lo(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("gpt-5")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?"openai":e.startsWith("claude")?"anthropic":e.startsWith("command")?"cohere":e.startsWith("accounts/fireworks")?"fireworks":e.startsWith("gemini")?"google-vertexai":e.startsWith("amazon.")?"bedrock":e.startsWith("mistral")?"mistralai":e.startsWith("sonar")||e.startsWith("pplx")?"perplexity":void 0}var qt=class ze extends rt{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(t){super(t),this._defaultConfig=t.defaultConfig??{},t.configurableFields==="any"?this._configurableFields="any":this._configurableFields=t.configurableFields??["model","modelProvider"],t.configPrefix?this._configPrefix=t.configPrefix.endsWith("_")?t.configPrefix:`${t.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=t.queuedMethodOperations??this._queuedMethodOperations,this._profile=t.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(t){let o=this._getCacheKey(t),n=this._modelInstanceCache.get(o);if(n)return n;let r={...this._defaultConfig,...this._modelParams(t)},s=await jo(r.model,r.modelProvider,r);for(let[a,l]of Object.entries(this._queuedMethodOperations))a in s&&typeof s[a]=="function"&&(s=await s[a](...l));return this._modelInstanceCache.set(o,s),s}async _generate(t,o,n){return(await this._getModelInstance(o))._generate(t,o??{},n)}bindTools(t,o){let n={...this._queuedMethodOperations};return n.bindTools=[t,o],new ze({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(t,...o)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[t,...o],new ze({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(t){let o=t?.configurable??{},n={};for(let[r,s]of Object.entries(o))if(r.startsWith(this._configPrefix)){let a=this._removePrefix(r,this._configPrefix);n[a]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([r])=>this._configurableFields.includes(r)))),n}_removePrefix(t,o){return t.startsWith(o)?t.slice(o.length):t}withConfig(t){let o={...t||{}},n=this._modelParams(o),r=Object.fromEntries(Object.entries(o).filter(([s])=>s!=="configurable"));return r.configurable=Object.fromEntries(Object.entries(o.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new Y({config:o,bound:new ze({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(t,o){let n=await this._getModelInstance(o),r=ce(o);return n.invoke(t,r)}async stream(t,o){let n=new yt({generator:await(await this._getModelInstance(o)).stream(t,o),config:o});return await n.setup,qe.fromAsyncGenerator(n)}async batch(t,o,n){return super.batch(t,o,n)}async*transform(t,o){let n=await this._getModelInstance(o),r=ce(o);yield*n.transform(t,r)}async*streamLog(t,o,n){let r=await this._getModelInstance(o),s=ce(o);yield*r.streamLog(t,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(t,o,n){if(o?.version==="v1"||o?.version==="v2"){let a=this,l=o;async function*u(){let m=await a._getModelInstance(l),c={...ce(l),version:l.version,...l.encoding!==void 0?{encoding:l.encoding}:{}},h;l.version==="v1"&&l.encoding==="text/event-stream"||l.version==="v1"||l.version==="v2"&&l.encoding,h=m.streamEvents(t,c,n);for await(let d of h)yield d}return qe.fromAsyncGenerator(u())}let r=this;async function*s(){let a=await r._getModelInstance(o),l=ce(o);yield*a.streamEvents(t,l)}return new At(s())}get profile(){if(this._profile)return this._profile;let t=this._getCacheKey({});return this._modelInstanceCache.get(t)?.profile??{}}_getCacheKey(t){let o=t??{};if(o.configurable){let{configurable:n}=o,r={};for(let[s,a]of Object.entries(n))s.startsWith("__pregel_")||(r[s]=a);o={...o,configurable:r}}return JSON.stringify(o)}};async function ee(e,t){let{configurableFields:o,configPrefix:n,modelProvider:r,profile:s,...a}={configPrefix:"",...t??{}};if(r===void 0&&e?.includes(":")){let[c,...h]=e.split(":"),d=h.length===0?[c]:[c,h.join(":")];eo.includes(d[0])&&([r,e]=d)}let l=Array.isArray(o)?[...o]:o;!e&&l===void 0&&(l=["model","modelProvider"]),n&&l===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...a},m;return l===void 0?m=new qt({defaultConfig:{...u,model:e,modelProvider:r},configPrefix:n,profile:s}):(e&&(u.model=e),r&&(u.modelProvider=r),m=new qt({defaultConfig:u,configPrefix:n,configurableFields:l,profile:s})),await m._getModelInstance(),m}var we=class extends Te{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){let o=$(this.config,t),n=await Qe.runWithConfig(o,async()=>this.func(e,o));return Te.isRunnable(n)&&this.recurse?await Qe.runWithConfig(o,async()=>n.invoke(e,o)):(this.#e=n,n)}};function to(e,t){let o,n;if(t==="inline")o=Ht,n=Gt;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function r(s){return s.map(o)}return ue.from([Ne.from(r),e,Ne.from(n)])}function Do(e){return T.isInstance(e)||H(e)||typeof e=="object"&&e!==null&&"structuredResponse"in e&&"messages"in e}var P="model_request",oo=class extends we{#e;#o;constructor(e){super({name:e.name??"model",func:(t,o)=>this.#t(t,o)}),this.#e=e,this.#o=e.systemMessage}async#r(e,t=this.#e.responseFormat){if(!t)return;let o;pe(e)?o=await e._getModelInstance():typeof e!="string"&&(o=e);let n=$t(t,void 0,o);if(n.length!==0)return n.every(r=>r instanceof q)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(r=>r instanceof G).reduce((r,s)=>(r[s.name]=s,r),{})}}async#t(e,t){let o=e.messages.at(-1);if(o&&M.isInstance(o)&&o.name&&this.#e.shouldReturnDirect.has(o.name))return[new L({update:{messages:[]}})];let{response:n,lastAiMessage:r,collectedCommands:s}=await this.#a(e,t);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:m}=n;return{messages:[...e.messages,...m],structuredResponse:u}}let a=[],l=T.isInstance(n)?n:r;return l&&(l.name=this.name,l.lc_kwargs.name=this.name,this.#c(e,l)?a.push(new L({update:{messages:[new T({content:"Sorry, need more steps to process this request.",name:this.name,id:l.id})]}})):a.push(new L({update:{messages:[l]}}))),H(n)&&!s.includes(n)&&a.push(n),a.push(...s),a}#s(){if(typeof this.#e.model=="string")return ee(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(e,t,o={}){let n=await this.#s(),r=t,s=this.#o,a=null,l=[],u=async d=>{Be(d.model);let f=await this.#r(d.model,d.responseFormat),g=await this.#d(d.model,d,f),x=[...s.text===""?[]:[s],...d.messages],y=Ue(this.#e.signal,t.signal),w=await wt(g.invoke(x,{...t,signal:y}),y);if(a=w,f?.type==="native"){let N=f.strategy.parse(w);if(N)return{structuredResponse:N,messages:[w]};if(!w.tool_calls||w.tool_calls.length===0)throw new me(typeof f.strategy.schema?.title=="string"?f.strategy.schema.title:"providerStrategy",["Model output did not satisfy the provided response schema."]);return w}if(!f||!w.tool_calls)return w;let O=w.tool_calls.filter(N=>N.name in f.tools);if(O.length===0)return w;if(O.length>1)return this.#i(w,O,f);let A=f.tools[O[0].name]?.options?.toolMessageContent;return this.#l(w,O[0],f,A??o.lastMessage)},m=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let d=m.length-1;d>=0;d--){let f=m[d],g=Array.isArray(f)?f[0]:f;if(g.wrapModelCall){let x=c,y=g;c=async w=>{let O=s,A=y.contextSchema?te(y.contextSchema,r?.context||{}):r?.context,N=Object.freeze({context:A,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal}),K={...w,state:{...g.stateSchema?te(Qt(g.stateSchema),e):{},messages:e.messages},runtime:N},j=async b=>{s=O;let J=b.tools??[],le=new Map(this.#e.toolClasses.filter(ie).map(_=>[_.name,_])),Ee=J.filter(_=>ie(_)&&!le.has(_.name)),ye=J.filter(_=>{if(!ie(_))return!1;let v=le.get(_.name);return v!=null&&v!==_});if(Ee.length>0&&!this.#e.middleware?.some(_=>_.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${y.name}": ${Ee.map(_=>_.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(ye.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${y.name}": ${ye.map(_=>_.name).join(", ")}. This is not supported.`);let p=b,C=b.systemPrompt!==s.text,I=b.systemMessage!==s;if(C&&I)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");C&&(s=new z({content:[{type:"text",text:b.systemPrompt}]}),p={...b,systemPrompt:s.text,systemMessage:s}),I&&(s=new z({...b.systemMessage}),p={...b,systemPrompt:s.text,systemMessage:s});let k=await x(p);return H(k)&&a?(l.includes(k)||l.push(k),a):k};if(!y.wrapModelCall)return j(K);try{let b=await y.wrapModelCall(K,j);if(!Do(b))throw new Error(`Invalid response from "wrapModelCall" in middleware "${y.name}": expected AIMessage or Command, got ${typeof b}`);return T.isInstance(b)?a=b:H(b)&&l.push(b),b}catch(b){throw ne.wrap(b,y.name)}}}}s=this.#o;let h={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:r?.context,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal})};return{response:await c(h),lastAiMessage:a,collectedCommands:l}}#i(e,t,o){let n=new Ce(t.map(r=>r.name));return this.#n(n,e,t[0],o)}#l(e,t,o,n){let r=o.tools[t.name];try{let s=r.parse(t.args);return{structuredResponse:s,messages:[e,new M({tool_call_id:t.id??"",content:JSON.stringify(s),name:t.name}),new T(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#n(s,e,t,o)}}async#n(e,t,o,n){let r=Object.values(n.tools).at(0)?.options?.handleError,s=o.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(r===!1)throw e;if(r===void 0||typeof r=="boolean"&&r||Array.isArray(r)&&r.some(a=>a instanceof Ce))return new L({update:{messages:[t,new M({content:e.message,tool_call_id:s})]},goto:P});if(typeof r=="string")return new L({update:{messages:[t,new M({content:r,tool_call_id:s})]},goto:P});if(typeof r=="function"){let a=await r(e);if(typeof a!="string")throw new Error("Error handler must return a string.");return new L({update:{messages:[t,new M({content:a,tool_call_id:s})]},goto:P})}return new L({update:{messages:[t,new M({content:e.message,tool_call_id:s})]},goto:P})}#c(e,t){let o=T.isInstance(t)&&t.tool_calls?.every(r=>this.#e.shouldReturnDirect.has(r.name)),n="remainingSteps"in e?e.remainingSteps:void 0;return!!(n&&(n<1&&o||n<2&&ge(e.messages.at(-1))))}async#d(e,t,o){let n={},r=Object.values(o&&"tools"in o?o.tools:{}),s=[...t?.tools??this.#e.toolClasses,...r.map(u=>u.tool)],a=t?.toolChoice||(r.length>0?"any":void 0);if(o?.type==="native"){let u=t?.modelSettings?.strict??o?.strategy?.strict??!0,m={name:o.strategy.schema?.name??"extract",description:vt(o.strategy.schema),schema:o.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:m},outputConfig:{format:{type:"json_schema",schema:o.strategy.schema}},responseSchema:o.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:o.strategy.schema},strict:t?.modelSettings?.strict})}let l=await Vt(e,s,{...n,...t?.modelSettings,tool_choice:a});return this.#e.includeAgentName==="inline"?to(l,this.#e.includeAgentName):l}getState(){let e=super.getState();return{messages:[],...e&&!H(e)?e:{}}}};var no=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(", ")}].`,D="tools",ro=e=>Array.isArray(e)&&e.every(Ke.isInstance),$o=e=>typeof e=="object"&&e!=null&&"messages"in e&&ro(e.messages),Bo=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function Uo(e,t){return fe.isInstance(e)?new M({content:e.message,tool_call_id:t.id,name:t.name}):new M({content:`${e}
27
+ Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var so=class extends we{options;tools;trace=!1;signal;handleToolErrors=Uo;wrapToolCall;constructor(e,t){let{name:o,tags:n,handleToolErrors:r,signal:s,wrapToolCall:a}=t??{};super({name:o,tags:n,func:(l,u)=>this.run(l,u)}),this.options=t,this.tools=e,this.handleToolErrors=r??this.handleToolErrors,this.signal=s,this.wrapToolCall=a}#e(e,t,o){if(Rt(e)||this.signal?.aborted)throw e;let n=e,r=o;if(o){let s=e;for(;ne.isInstance(s);)s=s.cause;fe.isInstance(s)&&(n=s,r=!1)}if(r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw n;if(typeof this.handleToolErrors=="function"){let s=this.handleToolErrors(n,t);if(s&&M.isInstance(s))return s;throw n}else if(this.handleToolErrors)return new M({name:t.name,content:`${n}
28
+ Please fix your mistakes.`,tool_call_id:t.id});throw n}async runTool(e,t,o){let n=t,r={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===e.name),a=async u=>{let{toolCall:m,tool:c}=u,h=c??this.tools.find(f=>f.name===m.name);if(h===void 0){let f=this.tools.map(g=>g.name);return new M({content:no(m.name,f),tool_call_id:m.id,name:m.name,status:"error"})}let d=h;try{let f=await d.invoke({...m,type:"tool_call"},{...t,config:t,toolCallId:m.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Ue(this.signal,t.signal)});return M.isInstance(f)||H(f)?f:new M({name:d.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:m.id})}catch(f){throw f instanceof pt?new fe(f,m):f}},l={toolCall:e,tool:s,state:o,runtime:r};if(this.wrapToolCall)try{return await this.wrapToolCall(l,a)}catch(u){return this.#e(u,e,!0)}if(!s){let u=this.tools.map(m=>m.name);return new M({content:no(e.name,u),tool_call_id:e.id,name:e.name,status:"error"})}try{return await a(l)}catch(u){return this.#e(u,e,!1)}}async run(e,t){let o;if(Bo(e)){let{lg_tool_call:s,jumpTo:a,...l}=e;o=[await this.runTool(e.lg_tool_call,t,l)]}else{let s;if(ro(e))s=e;else if($o(e))s=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),l;for(let u=s.length-1;u>=0;u-=1){let m=s[u];if(T.isInstance(m)){l=m;break}}if(!T.isInstance(l))throw new Error("ToolNode only accepts AIMessages as input.");o=await Promise.all(l.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,t,e))??[])}if(!o.some(H))return Array.isArray(e)?o:{messages:o};let n=[],r=null;for(let s of o)H(s)?s.graph===L.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>zo(a))?r?r.goto.push(...s.goto):r=new L({graph:L.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(e)?[s]:{messages:[s]});return r&&n.push(r),n}};function zo(e){return e instanceof U}function Se(e,t){let n=0;if(t&&t.length>0){let r=0;for(let s of t){let a=ot(s)?xt(s):s;r+=JSON.stringify(a).length}n+=r}for(let r of e){let s;typeof r.content=="string"?s=r.content:Array.isArray(r.content)?s=r.content.map(a=>typeof a=="string"?a:a.type==="text"&&"text"in a?a.text:"").join(""):s="",T.isInstance(r)&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0&&(s+=JSON.stringify(r.tool_calls)),M.isInstance(r)&&(s+=r.tool_call_id??""),n+=s.length}return Math.ceil(n/4)}function X(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function re(e){return typeof e=="function"?e:e.hook}var Fo=class{},Wo=class{},se=class extends we{constructor(e){super(e)}async invokeMiddleware(e,t){let o={};if(this.middleware.contextSchema&&F(this.middleware.contextSchema)){let u=de(this.middleware.contextSchema);if(u){let m={},c=t?.context||{};for(let h of Object.keys(u))h in c&&(m[h]=c[h]);o=te(this.middleware.contextSchema,m)}}let n={...e,messages:e.messages},r={context:o,store:t?.store,configurable:t?.configurable,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new Wo,{...r,context:Object.freeze(Object.assign(new Fo,o))})));if(!s)return{jumpTo:void 0};let a,l;if(this.name?.startsWith("BeforeAgentNode_")?(a=X(this.middleware.beforeAgent),l="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=X(this.middleware.beforeModel),l="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=X(this.middleware.afterAgent),l="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=X(this.middleware.afterModel),l="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:l?`no ${l} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:Xt(this.middleware.stateSchema)}}};var ao=class extends se{middleware;lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(e){super({name:`BeforeAgentNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.beforeAgent)(e,t)}};var io=class extends se{middleware;lc_namespace=["langchain","agents","beforeModelNodes"];constructor(e){super({name:`BeforeModelNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.beforeModel)(e,t)}};var lo=class extends se{middleware;lc_namespace=["langchain","agents","afterModelNodes"];constructor(e){super({name:`AfterModelNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.afterModel)(e,t)}};var co=class extends se{middleware;lc_namespace=["langchain","agents","afterAgentNodes"];constructor(e){super({name:`AfterAgentNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return re(this.middleware.afterAgent)(e,t)}};var uo=class mo{options;#e;#o="v2";#r;#t;constructor(t,o){if(this.options=t,this.#t=$(o??{},{metadata:{ls_integration:"langchain_create_agent"},configurable:{ls_agent_type:"root"}}),t.name&&(this.#t=$(this.#t,{metadata:{lc_agent_name:t.name}})),this.#o=t.version??this.#o,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Be(t.model);let n=this.options.middleware?.filter(p=>p.tools).flatMap(p=>p.tools)??[],r=[...t.tools??[],...n],s=new Set(r.filter(ie).filter(p=>"returnDirect"in p&&p.returnDirect).map(p=>p.name)),a=!!this.options.middleware?.some(p=>p.wrapModelCall),{state:l,input:u,output:m}=Ft(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new Nt(l,{input:u,output:m,context:this.options.contextSchema}),h=[],d=[],f=[],g=[],x=[];this.#r=new oo({model:this.options.model,systemMessage:Jt(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:r,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:x});let y=new Set,w=this.options.middleware??[];for(let p=0;p<w.length;p++){let C,I,k,_,v=w[p];if(y.has(v.name))throw new Error(`Middleware ${v.name} is defined multiple times`);if(y.add(v.name),v.beforeAgent){C=new ao(v);let S=`${v.name}.before_agent`;h.push({index:p,name:S,allowed:X(v.beforeAgent)}),c.addNode(S,C,C.nodeOptions)}if(v.beforeModel){I=new io(v);let S=`${v.name}.before_model`;d.push({index:p,name:S,allowed:X(v.beforeModel)}),c.addNode(S,I,I.nodeOptions)}if(v.afterModel){k=new lo(v);let S=`${v.name}.after_model`;f.push({index:p,name:S,allowed:X(v.afterModel)}),c.addNode(S,k,k.nodeOptions)}if(v.afterAgent){_=new co(v);let S=`${v.name}.after_agent`;g.push({index:p,name:S,allowed:X(v.afterAgent)}),c.addNode(S,_,_.nodeOptions)}v.wrapModelCall&&x.push(v)}c.addNode(P,this.#r);let O=w.some(p=>p.wrapToolCall),A=r.filter(ie);if(A.length>0||O){let p=new so(A,{signal:this.options.signal,wrapToolCall:Kt(w)});c.addNode(D,p)}let N;h.length>0?N=h[0].name:d.length>0?N=d[0].name:N=P;let K=d.length>0?d[0].name:P,j=g.length>0?g[g.length-1].name:R;c.addEdge(It,N);let b=A.length>0||O;for(let p=0;p<h.length;p++){let C=h[p],I=C.name,k=p===h.length-1?K:h[p+1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._.map(S=>S===R?j:S)]));c.addConditionalEdges(I,this.#c(A,k,j,b),v)}else c.addEdge(I,k)}for(let p=0;p<d.length;p++){let C=d[p],I=C.name,k=p===d.length-1?P:d[p+1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));c.addConditionalEdges(I,this.#d(A,k,b),v)}else c.addEdge(I,k)}let J=f.at(-1);if(f.length>0&&J)c.addEdge(P,J.name);else{let p=this.#s(A,!1,b).map(C=>C===R?j:C);p.length===1?c.addEdge(P,p[0]):c.addConditionalEdges(P,this.#i(j),p)}for(let p=f.length-1;p>0;p--){let C=f[p],I=C.name,k=f[p-1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));c.addConditionalEdges(I,this.#n(A,C.allowed,k,b),v)}else c.addEdge(I,k)}if(f.length>0){let p=f[0],C=p.name,I=this.#s(A,!0,b).filter(v=>v!=="tools"||b),k=!!(p.allowed&&p.allowed.length>0),_=I.map(v=>v===R?j:v);c.addConditionalEdges(C,this.#l(A,k,j,b),_)}for(let p=g.length-1;p>0;p--){let C=g[p],I=C.name,k=g[p-1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));c.addConditionalEdges(I,this.#n(A,C.allowed,k,b),v)}else c.addEdge(I,k)}if(g.length>0){let p=g[0],C=p.name;if(p.allowed&&p.allowed.length>0){let I=p.allowed.map(_=>V(_)).filter(_=>_!=="tools"||b),k=Array.from(new Set([R,...I]));c.addConditionalEdges(C,this.#n(A,p.allowed,R,b),k)}else c.addEdge(C,R)}if(b){let p=K;s.size>0?c.addConditionalEdges(D,this.#a(s,j,p),[p,j]):c.addEdge(D,p)}let le=(this.options.middleware??[]).flatMap(p=>p.streamTransformers??[]),Ee=[ae([]),he([]),...le,...this.options.streamTransformers??[]];this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description,transformers:Ee});let ye=Yt(this.#t);Object.keys(ye).length>0&&(this.#e=this.#e.withConfig(ye))}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(t){this.#e.checkpointer=t}get store(){return this.#e.store}set store(t){this.#e.store=t}withConfig(t){return new mo(this.options,$(this.#t,t))}#s(t,o=!1,n=t.length>0){let r=[];return n&&r.push(D),o&&r.push(P),r.push(R),r}#a(t,o,n){return r=>{let s=r.messages,a=s[s.length-1];return M.isInstance(a)&&a.name&&t.has(a.name)?this.options.responseFormat?n:o:n}}#i(t=R){return o=>{let n=o.messages.at(-1);if(!T.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return t;if(this.#o==="v1")return D;let r=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return r.length===0?t:r.map(s=>new U(D,{...o,lg_tool_call:s}))}}#l(t,o,n,r=t.length>0){let s=!!this.options.responseFormat;return a=>{let l=a,u=l.messages,m=u.at(-1);if(T.isInstance(m)&&(!m.tool_calls||m.tool_calls.length===0))return n;if(o&&l.jumpTo){let w=V(l.jumpTo);return w===R?n:w==="tools"?r?new U(D,{...a,jumpTo:void 0}):n:new U(P,{...a,jumpTo:void 0})}let c=u.filter(M.isInstance),h=u.filter(T.isInstance).at(-1),d=h?.tool_calls?.filter(w=>!c.some(O=>O.tool_call_id===w.id));if(d&&d.length>0)return this.#o==="v1"?D:d.map(w=>new U(D,{...a,lg_tool_call:w}));let f=h?.tool_calls?.some(w=>w.name.startsWith("extract-"));if(d&&d.length===0&&!f&&s)return P;if(!T.isInstance(m)||!m.tool_calls||m.tool_calls.length===0)return n;let g=m.tool_calls.every(w=>w.name.startsWith("extract-")),x=m.tool_calls.some(w=>!w.name.startsWith("extract-"));if(g||!x)return n;if(this.#o==="v1")return D;let y=m.tool_calls.filter(w=>!w.name.startsWith("extract-"));return y.length===0?n:y.map(w=>new U(D,{...a,lg_tool_call:w}))}}#n(t,o,n,r=t.length>0){let s=new Set(o.map(a=>V(a)));return a=>{let l=a;if(l.jumpTo){let u=V(l.jumpTo);if(u===R&&s.has(R))return R;if(u==="tools"&&s.has("tools"))return r?new U(D,{...a,jumpTo:void 0}):R;if(u==="model_request"&&s.has("model_request"))return new U(P,{...a,jumpTo:void 0})}return n}}#c(t,o,n,r=t.length>0){return s=>{let a=s;if(!a.jumpTo)return o;let l=V(a.jumpTo);return l===R?n:l==="tools"?r?new U(D,{...s,jumpTo:void 0}):n:new U(P,{...s,jumpTo:void 0})}}#d(t,o,n=t.length>0){return r=>{let s=r;if(!s.jumpTo)return o;let a=V(s.jumpTo);return a===R?R:a==="tools"?n?new U(D,{...r,jumpTo:void 0}):R:new U(P,{...r,jumpTo:void 0})}}async#u(t,o){if(!this.options.middleware||this.options.middleware.length===0||t instanceof L||!t)return t;let n=await Zt(this.options.middleware,t),r={...(await this.#e.getState(o).catch(()=>({values:{}}))).values,...t};if(!r)return r;for(let[s,a]of Object.entries(n))s in r||(r[s]=a);return r}async invoke(t,o){let n=$(this.#t,o),r=await this.#u(t,n);return this.#e.invoke(r,n)}async stream(t,o){let n=$(this.#t,o),r=await this.#u(t,n);return this.#e.stream(r,n)}streamEvents(t,o,n){if(o?.version!=="v3"||n!=null){let r=$(this.#t,o),s=o?.version==="v1"||o?.version==="v2"?o.version:"v2";return this.#e.streamEvents(t,{...r,version:s},n)}return(async()=>{let{transformers:r,version:s,...a}=o??{},l=$(this.#t,a),u=await this.#u(t,l);return await this.#e.streamEvents(u,{...l,version:"v3",transformers:r})})()}async drawMermaidPng(t){let o=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(o)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,o){return this.#e.getState(t,o)}getStateHistory(t,o){return this.#e.getStateHistory(t,o)}getSubgraphs(t,o){return this.#e.getSubgraphs(t,o)}getSubgraphsAsync(t,o){return this.#e.getSubgraphsAsync(t,o)}updateState(t,o,n){return this.#e.updateState(t,o,n)}get builder(){return this.#e.builder}};function Vo(e){return new uo(e)}var Yo=i.function().args(i.custom()).returns(i.union([i.boolean(),i.promise(i.boolean())])),Zo=i.function().args(i.custom(),i.custom(),i.custom()).returns(i.union([i.string(),i.promise(i.string())])),Xo=["approve","edit","reject"],Qo=i.enum(Xo),qo=i.object({allowedDecisions:i.array(Qo),description:i.union([i.string(),Zo]).optional(),argsSchema:i.record(i.any()).optional(),when:Yo.optional()}),qa=i.object({interruptOn:i.record(i.union([i.boolean(),qo])).optional(),descriptionPrefix:i.string().default("Tool execution requires approval")});var We="nostream",He=i.object({maxRetries:i.number().min(0).default(2),retryOn:i.union([i.function().args(i.instanceof(Error)).returns(i.boolean()),i.array(i.custom())]).default(()=>e=>ft(e)??!0),backoffFactor:i.number().min(0).default(2),initialDelayMs:i.number().min(0).default(1e3),maxDelayMs:i.number().min(0).default(6e4),jitter:i.boolean().default(!0)});var Ge=`<role>
29
29
  Context Extraction Assistant
30
30
  </role>
31
31
 
@@ -51,6 +51,6 @@ Respond ONLY with the extracted context. Do not include any additional informati
51
51
  <messages>
52
52
  Messages to summarize:
53
53
  {messages}
54
- </messages>`,en="Here is a summary of the conversation to date:",Je=20,tn=4e3,fo=5,on=i.function().args(i.array(i.custom())).returns(i.union([i.number(),i.promise(i.number())])),ke=i.object({fraction:i.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:i.number().positive("Tokens must be greater than 0").optional(),messages:i.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),mt=i.object({fraction:i.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:i.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:i.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),po=i.object({model:i.custom(),trigger:i.union([ke,i.array(ke)]).optional(),keep:mt.optional(),tokenCounter:on.optional(),summaryPrompt:i.string().default(Ge),trimTokensToSummarize:i.number().optional(),summaryPrefix:i.string().optional(),maxTokensBeforeSummary:i.number().optional(),messagesToKeep:i.number().optional()});function Ve(e){if("profile"in e&&typeof e.profile=="object"&&e.profile&&"maxInputTokens"in e.profile&&(typeof e.profile.maxInputTokens=="number"||e.profile.maxInputTokens==null))return e.profile.maxInputTokens??void 0;if("model"in e&&typeof e.model=="string")return nt(e.model);if("modelName"in e&&typeof e.modelName=="string")return nt(e.modelName)}function go(e){let{data:t,error:o}=Ct(po,e);if(o)throw new Error(`Invalid summarization middleware options: ${U.prettifyError(o)}`);return E({name:"SummarizationMiddleware",contextSchema:po.extend({model:i.custom().optional()}),beforeModel:async(n,r)=>{let s=t.trigger,a=t.keep;t.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),s===void 0&&(s={tokens:t.maxTokensBeforeSummary})),t.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!a||a&&"messages"in a&&a.messages===Je)&&(a={messages:t.messagesToKeep}));let l=r.context?.trigger!==void 0?r.context.trigger:s,u=r.context?.keep!==void 0?r.context.keep:a??{messages:Je},m=mt.parse(u),c=[];l===void 0?c=[]:Array.isArray(l)?c=l.map(J=>ke.parse(J)):c=[ke.parse(l)];let h=c.some(J=>"fraction"in J)||"fraction"in m,d=typeof t.model=="string"?await ee(t.model):t.model;if(h&&!Ve(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");let f=r.context?.summaryPrompt===Ge?t.summaryPrompt??Ge:r.context?.summaryPrompt??t.summaryPrompt??Ge,g=r.context.summaryPrefix??t.summaryPrefix??en,x=r.context?.trimTokensToSummarize!==void 0?r.context.trimTokensToSummarize:t.trimTokensToSummarize??tn;nn(n.messages);let y=r.context?.tokenCounter!==void 0?r.context.tokenCounter:t.tokenCounter??Se,w=await y(n.messages);if(!await an(n.messages,w,c,d))return;let{systemPrompt:O,conversationMessages:A}=rn(n.messages),N=await ln(A,m,y,d);if(N<=0)return;let{messagesToSummarize:K,preservedMessages:j}=sn(O,A,N),b=new Q({content:`${g}
54
+ </messages>`,en="Here is a summary of the conversation to date:",Je=20,tn=4e3,fo=5,on=i.function().args(i.array(i.custom())).returns(i.union([i.number(),i.promise(i.number())])),ke=i.object({fraction:i.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:i.number().positive("Tokens must be greater than 0").optional(),messages:i.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),mt=i.object({fraction:i.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:i.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:i.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),po=i.object({model:i.custom(),trigger:i.union([ke,i.array(ke)]).optional(),keep:mt.optional(),tokenCounter:on.optional(),summaryPrompt:i.string().default(Ge),trimTokensToSummarize:i.number().optional(),summaryPrefix:i.string().optional(),maxTokensBeforeSummary:i.number().optional(),messagesToKeep:i.number().optional()});function Ve(e){if("profile"in e&&typeof e.profile=="object"&&e.profile&&"maxInputTokens"in e.profile&&(typeof e.profile.maxInputTokens=="number"||e.profile.maxInputTokens==null))return e.profile.maxInputTokens??void 0;if("model"in e&&typeof e.model=="string")return nt(e.model);if("modelName"in e&&typeof e.modelName=="string")return nt(e.modelName)}function go(e){let{data:t,error:o}=bt(po,e);if(o)throw new Error(`Invalid summarization middleware options: ${B.prettifyError(o)}`);return E({name:"SummarizationMiddleware",contextSchema:po.extend({model:i.custom().optional()}),beforeModel:async(n,r)=>{let s=t.trigger,a=t.keep;t.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),s===void 0&&(s={tokens:t.maxTokensBeforeSummary})),t.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!a||a&&"messages"in a&&a.messages===Je)&&(a={messages:t.messagesToKeep}));let l=r.context?.trigger!==void 0?r.context.trigger:s,u=r.context?.keep!==void 0?r.context.keep:a??{messages:Je},m=mt.parse(u),c=[];l===void 0?c=[]:Array.isArray(l)?c=l.map(J=>ke.parse(J)):c=[ke.parse(l)];let h=c.some(J=>"fraction"in J)||"fraction"in m,d=typeof t.model=="string"?await ee(t.model):t.model;if(h&&!Ve(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");let f=r.context?.summaryPrompt===Ge?t.summaryPrompt??Ge:r.context?.summaryPrompt??t.summaryPrompt??Ge,g=r.context.summaryPrefix??t.summaryPrefix??en,x=r.context?.trimTokensToSummarize!==void 0?r.context.trimTokensToSummarize:t.trimTokensToSummarize??tn;nn(n.messages);let y=r.context?.tokenCounter!==void 0?r.context.tokenCounter:t.tokenCounter??Se,w=await y(n.messages);if(!await an(n.messages,w,c,d))return;let{systemPrompt:O,conversationMessages:A}=rn(n.messages),N=await ln(A,m,y,d);if(N<=0)return;let{messagesToSummarize:K,preservedMessages:j}=sn(O,A,N),b=new Q({content:`${g}
55
55
 
56
- ${await un(K,d,f,y,x,r)}`,id:A[0].id,additional_kwargs:{lc_source:"summarization"}});return{messages:[new Qe({id:Ot}),b,...j]}}})}function nn(e){for(let t of e)t.id||(t.id=ht())}function rn(e){return e.length>0&&z.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function sn(e,t,o){let n=t.slice(0,o),r=t.slice(o);return e&&n.unshift(e),{messagesToSummarize:n,preservedMessages:r}}async function an(e,t,o,n){if(o.length===0)return!1;for(let r of o){let s=!0,a=!1;if(r.messages!==void 0&&(a=!0,e.length<r.messages&&(s=!1)),r.tokens!==void 0&&(a=!0,t<r.tokens&&(s=!1)),r.fraction!==void 0){a=!0;let l=Ve(n);typeof l=="number"?t<Math.floor(l*r.fraction)&&(s=!1):s=!1}if(a&&s)return!0}return!1}async function ln(e,t,o,n){if("tokens"in t||"fraction"in t){let r=await cn(e,t,o,n);return typeof r=="number"?r:ho(e,Je)}return ho(e,t.messages??Je)}async function cn(e,t,o,n){if(e.length===0)return 0;let r;if("fraction"in t&&t.fraction!==void 0){let c=Ve(n);if(typeof c!="number")return;r=Math.floor(c*t.fraction)}else if("tokens"in t&&t.tokens!==void 0)r=Math.floor(t.tokens);else return;if(r<=0&&(r=1),await o(e)<=r)return 0;let s=0,a=e.length,l=e.length,u=Math.floor(Math.log2(e.length))+1;for(let c=0;c<u&&!(s>=a);c++){let h=Math.floor((s+a)/2);await o(e.slice(h))<=r?(l=h,a=h):s=h+1}if(l===e.length&&(l=s),l>=e.length){if(e.length===1)return 0;l=e.length-1}let m=Mo(e,l);if(m<=l)return m;for(let c=l;c>=0;c--)if(wo(e,c))return c;return 0}function ho(e,t){if(e.length<=t)return 0;let o=e.length-t,n=Mo(e,o);if(n<=o)return n;for(let r=o;r>=0;r--)if(wo(e,r))return r;return 0}function wo(e,t){if(t>=e.length)return!0;if(t<e.length&&T.isInstance(e[t])&&ge(e[t]))return!1;let o=Math.max(0,t-fo),n=Math.min(e.length,t+fo);for(let r=o;r<n;r++){if(!ge(e[r]))continue;let s=yo(e[r]);if(dn(e,r,t,s))return!1}return!0}function yo(e){let t=new Set;if(e.tool_calls)for(let o of e.tool_calls){let n=typeof o=="object"&&"id"in o?o.id:null;n&&t.add(n)}return t}function Mo(e,t){if(t>=e.length||!M.isInstance(e[t]))return t;let o=new Set,n=t;for(;n<e.length&&M.isInstance(e[n]);){let r=e[n];r.tool_call_id&&o.add(r.tool_call_id),n++}for(let r=t-1;r>=0;r--){let s=e[r];if(T.isInstance(s)&&ge(s)){let a=yo(s);for(let l of o)if(a.has(l))return r}}return n}function dn(e,t,o,n){for(let r=t+1;r<e.length;r++){let s=e[r];if(M.isInstance(s)&&n.has(s.tool_call_id)&&t<o!=r<o)return!0}return!1}async function un(e,t,o,n,r,s){if(!e.length)return"No previous conversation history.";let a=await mn(e,n,r);if(!a.length)return"Previous conversation was too long to summarize.";let l=yt(a);try{let u=o.replace("{messages}",l),m=B(Ae(s)??{},{metadata:{lc_source:"summarization"},tags:[We]}),c=(await t.invoke(u,m)).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(h=>typeof h=="string"?h:typeof h=="object"&&h!==null&&"text"in h?h.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(u){return`Error generating summary: ${u}`}}async function mn(e,t,o){if(o===void 0)return e;try{return await ot(e,{maxTokens:o,tokenCounter:async n=>t(n),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-15)}}var Ei=i.object({model:i.string().or(i.instanceof(kt)).optional(),systemPrompt:i.string().optional(),maxTools:i.number().optional(),alwaysInclude:i.array(i.string()).optional()});var ji=i.object({applyToInput:i.boolean().optional(),applyToOutput:i.boolean().optional(),applyToToolResults:i.boolean().optional()});var Ui=i.object({rules:i.record(i.string(),i.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var fn=["continue","error","end"],pn="continue";var hn=i.enum(fn).default(pn);i.object({toolName:i.string().optional(),threadLimit:i.number().optional(),runLimit:i.number().optional(),exitBehavior:hn});var Zi=i.object({threadToolCallCount:i.record(i.string(),i.number()).default({}),runToolCallCount:i.record(i.string(),i.number()).default({})});var gn=i.enum(["pending","in_progress","completed"]).describe("Status of the todo"),wn=i.object({content:i.string().describe("Content of the todo item"),status:gn}),rl=i.object({todos:i.array(wn).default([])});var yn="end",Mn=i.object({threadLimit:i.number().optional(),runLimit:i.number().optional(),exitBehavior:i.enum(["error","end"]).optional()}),Tn=i.object({threadModelCallCount:i.number().default(0),runModelCallCount:i.number().default(0)}),To=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:o,runCount:n}){let r=[];typeof e=="number"&&typeof o=="number"&&r.push(`thread level call limit reached with ${o} model calls`),typeof t=="number"&&typeof n=="number"&&r.push(`run level call limit reached with ${n} model calls`),super(`Model call limits exceeded${r.length>0?`: ${r.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function bo(e){return E({name:"ModelCallLimitMiddleware",contextSchema:Mn,stateSchema:Tn,beforeModel:{canJumpTo:["end"],hook:(t,o)=>{let n=o.context.exitBehavior??e?.exitBehavior??yn;n==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),n="error");let r=o.context.threadLimit??e?.threadLimit,s=o.context.runLimit??e?.runLimit,a=t.threadModelCallCount,l=t.runModelCallCount;if(typeof r=="number"&&r<=a){let u=new To({threadLimit:r,threadCount:a});if(n==="end")return{jumpTo:"end",messages:[new T(u.message)]};throw u}if(typeof s=="number"&&s<=l){let u=new To({runLimit:s,runCount:l});if(n==="end")return{jumpTo:"end",messages:[new T(u.message)]};throw u}return t}},afterModel:t=>({runModelCallCount:t.runModelCallCount+1,threadModelCallCount:t.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}var bl=i.object({onFailure:i.union([i.literal("error"),i.literal("continue"),i.function().args(i.instanceof(Error)).returns(i.string())]).default("continue")}).merge(He);var Al=i.object({tools:i.array(i.union([i.custom(),i.custom(),i.string()])).optional(),onFailure:i.union([i.literal("error"),i.literal("continue"),i.literal("raise"),i.literal("return_message"),i.function().args(i.instanceof(Error)).returns(i.string())]).default("continue")}).merge(He);var Zl=i.object({enableCaching:i.boolean().optional(),ttl:i.enum(["5m","1h"]).optional(),minMessagesToCache:i.number().optional(),unsupportedModelBehavior:i.enum(["ignore","warn","raise"]).optional()});var ec=i.object({enableCaching:i.boolean().optional(),ttl:i.enum(["5m","1h"]).optional(),minMessagesToCache:i.number().optional(),unsupportedModelBehavior:i.enum(["ignore","warn","raise"]).optional()});export{E as a,Vo as b,go as c,bo as d};
56
+ ${await un(K,d,f,y,x,r)}`,id:A[0].id,additional_kwargs:{lc_source:"summarization"}});return{messages:[new Ye({id:Ot}),b,...j]}}})}function nn(e){for(let t of e)t.id||(t.id=gt())}function rn(e){return e.length>0&&z.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function sn(e,t,o){let n=t.slice(0,o),r=t.slice(o);return e&&n.unshift(e),{messagesToSummarize:n,preservedMessages:r}}async function an(e,t,o,n){if(o.length===0)return!1;for(let r of o){let s=!0,a=!1;if(r.messages!==void 0&&(a=!0,e.length<r.messages&&(s=!1)),r.tokens!==void 0&&(a=!0,t<r.tokens&&(s=!1)),r.fraction!==void 0){a=!0;let l=Ve(n);typeof l=="number"?t<Math.floor(l*r.fraction)&&(s=!1):s=!1}if(a&&s)return!0}return!1}async function ln(e,t,o,n){if("tokens"in t||"fraction"in t){let r=await cn(e,t,o,n);return typeof r=="number"?r:ho(e,Je)}return ho(e,t.messages??Je)}async function cn(e,t,o,n){if(e.length===0)return 0;let r;if("fraction"in t&&t.fraction!==void 0){let c=Ve(n);if(typeof c!="number")return;r=Math.floor(c*t.fraction)}else if("tokens"in t&&t.tokens!==void 0)r=Math.floor(t.tokens);else return;if(r<=0&&(r=1),await o(e)<=r)return 0;let s=0,a=e.length,l=e.length,u=Math.floor(Math.log2(e.length))+1;for(let c=0;c<u&&!(s>=a);c++){let h=Math.floor((s+a)/2);await o(e.slice(h))<=r?(l=h,a=h):s=h+1}if(l===e.length&&(l=s),l>=e.length){if(e.length===1)return 0;l=e.length-1}let m=Mo(e,l);if(m<=l)return m;for(let c=l;c>=0;c--)if(wo(e,c))return c;return 0}function ho(e,t){if(e.length<=t)return 0;let o=e.length-t,n=Mo(e,o);if(n<=o)return n;for(let r=o;r>=0;r--)if(wo(e,r))return r;return 0}function wo(e,t){if(t>=e.length)return!0;if(t<e.length&&T.isInstance(e[t])&&ge(e[t]))return!1;let o=Math.max(0,t-fo),n=Math.min(e.length,t+fo);for(let r=o;r<n;r++){if(!ge(e[r]))continue;let s=yo(e[r]);if(dn(e,r,t,s))return!1}return!0}function yo(e){let t=new Set;if(e.tool_calls)for(let o of e.tool_calls){let n=typeof o=="object"&&"id"in o?o.id:null;n&&t.add(n)}return t}function Mo(e,t){if(t>=e.length||!M.isInstance(e[t]))return t;let o=new Set,n=t;for(;n<e.length&&M.isInstance(e[n]);){let r=e[n];r.tool_call_id&&o.add(r.tool_call_id),n++}for(let r=t-1;r>=0;r--){let s=e[r];if(T.isInstance(s)&&ge(s)){let a=yo(s);for(let l of o)if(a.has(l))return r}}return n}function dn(e,t,o,n){for(let r=t+1;r<e.length;r++){let s=e[r];if(M.isInstance(s)&&n.has(s.tool_call_id)&&t<o!=r<o)return!0}return!1}async function un(e,t,o,n,r,s){if(!e.length)return"No previous conversation history.";let a=await mn(e,n,r);if(!a.length)return"Previous conversation was too long to summarize.";let l=ht(a);try{let u=o.replace("{messages}",l),m=$(Ae(s)??{},{metadata:{lc_source:"summarization"},tags:[We]}),c=(await t.invoke(u,m)).content;return typeof c=="string"?c.trim():Array.isArray(c)?c.map(h=>typeof h=="string"?h:typeof h=="object"&&h!==null&&"text"in h?h.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(u){return`Error generating summary: ${u}`}}async function mn(e,t,o){if(o===void 0)return e;try{return await tt(e,{maxTokens:o,tokenCounter:async n=>t(n),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-15)}}var Ei=i.object({model:i.string().or(i.instanceof(Et)).optional(),systemPrompt:i.string().optional(),maxTools:i.number().optional(),alwaysInclude:i.array(i.string()).optional()});var ji=i.object({applyToInput:i.boolean().optional(),applyToOutput:i.boolean().optional(),applyToToolResults:i.boolean().optional()});var Ui=i.object({rules:i.record(i.string(),i.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var fn=["continue","error","end"],pn="continue";var hn=i.enum(fn).default(pn);i.object({toolName:i.string().optional(),threadLimit:i.number().optional(),runLimit:i.number().optional(),exitBehavior:hn});var Zi=i.object({threadToolCallCount:i.record(i.string(),i.number()).default({}),runToolCallCount:i.record(i.string(),i.number()).default({})});var gn=i.enum(["pending","in_progress","completed"]).describe("Status of the todo"),wn=i.object({content:i.string().describe("Content of the todo item"),status:gn}),rl=i.object({todos:i.array(wn).default([])});var yn="end",Mn=i.object({threadLimit:i.number().optional(),runLimit:i.number().optional(),exitBehavior:i.enum(["error","end"]).optional()}),Tn=i.object({threadModelCallCount:i.number().default(0),runModelCallCount:i.number().default(0)}),To=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:o,runCount:n}){let r=[];typeof e=="number"&&typeof o=="number"&&r.push(`thread level call limit reached with ${o} model calls`),typeof t=="number"&&typeof n=="number"&&r.push(`run level call limit reached with ${n} model calls`),super(`Model call limits exceeded${r.length>0?`: ${r.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function bo(e){return E({name:"ModelCallLimitMiddleware",contextSchema:Mn,stateSchema:Tn,beforeModel:{canJumpTo:["end"],hook:(t,o)=>{let n=o.context.exitBehavior??e?.exitBehavior??yn;n==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),n="error");let r=o.context.threadLimit??e?.threadLimit,s=o.context.runLimit??e?.runLimit,a=t.threadModelCallCount,l=t.runModelCallCount;if(typeof r=="number"&&r<=a){let u=new To({threadLimit:r,threadCount:a});if(n==="end")return{jumpTo:"end",messages:[new T(u.message)]};throw u}if(typeof s=="number"&&s<=l){let u=new To({runLimit:s,runCount:l});if(n==="end")return{jumpTo:"end",messages:[new T(u.message)]};throw u}return t}},afterModel:t=>({runModelCallCount:t.runModelCallCount+1,threadModelCallCount:t.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}var bl=i.object({onFailure:i.union([i.literal("error"),i.literal("continue"),i.function().args(i.instanceof(Error)).returns(i.string())]).default("continue")}).merge(He);var Al=i.object({tools:i.array(i.union([i.custom(),i.custom(),i.string()])).optional(),onFailure:i.union([i.literal("error"),i.literal("continue"),i.literal("raise"),i.literal("return_message"),i.function().args(i.instanceof(Error)).returns(i.string())]).default("continue")}).merge(He);var Zl=i.object({enableCaching:i.boolean().optional(),ttl:i.enum(["5m","1h"]).optional(),minMessagesToCache:i.number().optional(),unsupportedModelBehavior:i.enum(["ignore","warn","raise"]).optional()});var ec=i.object({enableCaching:i.boolean().optional(),ttl:i.enum(["5m","1h"]).optional(),minMessagesToCache:i.number().optional(),unsupportedModelBehavior:i.enum(["ignore","warn","raise"]).optional()});export{E as a,Vo as b,go as c,bo as d};
@@ -178,4 +178,4 @@ Details: ${p.message}`),of(p)&&(h=`${h}
178
178
  ${$a.prettifyError(p)}`),new $r(h,JSON.stringify(e))}else{let p=re(n,this.schema);if(!p.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
179
179
  Details: ${p.errors.map(m=>`${m.keywordLocation}: ${m.error}`).join(`
180
180
  `)}`),new $r(h,JSON.stringify(e))}i=n}let a=bn(t),s=nt.configure(a.callbacks,this.callbacks,a.tags||r,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),o;$t(e)&&(o=e.id),!o&&Il(a)&&(o=a.toolCall.id);let c=await s?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,o);delete a.runId;let l;try{let p=await this._call(i,c,a);l=Wo(p)?await kf(p,async h=>{try{await c?.handleToolEvent(h)}catch(m){await c?.handleToolError(m)}}):p}catch(p){throw await c?.handleToolError(p),p}let u,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
181
- Result: ${JSON.stringify(l)}`);else u=l;let f=Hw({content:u,artifact:d,toolCallId:o,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},xp=class extends hc{schema=vt.object({input:vt.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},Ep=class extends xp{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 r=bn(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,t,r){return this.func(e,t,r)}},Sp=class extends hc{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,r){let n=bn(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},zw=class{getTools(){return this.tools}};function Bw(e,t){let r=Bi(t.schema),n=rn(t.schema);if(!t.schema||r||n)return new Ep({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(s,o,c)=>new Promise((l,u)=>{let d=ue(c,{callbacks:o?.getChild()});be.runWithConfig(We(d),async()=>{try{l(e(s,d))}catch(f){u(f)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new Sp({...t,description:a,schema:i,func:async(s,o,c)=>new Promise((l,u)=>{let d,f=()=>{c?.signal&&d&&c.signal.removeEventListener("abort",d)};c?.signal&&(d=()=>{f(),u(Ht(c.signal))},c.signal.addEventListener("abort",d,{once:!0}));let p=ue(c,{callbacks:o?.getChild()});be.runWithConfig(We(p),async()=>{try{let h=await e(s,p);if(Wo(h)){l(h);return}if(c?.signal?.aborted){f();return}f(),l(h)}catch(h){f(),u(h)}})})})}function Fw(e){return typeof e=="object"&&e!==null&&"type"in e}function Hw(e){let{content:t,artifact:r,toolCallId:n,metadata:i}=e;return n&&!La(t)?typeof t=="string"||Array.isArray(t)&&t.every(Fw)?new er({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:i}):new er({status:"success",content:Gw(t),artifact:r,tool_call_id:n,name:e.name,metadata:i}):t}function Gw(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}export{L as a,fx as b,Ka as c,Th as d,Ah as e,jr as f,Zw as g,Cc as h,Pp as i,Oc as j,Xw as k,Zn as l,ft as m,mx as n,nu as o,et as p,ea as q,zC as r,h0 as s,Ba as t,At as u,Fa as v,ah as w,sh as x,Nt as y,Pc as z,Mc as A,eb as B,jc as C,tb as D,rb as E,Pa as F,nb as G,Zc as H,Pe as I,Xc as J,Ie as K,Eb as L,qp as M,ce as N,Nr as O,Qc as P,ze as Q,tl as R,rl as S,Sb as T,Cb as U,La as V,er as W,Yp as X,Da as Y,Xp as Z,Qp as _,$r as $,b0 as aa,Ga as ba,vl as ca,Jn as da,Pr as ea,hv as fa,mv as ga,Mr as ha,Va as ia,Cl as ja,E0 as ka,S0 as la,Ol as ma,Rl as na,k0 as oa,C0 as pa,tr as qa,Nl as ra,P0 as sa,M0 as ta,$l as ua,Xn as va,Pl as wa,H0 as xa,G0 as ya,iv as za,Ml as Aa,Qn as Ba,qa as Ca,av as Da,sv as Ea,ov as Fa,jl as Ga,ZC as Ha,vx as Ia,Ch as Ja,Oh as Ka,nr as La,Lt as Ma,tT as Na,rt as Oa,sT as Pa,TT as Qa,$T as Ra,XT as Sa,bn as Ta,nt as Ua,Vr as Va,be as Wa,mA as Xa,qe as Ya,xn as Za,Y as _a,ue as $a,We as ab,it as bb,dO as cb,Re as db,ia as eb,Jt as fb,Cr as gb,sw as hb,NO as ib,LO as jb,cw as kb,$n as lb,lw as mb,nO as nb,Ir as ob,Yk as pb,uy as qb,oe as rb,he as sb,EA as tb,Zr as ub,zg as vb,Bg as wb,SA as xb,TA as yb,zi as zb,AA as Ab,IA as Bb,af as Cb,kA as Db,Bi as Eb,so as Fb,_t as Gb,oo as Hb,Fg as Ib,Hg as Jb,CA as Kb,rf as Lb,OA as Mb,RA as Nb,Ui as Ob,nf as Pb,NA as Qb,sf as Rb,$A as Sb,of as Tb,w as Ub,vt as Vb,Wt as Wb,Ki as Xb,RC as Yb,Zo as Zb,nR as _b,fa as $b,ge as ac,_e as bc,pa as cc,IR as dc,lp as ec,up as fc,ha as gc,pp as hc,kR as ic,gw as jc,Or as kc,_w as lc,yw as mc,sp as nc,BR as oc,sc as pc,oc as qc,bw as rc,tN as sc,uN as tc,bp as uc,jw as vc,Uw as wc,dc as xc,fc as yc,pc as zc,vp as Ac,MN as Bc,hc as Cc,Bw as Dc};
181
+ Result: ${JSON.stringify(l)}`);else u=l;let f=Hw({content:u,artifact:d,toolCallId:o,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},xp=class extends hc{schema=vt.object({input:vt.string().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,t)}},Ep=class extends xp{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 r=bn(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,t,r){return this.func(e,t,r)}},Sp=class extends hc{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,r){let n=bn(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n,r)}_call(e,t,r){return this.func(e,t,r)}},zw=class{getTools(){return this.tools}};function Bw(e,t){let r=Bi(t.schema),n=rn(t.schema);if(!t.schema||r||n)return new Ep({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(s,o,c)=>new Promise((l,u)=>{let d=ue(c,{callbacks:o?.getChild()});be.runWithConfig(We(d),async()=>{try{l(e(s,d))}catch(f){u(f)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new Sp({...t,description:a,schema:i,func:async(s,o,c)=>new Promise((l,u)=>{let d,f=()=>{c?.signal&&d&&c.signal.removeEventListener("abort",d)};c?.signal&&(d=()=>{f(),u(Ht(c.signal))},c.signal.addEventListener("abort",d,{once:!0}));let p=ue(c,{callbacks:o?.getChild()});be.runWithConfig(We(p),async()=>{try{let h=await e(s,p);if(Wo(h)){l(h);return}if(c?.signal?.aborted){f();return}f(),l(h)}catch(h){f(),u(h)}})})})}function Fw(e){return typeof e=="object"&&e!==null&&"type"in e}function Hw(e){let{content:t,artifact:r,toolCallId:n,metadata:i}=e;return n&&!La(t)?typeof t=="string"||Array.isArray(t)&&t.every(Fw)?new er({status:"success",content:t,artifact:r,tool_call_id:n,name:e.name,metadata:i}):new er({status:"success",content:Gw(t),artifact:r,tool_call_id:n,name:e.name,metadata:i}):t}function Gw(e){try{return JSON.stringify(e)??""}catch{return`${e}`}}export{L as a,h0 as b,Ba as c,At as d,Fa as e,ah as f,sh as g,Nt as h,Pc as i,Mc as j,eb as k,jc as l,tb as m,rb as n,Pa as o,nb as p,Zc as q,Zw as r,Cc as s,Pp as t,Oc as u,Xw as v,Zn as w,ft as x,Pe as y,Xc as z,Ie as A,Eb as B,qp as C,ce as D,Nr as E,Qc as F,ze as G,tl as H,rl as I,Sb as J,vl as K,Jn as L,Cb as M,La as N,er as O,Yp as P,Da as Q,Xp as R,Qp as S,$r as T,b0 as U,Ga as V,Va as W,Cl as X,E0 as Y,S0 as Z,Ol as _,Rl as $,k0 as aa,C0 as ba,tr as ca,Nl as da,P0 as ea,M0 as fa,$l as ga,Xn as ha,Pl as ia,H0 as ja,G0 as ka,iv as la,Ml as ma,Qn as na,qa as oa,av as pa,sv as qa,ov as ra,jl as sa,Pr as ta,hv as ua,mv as va,Mr as wa,fx as xa,Ka as ya,Th as za,Ah as Aa,jr as Ba,mx as Ca,nu as Da,et as Ea,vx as Fa,Ch as Ga,Oh as Ha,nr as Ia,Lt as Ja,tT as Ka,rt as La,sT as Ma,TT as Na,$T as Oa,XT as Pa,bn as Qa,nt as Ra,Vr as Sa,be as Ta,mA as Ua,qe as Va,xn as Wa,Y as Xa,ue as Ya,We as Za,it as _a,dO as $a,Re as ab,ia as bb,Jt as cb,Cr as db,sw as eb,NO as fb,LO as gb,cw as hb,$n as ib,lw as jb,nO as kb,Ir as lb,oe as mb,he as nb,EA as ob,Zr as pb,zg as qb,Bg as rb,SA as sb,TA as tb,zi as ub,AA as vb,IA as wb,af as xb,kA as yb,Bi as zb,so as Ab,_t as Bb,oo as Cb,Fg as Db,Hg as Eb,CA as Fb,rf as Gb,OA as Hb,RA as Ib,Ui as Jb,nf as Kb,NA as Lb,sf as Mb,$A as Nb,of as Ob,w as Pb,vt as Qb,Yk as Rb,uy as Sb,Wt as Tb,Ki as Ub,RC as Vb,Zo as Wb,nR as Xb,fa as Yb,ge as Zb,_e as _b,pa as $b,IR as ac,lp as bc,up as cc,ha as dc,pp as ec,kR as fc,gw as gc,Or as hc,_w as ic,yw as jc,sp as kc,dc as lc,fc as mc,pc as nc,vp as oc,ea as pc,zC as qc,ZC as rc,BR as sc,sc as tc,oc as uc,bw as vc,tN as wc,uN as xc,bp as yc,jw as zc,Uw as Ac,MN as Bc,hc as Cc,Bw as Dc};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import p from"./PWFUEBTT.js";import n from"./MXAZE2VM.js";import{a as o,c as m}from"./V6HOUZPZ.js";import l from"./OZ2CM3J2.js";import"./OOGADOKQ.js";import k from"./UAG6GDUG.js";import j from"./VMZZR7MY.js";import h from"./3SD47V7G.js";import g from"./6GODC6RU.js";import f from"./CCC6LBMY.js";import"./34O57OGV.js";import"./RZIXMISL.js";import"./FDOMMK2M.js";import e from"./TBYDZN4H.js";import"./4ALF2CJY.js";import"./725MBCQF.js";import d from"./BQYF37UD.js";import"./3XDT7MWI.js";import"./RN6WMVZX.js";import"./HB72YIII.js";import"./3UEKINYC.js";import"./RLEHNAIA.js";import c from"./KJLLN4P4.js";import"./HHBNLCJP.js";import"./7QIX4PZR.js";import"./RLB6TK6B.js";import b from"./JWZD3D5E.js";import a from"./UHICISBZ.js";import"./ONQ6JSBJ.js";import{v as i,z as r}from"./COH3QXWG.js";import"./R74ZHFA6.js";import"./3VCPN2KW.js";import"./S4LELUBK.js";import"./OL7QBAGS.js";import"./S627D4K7.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,,,,,,,,,,,,,,,,,,,,,,p])=>{var t=class extends i{constructor(){super(...arguments),this.agent=p}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-navigation-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=o(this,"arcgis-assistant-navigation-agent"),this.#i=m(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-navigation-agent",t);return t},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c,d,e,f,g,h,j,k,l,n,p)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./RZIXMISL.js";import"./FDOMMK2M.js";import"./S627D4K7.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as listLayerFieldsTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import b from"./UAG6GDUG.js";import a from"./CCC6LBMY.js";import"./ONQ6JSBJ.js";import"./S627D4K7.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,a])=>{return a},a,b)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as c}from"./ONQ6JSBJ.js";import{Dc as d}from"./AI6DYOKR.js";import{a}from"./VXFQANGJ.js";export default $arcgis.t(([i,u,w,{addressToLocations:S},v])=>{async function y(e,s){let r=w.getDefault().helperServices,n=r.geocode.find(g=>g.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let l=n.url,m=`${i.assetsPath?.endsWith("/")?i.assetsPath:`${i.assetsPath}/`}esri/images/search/search-symbol-32.png`,o=(await S(l,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!o?.extent||!o.location)throw new Error(`Could not find location for: ${e}`);let h=new v({url:m,width:24,height:24}),p=new u({geometry:o.location,symbol:h});s.graphics.removeAll(),s.graphics.add(p),await s.goTo(o.extent);let t={address:o.address??e,location:o.location.toJSON(),extent:o.extent.toJSON()},f={value:t,sharedStatePatch:{lastResolvedLocation:{value:t}},sharedResourceAdditions:[{kind:"point",description:t.address,payload:t.location}]};return[`Successfully zoomed to ${t.address}.`,f]}async function T({address:e},s){let{mapView:r}=c(s,["mapView"]);return await y(e,r)}var A=a.object({address:a.string().describe("The full address or place name to locate.")}),W=d(T,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:A,responseFormat:"content_and_artifact"});return W},"config","Graphic","portal/Portal","rest/locator","symbols/PictureMarkerSymbol")
2
+ import{a as c}from"./ONQ6JSBJ.js";import{Dc as d}from"./S627D4K7.js";import{a}from"./VXFQANGJ.js";export default $arcgis.t(([i,u,w,{addressToLocations:S},v])=>{async function y(e,s){let r=w.getDefault().helperServices,n=r.geocode.find(g=>g.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let l=n.url,m=`${i.assetsPath?.endsWith("/")?i.assetsPath:`${i.assetsPath}/`}esri/images/search/search-symbol-32.png`,o=(await S(l,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!o?.extent||!o.location)throw new Error(`Could not find location for: ${e}`);let h=new v({url:m,width:24,height:24}),p=new u({geometry:o.location,symbol:h});s.graphics.removeAll(),s.graphics.add(p),await s.goTo(o.extent);let t={address:o.address??e,location:o.location.toJSON(),extent:o.extent.toJSON()},f={value:t,sharedStatePatch:{lastResolvedLocation:{value:t}},sharedResourceAdditions:[{kind:"point",description:t.address,payload:t.location}]};return[`Successfully zoomed to ${t.address}.`,f]}async function T({address:e},s){let{mapView:r}=c(s,["mapView"]);return await y(e,r)}var A=a.object({address:a.string().describe("The full address or place name to locate.")}),W=d(T,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:A,responseFormat:"content_and_artifact"});return W},"config","Graphic","portal/Portal","rest/locator","symbols/PictureMarkerSymbol")
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as p}from"./VOKXKU7M.js";function f(r,e,o){return{name:r,handler:async(a,t)=>{let n=async l=>{let u=await e.beforeAgent?.(l),w=u?{...l,state:{...l.state,...u}}:l,i=await t(w),d=await e.afterAgent?.({...w,result:i});return d?{...i,...d}:i};return e.wrapAgent?await e.wrapAgent(a,n):await n(a)},hooks:e,outputKey:o?.outputKey}}function M(r,e,o){return{name:r,handler:async(a,t)=>e.wrapToolCall?await e.wrapToolCall(a,t):await t(a),outputKey:o?.outputKey}}function y(r){return r.map(e=>s(e.name,e.hooks??{})).filter(e=>!!e)}function s(r,e){let{afterModel:o,beforeModel:a,wrapModelCall:t,wrapToolCall:n}=e;if(!(!o&&!a&&!t&&!n))return p({afterModel:o,beforeModel:a,name:r,wrapModelCall:t,wrapToolCall:n})}export{f as a,M as b,y as c};
2
+ import{a as p}from"./S4LELUBK.js";function f(r,e,o){return{name:r,handler:async(a,t)=>{let n=async l=>{let u=await e.beforeAgent?.(l),w=u?{...l,state:{...l.state,...u}}:l,i=await t(w),d=await e.afterAgent?.({...w,result:i});return d?{...i,...d}:i};return e.wrapAgent?await e.wrapAgent(a,n):await n(a)},hooks:e,outputKey:o?.outputKey}}function M(r,e,o){return{name:r,handler:async(a,t)=>e.wrapToolCall?await e.wrapToolCall(a,t):await t(a),outputKey:o?.outputKey}}function y(r){return r.map(e=>s(e.name,e.hooks??{})).filter(e=>!!e)}function s(r,e){let{afterModel:o,beforeModel:a,wrapModelCall:t,wrapToolCall:n}=e;if(!(!o&&!a&&!t&&!n))return p({afterModel:o,beforeModel:a,name:r,wrapModelCall:t,wrapToolCall:n})}export{f as a,M as b,y as c};
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import a from"./ANRQWYU2.js";import{c as C,e as N}from"./R2PQVY4O.js";import"./G2EGT3CF.js";import"./EWLXNGKH.js";import"./AI6DYOKR.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([{property:B,subclass:D},{a:h,b:S,c:p,d:A}])=>{var G=Object.defineProperty,z=Object.getOwnPropertyDescriptor,P=(t,e,s,n)=>{for(var r=n>1?void 0:n?z(e,s):e,o=t.length-1,a;o>=0;o--)(a=t[o])&&(r=(n?a(e,s,r):a(r))||r);return n&&r&&G(e,s,r),r},x=class extends A{constructor(t){super(t)}getAgents(){return this.agents}generate(){let t=this.getAgents();this.validateAgents(t);for(let o of t)o.generate();let e=S(t.flatMap(o=>o.getSchemas()));for(let[o]of t.entries())e[_(o)]=void 0;let s=C(e),n=this.buildNodes(t),r=this.buildEdges(t);return{workspace:s,createGraph:()=>N(n,r,s,{entryNode:this.getEntryNode(t)})}}getEntryNode(t){return y}isTerminalAgent(t,e){return!1}buildNodes(t){let e={};for(let[s,n]of t.entries()){let r=_(s),o=p(n,s);e[o]=async(a,u)=>{let l=await n.run(F(a,n),u),i={},m=i;return m[r]=l,i}}return e[y]=()=>({}),e[k]=s=>R(s,t),e}buildEdges(t){return[...t.map((e,s)=>({from:y,to:p(e,s)})),...t.map((e,s)=>({from:p(e,s),to:k}))]}};P([B()],x.prototype,"agents",2);x=P([D("ParallelWorkflow")],x);var y="__parallel_fanOut",k="__parallel_join";function _(t){return`__parallel_update_${t}`}function W(t,e){return Object.fromEntries(e.filter(s=>Object.hasOwn(t,s)).map(s=>[s,t[s]]))}function F(t,e){let s=e.inputSchema;return s?{...W(t,h(s)),agentExecutionContext:t.agentExecutionContext,outputMessage:t.outputMessage,status:void 0,summary:""}:{...t,status:void 0,summary:""}}function I(t,e){return t.outputSchema?W(e,h(t.outputSchema)):{}}function K(t,e){let s=t.agentExecutionContext?.messages??[],n=e.agentExecutionContext?.messages??[];return n.length>s.length?n.slice(s.length):void 0}function R(t,e){let s=[],n=[],r=[],o={},a={},u=new Set;for(let[m,J]of e.entries()){let E=_(m),d=t[E];if(a[E]=void 0,!d||typeof d!="object")continue;let c=d,b=c.outputMessage,O=K(t,c),v=c.summary,$=I(J,c),w=b.trim();typeof b=="string"&&w&&s.push(w);let j=v.trim();typeof v=="string"&&j&&n.push(j),Array.isArray(O)&&r.push(...O),c.status&&u.add(c.status);for(let[f,g]of Object.entries($))if(!(g===void 0||f.startsWith("__parallel_update_"))&&!M(t[f],g)){if(!Object.hasOwn(o,f)){o[f]=g;continue}if(!M(o[f],g))throw new Error(`ParallelWorkflow detected conflicting updates for state key "${f}".`)}}let l={...a,...o},i=l;return r.length>0&&(i.agentExecutionContext={...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages,...r]}),s.length&&(i.outputMessage=s.join(`
2
+ import a from"./JKKU4K4C.js";import{c as C,e as N}from"./XKH37FLY.js";import"./HHBNLCJP.js";import"./OL7QBAGS.js";import"./S627D4K7.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([{property:B,subclass:D},{a:h,b:S,c:p,d:A}])=>{var G=Object.defineProperty,z=Object.getOwnPropertyDescriptor,P=(t,e,s,n)=>{for(var r=n>1?void 0:n?z(e,s):e,o=t.length-1,a;o>=0;o--)(a=t[o])&&(r=(n?a(e,s,r):a(r))||r);return n&&r&&G(e,s,r),r},x=class extends A{constructor(t){super(t)}getAgents(){return this.agents}generate(){let t=this.getAgents();this.validateAgents(t);for(let o of t)o.generate();let e=S(t.flatMap(o=>o.getSchemas()));for(let[o]of t.entries())e[_(o)]=void 0;let s=C(e),n=this.buildNodes(t),r=this.buildEdges(t);return{workspace:s,createGraph:()=>N(n,r,s,{entryNode:this.getEntryNode(t)})}}getEntryNode(t){return y}isTerminalAgent(t,e){return!1}buildNodes(t){let e={};for(let[s,n]of t.entries()){let r=_(s),o=p(n,s);e[o]=async(a,u)=>{let l=await n.run(F(a,n),u),i={},m=i;return m[r]=l,i}}return e[y]=()=>({}),e[k]=s=>R(s,t),e}buildEdges(t){return[...t.map((e,s)=>({from:y,to:p(e,s)})),...t.map((e,s)=>({from:p(e,s),to:k}))]}};P([B()],x.prototype,"agents",2);x=P([D("ParallelWorkflow")],x);var y="__parallel_fanOut",k="__parallel_join";function _(t){return`__parallel_update_${t}`}function W(t,e){return Object.fromEntries(e.filter(s=>Object.hasOwn(t,s)).map(s=>[s,t[s]]))}function F(t,e){let s=e.inputSchema;return s?{...W(t,h(s)),agentExecutionContext:t.agentExecutionContext,outputMessage:t.outputMessage,status:void 0,summary:""}:{...t,status:void 0,summary:""}}function I(t,e){return t.outputSchema?W(e,h(t.outputSchema)):{}}function K(t,e){let s=t.agentExecutionContext?.messages??[],n=e.agentExecutionContext?.messages??[];return n.length>s.length?n.slice(s.length):void 0}function R(t,e){let s=[],n=[],r=[],o={},a={},u=new Set;for(let[m,J]of e.entries()){let E=_(m),d=t[E];if(a[E]=void 0,!d||typeof d!="object")continue;let c=d,b=c.outputMessage,O=K(t,c),v=c.summary,$=I(J,c),w=b.trim();typeof b=="string"&&w&&s.push(w);let j=v.trim();typeof v=="string"&&j&&n.push(j),Array.isArray(O)&&r.push(...O),c.status&&u.add(c.status);for(let[f,g]of Object.entries($))if(!(g===void 0||f.startsWith("__parallel_update_"))&&!M(t[f],g)){if(!Object.hasOwn(o,f)){o[f]=g;continue}if(!M(o[f],g))throw new Error(`ParallelWorkflow detected conflicting updates for state key "${f}".`)}}let l={...a,...o},i=l;return r.length>0&&(i.agentExecutionContext={...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages,...r]}),s.length&&(i.outputMessage=s.join(`
3
3
 
4
4
  `)),n.length&&(i.summary=n.join(`
5
5
 
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./RN6WMVZX.js";import"./ONQ6JSBJ.js";import"./S627D4K7.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as goToLayerTool};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import a from"./CCC6LBMY.js";import{a as m}from"./ONQ6JSBJ.js";import{Dc as f}from"./AI6DYOKR.js";import{a as o}from"./VXFQANGJ.js";export default $arcgis.t(([{b:c,c:h}])=>{var g=(a,e,i)=>{let t=a.createQuery();return t.outFields=[e],t.where=i||"1=1",t.num=1,t},w=async(a,e,i,t)=>{let r=t.map?.allLayers.find(y=>y.id===a),n=g(r,e,i.where),s=(await r.queryFeatures(n)).features[0],d=s?s.attributes[e]:null,u=c(r,e,d,t.timeZone),l=h(r,e);return{tool:"getAttribute",layerName:r.title??a,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:i.where}}};async function b({layerId:a,fieldName:e,query:i},t){let{mapView:r}=m(t,["mapView"]),n=await w(a,e,i,r);return JSON.stringify(n,null,2)}var p=o.object({layerId:o.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:o.string().describe("The name of the field/attribute from which to get a field value."),query:o.object({where:o.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),q=f(b,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:p});return q},a)
2
+ import a from"./CCC6LBMY.js";import{a as m}from"./ONQ6JSBJ.js";import{Dc as f}from"./S627D4K7.js";import{a as o}from"./VXFQANGJ.js";export default $arcgis.t(([{b:c,c:h}])=>{var g=(a,e,i)=>{let t=a.createQuery();return t.outFields=[e],t.where=i||"1=1",t.num=1,t},w=async(a,e,i,t)=>{let r=t.map?.allLayers.find(y=>y.id===a),n=g(r,e,i.where),s=(await r.queryFeatures(n)).features[0],d=s?s.attributes[e]:null,u=c(r,e,d,t.timeZone),l=h(r,e);return{tool:"getAttribute",layerName:r.title??a,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:i.where}}};async function b({layerId:a,fieldName:e,query:i},t){let{mapView:r}=m(t,["mapView"]),n=await w(a,e,i,r);return JSON.stringify(n,null,2)}var p=o.object({layerId:o.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:o.string().describe("The name of the field/attribute from which to get a field value."),query:o.object({where:o.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),q=f(b,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:p});return q},a)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a as r}from"./VXFQANGJ.js";export default $arcgis.t(([p,l])=>{var m=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],u=r.enum(m);var f=750;function y(e){return"point"in e&&e.point!==void 0}function h(e){return"layerId"in e&&e.layerId!==void 0}var $=async(e,a)=>{if(y(e)){let{point:t}=e;return{geometry:new p({x:t.x,y:t.y,spatialReference:t.spatialReference?{wkid:t.spatialReference.wkid}:a.spatialReference})}}if(h(e)){let t=a.map?.allLayers.find(o=>o.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let i=t.title??t.id,n=e.where?.trim()||"1=1";try{let o=await t.queryFeatures({where:n,returnGeometry:!0,outSpatialReference:a.spatialReference,num:f+1});if(!o.features.length)return{error:`No features found in geometry layer "${i}" with the specified where clause: ${n}`};if(o.features.length>f)return{error:`Geometry filter for layer "${i}" matched too many features (${o.features.length}+). Please narrow the geometry layer filter.`};let s=o.features.map(d=>d.geometry).filter(d=>!!d);if(!s.length)return{error:"No valid geometries found for the matched geometry layer features."};let c=s.length===1?s[0]:l.executeMany(s);return c?(c.spatialReference||(c.spatialReference=a.spatialReference),{geometry:c}):{error:"Failed to combine geometries from geometry layer."}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},g=r.object({id:r.string()}),b=r.object({id:r.string(),kind:r.literal("point"),payload:r.object({x:r.number(),y:r.number(),spatialReference:r.object({wkid:r.number()}).optional()})}),x=r.object({sharedResourceId:r.string().describe("ID of a point returned by listSharedResources for a previously geocoded address or place."),distance:r.number().optional().describe("Optional buffer distance around the point."),units:u.optional().describe("The units for the distance buffer.")}),j=(e,a)=>{if(!e||!("sharedResourceId"in e))return e;if(!a)throw new Error("Shared resources are unavailable in the tool runtime state.");let t=a.find(n=>{let o=g.safeParse(n);return o.success&&o.data.id===e.sharedResourceId});if(!t)throw new Error(`Shared resource not found: ${e.sharedResourceId}`);let i=b.safeParse(t);if(!i.success)throw new Error(`Shared resource ${e.sharedResourceId} does not contain a valid point.`);return{point:i.data.payload,distance:e.distance,units:e.units}};return{a:u,b:y,c:h,d:$,e:x,f:j}},"geometry/Point","geometry/operators/unionOperator")
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as E,b as I}from"./34O57OGV.js";import{a as R}from"./FDOMMK2M.js";import a from"./AKD5UOVX.js";import{a as F}from"./ONQ6JSBJ.js";import{Dc as S}from"./AI6DYOKR.js";import{a as e}from"./VXFQANGJ.js";export default $arcgis.t(([A,D,W,{a:L,b:v,c:N,d:T,e:q,f:O}])=>{var C=async p=>{let{targetLayer:a,fieldName:n,statisticType:l,mapView:i,layersAndFieldsRegistry:h,geometryFilter:t}=p,s=i.map?.allLayers.find(r=>r.id===a.layerId);if(!s)throw new Error(`Layer '${a.layerId}' not found.`);let w=await i.whenLayerView(s),o=h.get(a.layerId)?.fieldRegistry.get(n),x=o?.alias;if(!o)throw new Error(`Field '${n}' not found.`);let b,c;if(t){let r=await N(t,i);if("error"in r)throw new Error(r.error);if(!r.geometry)throw v(t)?new Error(`No features found matching: ${t.where}`):new Error("Failed to create geometry");if(v(t)){let g=i.map?.allLayers.find(f=>f.id===t.layerId);b={geometryLayerName:g?.title??g?.id,geometryLayerId:t.layerId,geometryWhere:t.where,distance:t.distance,units:t.units,applied:!0}}else L(t)&&(b={point:t.point,distance:t.distance,units:t.units,applied:!0});c=new W({geometry:r.geometry,distance:t.distance,units:t.units,spatialRelationship:"intersects"})}let y=E(w,[n],!1),u=null,m=null,V=10;if(o.type!=="geometry"&&o.type!=="oid"&&o.type!=="global-id")try{let r={layer:s,useFeaturesInView:y,view:y?i:void 0,field:n,sqlWhere:I(s.definitionExpression,a.where),...c&&{filter:c},outStatisticTypes:{include:[l]}};u=await A(r);let g=["string","small-integer","integer"],f=o.domain?.type==="coded-value"?o.domain:null;(g.includes(o.type)||f)&&(m=(await D({layer:s,useFeaturesInView:y,view:y?i:void 0,field:n,sqlWhere:I(s.definitionExpression,a.where),...c&&{filter:c}})).uniqueValueInfos.sort((d,j)=>j.count-d.count).slice(0,V)),m&&o.domain?.type==="coded-value"&&(m=m.map(d=>({...d,value:f?f.getName(d.value)??d.value:d.value})))}catch(r){console.error("Statistics error:",r)}return{tool:"getStatistics",layerName:s.title??a.layerId,summary:`${l} = ${typeof u?.[l]=="number"?u[l]:"N/A"}`,details:{fieldName:n,fieldAlias:x,statisticType:l,statistic:u?.[l]??null,summaryStatistics:u,uniqueValues:m,where:a.where,spatialFilterInfo:b}}};async function U({targetLayer:p,fieldName:a,statisticType:n,geometryFilter:l},i){let h=R(i,"layersAndFieldsRegistry"),{mapView:t}=F(i,["mapView"]),s=O(l,i.state?.agentExecutionContext?.sharedResources),w=await C({targetLayer:p,fieldName:a,statisticType:n,mapView:t,layersAndFieldsRegistry:h,geometryFilter:s});return JSON.stringify(w,null,2)}var $=e.object({layerId:e.string().describe("The layerId of the layer containing the geometry by which to filter."),where:e.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:e.number().optional().describe("The buffer distance around the geometry."),units:T.optional().describe("The units for the distance buffer.")}),G=e.object({point:e.object({x:e.number().describe("X coordinate (longitude) from navigation result"),y:e.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:e.object({wkid:e.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:e.number().optional().describe("Optional buffer distance around the point."),units:T.optional().describe("The units for the distance buffer.")}),Q=e.object({targetLayer:e.object({layerId:e.string().describe("The layerId of the layer containing the field from which to get a value."),where:e.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:e.union([$,G,q]).optional().describe("Geometry filter for spatial queries. Use 'sharedResourceId' with an ID from listSharedResources for a previously geocoded location. Use 'point' for inline coordinates or 'layerId/where' for features from another layer."),fieldName:e.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:e.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),_=S(U,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
2
+ import{a as E,b as I}from"./34O57OGV.js";import{a as R}from"./FDOMMK2M.js";import a from"./UHICISBZ.js";import{a as F}from"./ONQ6JSBJ.js";import{Dc as S}from"./S627D4K7.js";import{a as e}from"./VXFQANGJ.js";export default $arcgis.t(([A,D,U,{a:v,b:L,c:T,d:N,e:q,f:O}])=>{var W=async p=>{let{targetLayer:a,fieldName:n,statisticType:l,mapView:i,layersAndFieldsRegistry:h,geometryFilter:t}=p,s=i.map?.allLayers.find(r=>r.id===a.layerId);if(!s)throw new Error(`Layer '${a.layerId}' not found.`);let w=await i.whenLayerView(s),o=h.get(a.layerId)?.fieldRegistry.get(n),x=o?.alias;if(!o)throw new Error(`Field '${n}' not found.`);let b,d;if(t){let r=await N(t,i);if("error"in r)throw new Error(r.error);if(!r.geometry)throw T(t)?new Error(`No features found matching: ${t.where}`):new Error("Failed to create geometry");if(T(t)){let g=i.map?.allLayers.find(f=>f.id===t.layerId);b={geometryLayerName:g?.title??g?.id,geometryLayerId:t.layerId,geometryWhere:t.where,distance:t.distance,units:t.units,applied:!0}}else L(t)&&(b={point:t.point,distance:t.distance,units:t.units,applied:!0});d=new U({geometry:r.geometry,distance:t.distance,units:t.units,spatialRelationship:"intersects"})}let y=E(w,[n],!1),u=null,m=null,V=10;if(o.type!=="geometry"&&o.type!=="oid"&&o.type!=="global-id")try{let r={layer:s,useFeaturesInView:y,view:y?i:void 0,field:n,sqlWhere:I(s.definitionExpression,a.where),...d&&{filter:d},outStatisticTypes:{include:[l]}};u=await A(r);let g=["string","small-integer","integer"],f=o.domain?.type==="coded-value"?o.domain:null;(g.includes(o.type)||f)&&(m=(await D({layer:s,useFeaturesInView:y,view:y?i:void 0,field:n,sqlWhere:I(s.definitionExpression,a.where),...d&&{filter:d}})).uniqueValueInfos.sort((c,j)=>j.count-c.count).slice(0,V)),m&&o.domain?.type==="coded-value"&&(m=m.map(c=>({...c,value:f?f.getName(c.value)??c.value:c.value})))}catch(r){console.error("Statistics error:",r)}return{tool:"getStatistics",layerName:s.title??a.layerId,summary:`${l} = ${typeof u?.[l]=="number"?u[l]:"N/A"}`,details:{fieldName:n,fieldAlias:x,statisticType:l,statistic:u?.[l]??null,summaryStatistics:u,uniqueValues:m,where:a.where,spatialFilterInfo:b}}};async function C({targetLayer:p,fieldName:a,statisticType:n,geometryFilter:l},i){let h=R(i,"layersAndFieldsRegistry"),{mapView:t}=F(i,["mapView"]),s=O(l,i.state?.agentExecutionContext?.sharedResources),w=await W({targetLayer:p,fieldName:a,statisticType:n,mapView:t,layersAndFieldsRegistry:h,geometryFilter:s});return JSON.stringify(w,null,2)}var $=e.object({layerId:e.string().describe("The layerId of the layer containing the geometry by which to filter."),where:e.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:e.number().optional().describe("The buffer distance around the geometry."),units:v.optional().describe("The units for the distance buffer.")}),G=e.object({point:e.object({x:e.number().describe("X coordinate (longitude) from navigation result"),y:e.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:e.object({wkid:e.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:e.number().optional().describe("Optional buffer distance around the point."),units:v.optional().describe("The units for the distance buffer.")}),Q=e.object({targetLayer:e.object({layerId:e.string().describe("The layerId of the layer containing the field from which to get a value."),where:e.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:e.union([$,G,q]).optional().describe("Geometry filter for spatial queries. Use 'sharedResourceId' with an ID from listSharedResources for a previously geocoded location. Use 'point' for inline coordinates or 'layerId/where' for features from another layer."),fieldName:e.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:e.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Z=S(C,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
3
3
 
4
4
  USE THIS TOOL FOR:
5
5
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -11,4 +11,4 @@ DO NOT USE FOR:
11
11
  - "Show / list / find features" \u2014 use queryFeatures instead
12
12
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
13
13
 
14
- Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Q});return _},"smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","layers/support/FeatureFilter",a)
14
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Q});return Z},"smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","layers/support/FeatureFilter",a)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{a}from"./RLB6TK6B.js";import"./ONQ6JSBJ.js";import"./S627D4K7.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export{a as resetMapTool};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import b from"./VMZZR7MY.js";import"./34O57OGV.js";import"./FDOMMK2M.js";import a from"./UHICISBZ.js";import"./ONQ6JSBJ.js";import"./S627D4K7.js";import"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([,a])=>{return a},a,b)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{d as b}from"./G2EGT3CF.js";import{Ya as G,a as E,b as y,ka as h}from"./EWLXNGKH.js";var x=new Set(["agentExecutionContext","outputMessage","summary","status"]);function O(r){let o=[...new Set([...r].filter(n=>x.has(n)))];if(o.length!==0)throw new Error(`custom state cannot define reserved runtime fields: ${o.join(", ")}.`)}function $(r){let o=Object.entries(r);return Object.fromEntries(o.map(([n,t])=>[n,h({reducer:(i,g)=>g,default:()=>t})]))}function S(r={}){O(Object.keys(r));let o=$(r);return h.Root({...o,agentExecutionContext:h({reducer:(n,t)=>({...n,...t}),default:b}),outputMessage:h({reducer:(n="",t)=>typeof t=="string"&&t.trim()?t:n,default:()=>""}),summary:h({reducer:(n="",t)=>typeof t=="string"?t:n,default:()=>""}),status:h({reducer:(n,t)=>t??n,default:()=>{}})})}function C(r){let o=new Set;for(let t of r)for(let i of Object.keys(t.shape??{}))o.add(i);let n=Object.fromEntries([...o].map(t=>[t,void 0]));return S(n)}function P(r,o,n,t={}){let{agent:i,entryNode:g,middlewares:c=[]}=t,s=new G(n);if(Object.keys(r).length===0)throw new Error("Graph requires at least one node.");if(o.length===0)throw new Error("Graph requires at least one edge.");if(c.length>0&&!i)throw new Error("Graph middleware requires agent metadata.");let a=new Set(Object.keys(r)),m=new Map,w=new Map;for(let e of a)m.set(e,0),w.set(e,0);for(let e of o)"to"in e?(a.has(e.from)&&w.set(e.from,(w.get(e.from)??0)+1),a.has(e.to)&&m.set(e.to,(m.get(e.to)??0)+1)):a.has(e.from)&&w.set(e.from,(w.get(e.from)??0)+1);for(let[e,f]of Object.entries(r)){let u=N(i,e,c,async(d,p)=>await Promise.resolve(f(d,p))),l=async(d,p)=>await u(d,p);s=s.addNode(e,l)}for(let e of o)if("to"in e){let f=e.from,u=e.to;if(!a.has(f))throw new Error(`Graph edge references unknown from-node: ${f}`);if(!a.has(u))throw new Error(`Graph edge references unknown to-node: ${u}`);s.addEdge(f,u)}else{let f=e.from;if(!a.has(f))throw new Error(`Graph conditional edge references unknown from-node: ${f}`);s.addConditionalEdges(f,async(u,l)=>{let d=await e.decide(u,l);if(!d)return y;if(!a.has(d))throw new Error(`Graph conditional edge returned unknown node: ${d}`);return d})}let k=v(a,m,g);s.addEdge(E,k);let j=[...a].filter(e=>(w.get(e)??0)===0);for(let e of j)s.addEdge(e,y);return s}function N(r,o,n,t){return!n.length||!r?t:async(i,g)=>await n.reduceRight((c,s)=>async a=>await s.handler(a,c),async c=>{let s=await t(c.state,c.config);return{...c.state,...s}})({agent:r,config:g,nodeName:o,state:i})}function v(r,o,n){if(n){if(!r.has(n))throw new Error(`Graph entry node references unknown node: ${n}`);return n}let t=[...r].filter(i=>(o.get(i)??0)===0);if(t.length!==1)throw new Error(`Graph could not infer a single entry node (found ${t.length}). Provide an explicit entryNode or ensure exactly one node has no incoming edges.`);return t[0]}export{O as a,$ as b,S as c,C as d,P as e};
2
+ import{d as b}from"./HHBNLCJP.js";import{Ya as G,ka as h,r as E,s as y}from"./OL7QBAGS.js";var x=new Set(["agentExecutionContext","outputMessage","summary","status"]);function O(r){let o=[...new Set([...r].filter(n=>x.has(n)))];if(o.length!==0)throw new Error(`custom state cannot define reserved runtime fields: ${o.join(", ")}.`)}function $(r){let o=Object.entries(r);return Object.fromEntries(o.map(([n,t])=>[n,h({reducer:(i,g)=>g,default:()=>t})]))}function S(r={}){O(Object.keys(r));let o=$(r);return h.Root({...o,agentExecutionContext:h({reducer:(n,t)=>({...n,...t}),default:b}),outputMessage:h({reducer:(n="",t)=>typeof t=="string"&&t.trim()?t:n,default:()=>""}),summary:h({reducer:(n="",t)=>typeof t=="string"?t:n,default:()=>""}),status:h({reducer:(n,t)=>t??n,default:()=>{}})})}function C(r){let o=new Set;for(let t of r)for(let i of Object.keys(t.shape??{}))o.add(i);let n=Object.fromEntries([...o].map(t=>[t,void 0]));return S(n)}function P(r,o,n,t={}){let{agent:i,entryNode:g,middlewares:c=[]}=t,s=new G(n);if(Object.keys(r).length===0)throw new Error("Graph requires at least one node.");if(o.length===0)throw new Error("Graph requires at least one edge.");if(c.length>0&&!i)throw new Error("Graph middleware requires agent metadata.");let a=new Set(Object.keys(r)),m=new Map,w=new Map;for(let e of a)m.set(e,0),w.set(e,0);for(let e of o)"to"in e?(a.has(e.from)&&w.set(e.from,(w.get(e.from)??0)+1),a.has(e.to)&&m.set(e.to,(m.get(e.to)??0)+1)):a.has(e.from)&&w.set(e.from,(w.get(e.from)??0)+1);for(let[e,f]of Object.entries(r)){let u=N(i,e,c,async(d,p)=>await Promise.resolve(f(d,p))),l=async(d,p)=>await u(d,p);s=s.addNode(e,l)}for(let e of o)if("to"in e){let f=e.from,u=e.to;if(!a.has(f))throw new Error(`Graph edge references unknown from-node: ${f}`);if(!a.has(u))throw new Error(`Graph edge references unknown to-node: ${u}`);s.addEdge(f,u)}else{let f=e.from;if(!a.has(f))throw new Error(`Graph conditional edge references unknown from-node: ${f}`);s.addConditionalEdges(f,async(u,l)=>{let d=await e.decide(u,l);if(!d)return y;if(!a.has(d))throw new Error(`Graph conditional edge returned unknown node: ${d}`);return d})}let k=v(a,m,g);s.addEdge(E,k);let j=[...a].filter(e=>(w.get(e)??0)===0);for(let e of j)s.addEdge(e,y);return s}function N(r,o,n,t){return!n.length||!r?t:async(i,g)=>await n.reduceRight((c,s)=>async a=>await s.handler(a,c),async c=>{let s=await t(c.state,c.config);return{...c.state,...s}})({agent:r,config:g,nodeName:o,state:i})}function v(r,o,n){if(n){if(!r.has(n))throw new Error(`Graph entry node references unknown node: ${n}`);return n}let t=[...r].filter(i=>(o.get(i)??0)===0);if(t.length!==1)throw new Error(`Graph could not infer a single entry node (found ${t.length}). Provide an explicit entryNode or ensure exactly one node has no incoming edges.`);return t[0]}export{O as a,$ as b,S as c,C as d,P as e};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ var i=(e,o)=>(s,t)=>{let c=t?.configurable?.services;for(let r of e)if(!c?.[r])throw new Error(`${o} requires services.${r} to be available.`);return s};export{i as a};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./RHYNE5OE.js";import{a as t}from"./FDOMMK2M.js";import{a as l}from"./ONQ6JSBJ.js";import{Dc as d}from"./AI6DYOKR.js";import{a}from"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([o])=>{var g=.7,b=10;async function S(i){let{query:e,layerIds:s,includeSummaryStatistics:r=!1,fieldSearch:c,layersAndFieldsRegistry:m,embeddingCache:y,mapView:u,minScore:f=g,topResults:h=b}=i,n=await c.searchFields({text:e,layerIds:s,minScore:f,topResults:h,embeddingCache:y}),p=await o(n,m,u,r);return{matches:n,...p}}var v=a.object({query:a.string().describe("A concise semantic description of the fields relevant to the user's task."),layerIds:a.array(a.string()).min(1).describe("Layer IDs returned by findRelevantLayers, restricted to layers relevant to the current task."),includeSummaryStatistics:a.boolean().optional().default(!1).describe("Set to true only when the task directly asks for numeric summaries such as average, minimum, maximum, total, variance, or range.")});async function w(i,e){let{mapView:s}=l(e,["mapView"]),r=await S({...i,fieldSearch:t(e,"fieldSearch"),layersAndFieldsRegistry:t(e,"layersAndFieldsRegistry"),embeddingCache:t(e,"embeddingCache"),mapView:s});return JSON.stringify(r,null,2)}var A=d(w,{name:"findRelevantFields",description:"Finds relevant fields within candidate layers. Returns ranked matches, field metadata, categorical values, and optional numeric summary statistics. Call findRelevantLayers first when layer IDs are not already known.",schema:v});return A},b)
2
+ import b from"./RHYNE5OE.js";import{a as t}from"./FDOMMK2M.js";import{a as l}from"./ONQ6JSBJ.js";import{Dc as d}from"./S627D4K7.js";import{a}from"./VXFQANGJ.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([o])=>{var g=.7,b=10;async function S(i){let{query:e,layerIds:s,includeSummaryStatistics:r=!1,fieldSearch:c,layersAndFieldsRegistry:m,embeddingCache:y,mapView:u,minScore:f=g,topResults:h=b}=i,n=await c.searchFields({text:e,layerIds:s,minScore:f,topResults:h,embeddingCache:y}),p=await o(n,m,u,r);return{matches:n,...p}}var v=a.object({query:a.string().describe("A concise semantic description of the fields relevant to the user's task."),layerIds:a.array(a.string()).min(1).describe("Layer IDs returned by findRelevantLayers, restricted to layers relevant to the current task."),includeSummaryStatistics:a.boolean().optional().default(!1).describe("Set to true only when the task directly asks for numeric summaries such as average, minimum, maximum, total, variance, or range.")});async function w(i,e){let{mapView:s}=l(e,["mapView"]),r=await S({...i,fieldSearch:t(e,"fieldSearch"),layersAndFieldsRegistry:t(e,"layersAndFieldsRegistry"),embeddingCache:t(e,"embeddingCache"),mapView:s});return JSON.stringify(r,null,2)}var A=d(w,{name:"findRelevantFields",description:"Finds relevant fields within candidate layers. Returns ranked matches, field metadata, categorical values, and optional numeric summary statistics. Call findRelevantLayers first when layer IDs are not already known.",schema:v});return A},b)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{Dc as u}from"./AI6DYOKR.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([d,{property:a,subclass:h}])=>{var l=Object.defineProperty,m=Object.getOwnPropertyDescriptor,s=(e,t,n,r)=>{for(var o=r>1?void 0:r?m(t,n):t,c=e.length-1,p;c>=0;c--)(p=e[c])&&(o=(r?p(t,n,o):p(o))||o);return r&&o&&l(t,n,o),o},i=class extends d{constructor(e){super(e),this.resultMode="continue",this.middlewares=[]}getTool(){return u(this._executeWithMiddlewares.bind(this),{name:this.name,description:this.description,returnDirect:this.resultMode==="terminal",schema:this.inputSchema})}async _executeWithMiddlewares(e,t){let n=async r=>{let o=await this.execute(r.input,r.config);return this._validateOutput(o)};return await this.middlewares.reduceRight((r,o)=>async c=>await o.handler(c,r),n)({config:t,input:e,tool:this,toolCallId:f(t)})}_validateOutput(e){if(!this.outputSchema)return e;let t=this.outputSchema.safeParse(e);if(!t.success)throw new Error(`FunctionTool output schema validation failed: ${t.error.message}`);return t.data}};s([a()],i.prototype,"name",2);s([a()],i.prototype,"description",2);s([a()],i.prototype,"resultMode",2);s([a()],i.prototype,"inputSchema",2);s([a()],i.prototype,"outputSchema",2);s([a()],i.prototype,"middlewares",2);s([a()],i.prototype,"execute",2);i=s([h("FunctionTool")],i);function f(e){let t=e?.toolCall;return typeof t?.id=="string"?t.id:void 0}return i},"core/Accessor","core/accessorSupport/decorators")
2
+ import{Dc as u}from"./S627D4K7.js";import"./MWYBF3F3.js";import"./UZLQALHY.js";export default $arcgis.t(([d,{property:a,subclass:h}])=>{var l=Object.defineProperty,m=Object.getOwnPropertyDescriptor,s=(e,t,n,r)=>{for(var o=r>1?void 0:r?m(t,n):t,c=e.length-1,p;c>=0;c--)(p=e[c])&&(o=(r?p(t,n,o):p(o))||o);return r&&o&&l(t,n,o),o},i=class extends d{constructor(e){super(e),this.resultMode="continue",this.middlewares=[]}getTool(){return u(this._executeWithMiddlewares.bind(this),{name:this.name,description:this.description,returnDirect:this.resultMode==="terminal",schema:this.inputSchema})}async _executeWithMiddlewares(e,t){let n=async r=>{let o=await this.execute(r.input,r.config);return this._validateOutput(o)};return await this.middlewares.reduceRight((r,o)=>async c=>await o.handler(c,r),n)({config:t,input:e,tool:this,toolCallId:f(t)})}_validateOutput(e){if(!this.outputSchema)return e;let t=this.outputSchema.safeParse(e);if(!t.success)throw new Error(`FunctionTool output schema validation failed: ${t.error.message}`);return t.data}};s([a()],i.prototype,"name",2);s([a()],i.prototype,"description",2);s([a()],i.prototype,"resultMode",2);s([a()],i.prototype,"inputSchema",2);s([a()],i.prototype,"outputSchema",2);s([a()],i.prototype,"middlewares",2);s([a()],i.prototype,"execute",2);i=s([h("FunctionTool")],i);function f(e){let t=e?.toolCall;return typeof t?.id=="string"?t.id:void 0}return i},"core/Accessor","core/accessorSupport/decorators")
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import"./UZLQALHY.js";var e='---\nname: filter\ndescription: Changes feature emphasis on the map by including, excluding, highlighting, dimming, or clearing filtered features. Use when the user asks to visually filter feature-layer data.\nallowed-tools: findRelevantLayers findRelevantFields setFeatureEffect resetMap clearFilters\n---\n\n# Filter\n\n- Use `clearFilters` when the user asks only to remove feature filters or effects. Use `resetMap` only when the user asks to reset the broader map state.\n- Reuse a preceding query result from this run whenever it contains the layer ID and filtering criteria needed for the visual operation. Do not repeat layer or field discovery in that case.\n- A preceding query result may provide the layer ID, where clause, geometry filter, `useCurrentExtent`, object IDs, and count. Preserve and reuse those values rather than reconstructing them.\n- If no usable preceding query geometry exists and the task refers to an address, place, or location resolved by an earlier agent, call `listSharedResources` with `point` as the requested kind. If a resource description clearly matches the location, pass its exact ID as `geometryFilter.sharedResourceId` and use `where: "1=1"` unless the user requests an additional attribute filter. If no resource clearly matches a referential location such as "this location," state that the spatial anchor is unavailable and do not guess coordinates.\n- If no usable preceding query result exists, start with `findRelevantLayers`. Use the assigned task as the semantic query. If no relevant layers are returned, explain that no matching map layer was found and stop. Never invent a layer ID.\n- When discovery is required, call `findRelevantFields` with only relevant layer IDs before constructing a filter. Use only the exact field names and categorical values returned by `findRelevantFields`.\n- Leave `includeSummaryStatistics` false unless the filter criteria explicitly depend on a requested numeric summary.\n- Use real field names rather than aliases in SQL-92 where clauses. Use `1=1` when no attribute filter is requested.\n- For highlight, show, include, exclude, or other visual-filter requests with feature criteria, call `setFeatureEffect` using the same layer ID, where clause, geometry filter, and `useCurrentExtent` value determined by the preceding query or discovery steps.\n- If a preceding query returned object IDs for ranked, top-N, or otherwise selected records, pass those object IDs to `setFeatureEffect` instead of rebuilding the selection using only a where clause.\n- Prefer the default feature effects unless the user explicitly requests a particular visual treatment.\n- Set `useCurrentExtent` only when the user explicitly refers to the current view or visible map area.\n- When available, use the preceding query result for feature counts or attribute details in the final response.\n- Report the `setFeatureEffect` outcome faithfully. Do not claim that a map effect was applied when the tool failed or no matching layer or field was found.\n';export{e as default};