@arcgis/ai-components 5.2.0-next.36 → 5.2.0-next.38

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 (53) hide show
  1. package/dist/cdn/{KRE4U7V7.js → 2K3FTW7J.js} +1 -1
  2. package/dist/cdn/{TSEQVE2H.js → 32B6ZVYG.js} +1 -1
  3. package/dist/cdn/{L77BTGXY.js → 3RPE2QMJ.js} +1 -1
  4. package/dist/cdn/{4RZPOYZ7.js → 3X7JLPXS.js} +1 -1
  5. package/dist/cdn/53TGCGSX.js +18 -0
  6. package/dist/cdn/{JEIMRNYM.js → 7GE723EX.js} +1 -1
  7. package/dist/cdn/{S27EJSLC.js → B7W5WD4R.js} +1 -1
  8. package/dist/cdn/BLKXZEPZ.js +56 -0
  9. package/dist/cdn/{IGZWQJW7.js → D36UDLAY.js} +1 -1
  10. package/dist/cdn/{7IFCBXV7.js → DFF2LGQI.js} +1 -1
  11. package/dist/cdn/{YRBANNQ5.js → E2JBQWHX.js} +1 -1
  12. package/dist/cdn/{O7TGCM5P.js → EJ2LRQVR.js} +1 -1
  13. package/dist/cdn/{Q73PK7Q7.js → FDPJ5Y3M.js} +1 -1
  14. package/dist/cdn/FK7ENS6I.js +2 -0
  15. package/dist/cdn/{CIW3QMKV.js → FNFJYOHX.js} +1 -1
  16. package/dist/cdn/{2NMR43NW.js → GJHBXGNP.js} +1 -1
  17. package/dist/cdn/HW2FV2RU.js +48 -0
  18. package/dist/cdn/{XVQJBUMY.js → I4A2LAZS.js} +1 -1
  19. package/dist/cdn/{O3F47IO5.js → I5QIEV37.js} +1 -1
  20. package/dist/cdn/{YYY7HKYX.js → IBKTXP76.js} +1 -1
  21. package/dist/cdn/MU52B4SV.js +181 -0
  22. package/dist/cdn/{SMADRJ67.js → NV2KTZTO.js} +1 -1
  23. package/dist/cdn/ON5PWODA.js +208 -0
  24. package/dist/cdn/{IXAKT6L3.js → P22UEKRX.js} +1 -1
  25. package/dist/cdn/PA5W5PWE.js +2 -0
  26. package/dist/cdn/{WAVKMZA6.js → QA7IATZC.js} +1 -1
  27. package/dist/cdn/{IC5P5NYY.js → QJJ6YSAC.js} +1 -1
  28. package/dist/cdn/{HOCTVCHH.js → RHM3WKYV.js} +1 -1
  29. package/dist/cdn/{E7TMP4YV.js → SHFSDORL.js} +1 -1
  30. package/dist/cdn/{AMVOJNWN.js → TIEV263K.js} +1 -1
  31. package/dist/cdn/{HXOSLGWU.js → TKSWXCCJ.js} +1 -1
  32. package/dist/cdn/{AFLQZIKS.js → VAX3IAC3.js} +31 -31
  33. package/dist/cdn/{WDE3HN7K.js → XHJTT7BG.js} +1 -1
  34. package/dist/cdn/XNITXZDU.js +2 -0
  35. package/dist/cdn/{C7E7MJSR.js → XXIKORXX.js} +1 -1
  36. package/dist/cdn/{HBYZSLEZ.js → Y7KEZCVG.js} +1 -1
  37. package/dist/cdn/agent-utils/index.js +1 -1
  38. package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
  39. package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
  40. package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
  41. package/dist/cdn/index.js +1 -1
  42. package/dist/docs/api.json +1 -1
  43. package/dist/docs/docs.json +1 -1
  44. package/dist/docs/web-types.json +1 -1
  45. package/package.json +9 -9
  46. package/dist/cdn/6LZ6GOHF.js +0 -56
  47. package/dist/cdn/CJIV4KJZ.js +0 -179
  48. package/dist/cdn/CVHJMR5X.js +0 -2
  49. package/dist/cdn/EBRNMPPO.js +0 -48
  50. package/dist/cdn/IKEF7ZHH.js +0 -181
  51. package/dist/cdn/LODKJRS4.js +0 -2
  52. package/dist/cdn/PKHQW7QU.js +0 -18
  53. package/dist/cdn/VKU4WAQV.js +0 -2
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./HXOSLGWU.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{c as s,d as n}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as r,z as o}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,{fetchKnowledgeGraph:p},,,a])=>{var i=class extends r{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#e;#i;#t;#r;get serviceUrl(){return this.#i}set serviceUrl(t){this.#i=t}async getContext(){let t=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#e)return{...t,view:this.#e};if(this.#t)try{let e=await this.#t;return{...t,knowledgeGraph:e}}catch(e){console.error("Failed to load knowledge graph via service URL:",e)}if(!this.context?.knowledgeGraph&&!this.context?.view)throw new Error("arcgis-assistant-knowledge-agent requires either a knowledgeGraph or view in context, and neither were provided");return this.context}willUpdate(t){t.has("serviceUrl")&&this.serviceUrl?this.#t=p(this.serviceUrl):this.#t=void 0}load(){this.#e=n(this)??void 0,this.#r=s(this)}disconnectedCallback(){this.#r?.unregister(this.agent.id),super.disconnectedCallback()}};o("arcgis-assistant-knowledge-agent",i);return i},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c)
2
+ import c from"./TKSWXCCJ.js";import b from"./VAX3IAC3.js";import a from"./HW2FV2RU.js";import{c as s,d as n}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as r,z as o}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./3X7JLPXS.js";import"./BLKXZEPZ.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,{fetchKnowledgeGraph:p},,,a])=>{var i=class extends r{constructor(){super(...arguments),this.agent=a}static{this.properties={referenceElement:1,serviceUrl:3,context:0}}#e;#i;#t;#r;get serviceUrl(){return this.#i}set serviceUrl(t){this.#i=t}async getContext(){let t=this.context?{...this.context,knowledgeGraph:void 0,view:void 0}:{};if(this.#e)return{...t,view:this.#e};if(this.#t)try{let e=await this.#t;return{...t,knowledgeGraph:e}}catch(e){console.error("Failed to load knowledge graph via service URL:",e)}if(!this.context?.knowledgeGraph&&!this.context?.view)throw new Error("arcgis-assistant-knowledge-agent requires either a knowledgeGraph or view in context, and neither were provided");return this.context}willUpdate(t){t.has("serviceUrl")&&this.serviceUrl?this.#t=p(this.serviceUrl):this.#t=void 0}load(){this.#e=n(this)??void 0,this.#r=s(this)}disconnectedCallback(){this.#r?.unregister(this.agent.id),super.disconnectedCallback()}};o("arcgis-assistant-knowledge-agent",i);return i},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/knowledgeGraphService",a,b,c)
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as m}from"./4RZPOYZ7.js";import{a as k,b as E,ta as $}from"./CJIV4KJZ.js";import{a as f}from"./WNS5ZUF5.js";export default $arcgis.t(([,,,,,,{q:N,r:T},{a:b,b:v,c:x,d:C,e:F,f:R,g:L,h:_,i:I,j:M,k:Z,l:A,m:S,n:q,o:p,p:j}])=>{var w=[C,F,R,L,_,I,M,Z,A];async function G(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),c=r.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((h,z)=>`${z+1}. layerId=${h.id} | title=${h.title??""} | name=${h.name??""} | score=${h.score.toFixed(2)}`).join(`
2
+ import b from"./VAX3IAC3.js";import a from"./HW2FV2RU.js";import{a as m}from"./3X7JLPXS.js";import{Va as $,a as k,b as E}from"./ON5PWODA.js";import{a as f}from"./WNS5ZUF5.js";export default $arcgis.t(([,,,,,,{q:N,r:T},{a:b,b:v,c:x,d:C,e:F,f:R,g:L,h:_,i:I,j:M,k:Z,l:A,m:S,n:q,o:p,p:j}])=>{var w=[C,F,R,L,_,I,M,Z,A];async function G(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),c=r.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((h,z)=>`${z+1}. layerId=${h.id} | title=${h.title??""} | name=${h.name??""} | score=${h.score.toFixed(2)}`).join(`
3
3
  `):"",l=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",i=e.intent==="goToBookmark"&&c.length?`Available bookmarks:
4
4
  ${c.map(h=>`- ${h}`).join(`
5
5
  `)}`:"",o=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as c}from"./CVHJMR5X.js";export default $arcgis.t(([l,{property:i,subclass:y},{watch:d}])=>{var w=Object.defineProperty,g=Object.getOwnPropertyDescriptor,t=(s,a,p,o)=>{for(var r=o>1?void 0:o?g(a,p):a,h=s.length-1,n;h>=0;h--)(n=s[h])&&(r=(o?n(a,p,r):n(r))||r);return o&&r&&w(a,p,r),r},m=()=>{throw new Error("createGraph method not implemented.")},e=class extends l{constructor(){super(...arguments),this.description="",this.middlewares=[],this.createGraph=m,this.workspace=c()}initialize(){this.addHandles([d(()=>[this.name,this.description],()=>this.generate(),{initial:!0,sync:!0}),d(()=>this.createGraph,()=>this._compiledGraph=void 0)])}get id(){return this.name.replace(/\s+/gu,"-").toLowerCase()}get registration(){return{id:this.id,name:this.name,description:this.description,createGraph:this.createGraph,workspace:this.workspace}}async run(s={},a){return this.createGraph===m&&this.generate(),this._compiledGraph=this._compiledGraph??this.createGraph().compile(),await this._compiledGraph.invoke(s,a)}};t([i({readOnly:!0})],e.prototype,"id",1);t([i()],e.prototype,"name",2);t([i()],e.prototype,"description",2);t([i()],e.prototype,"middlewares",2);t([i({readOnly:!0})],e.prototype,"createGraph",2);t([i({readOnly:!0})],e.prototype,"workspace",2);t([i({readOnly:!0})],e.prototype,"registration",1);e=t([y("BaseAgent")],e);return e},"core/Accessor","core/accessorSupport/decorators","core/reactiveUtils")
2
+ import{a as c}from"./XNITXZDU.js";export default $arcgis.t(([l,{property:i,subclass:y},{watch:d}])=>{var w=Object.defineProperty,g=Object.getOwnPropertyDescriptor,t=(s,a,p,o)=>{for(var r=o>1?void 0:o?g(a,p):a,h=s.length-1,n;h>=0;h--)(n=s[h])&&(r=(o?n(a,p,r):n(r))||r);return o&&r&&w(a,p,r),r},m=()=>{throw new Error("createGraph method not implemented.")},e=class extends l{constructor(){super(...arguments),this.description="",this.middlewares=[],this.createGraph=m,this.workspace=c()}initialize(){this.addHandles([d(()=>[this.name,this.description],()=>this.generate(),{initial:!0,sync:!0}),d(()=>this.createGraph,()=>this._compiledGraph=void 0)])}get id(){return this.name.replace(/\s+/gu,"-").toLowerCase()}get registration(){return{id:this.id,name:this.name,description:this.description,createGraph:this.createGraph,workspace:this.workspace}}async run(s={},a){return this.createGraph===m&&this.generate(),this._compiledGraph=this._compiledGraph??this.createGraph().compile(),await this._compiledGraph.invoke(s,a)}};t([i({readOnly:!0})],e.prototype,"id",1);t([i()],e.prototype,"name",2);t([i()],e.prototype,"description",2);t([i()],e.prototype,"middlewares",2);t([i({readOnly:!0})],e.prototype,"createGraph",2);t([i({readOnly:!0})],e.prototype,"workspace",2);t([i({readOnly:!0})],e.prototype,"registration",1);e=t([y("BaseAgent")],e);return e},"core/Accessor","core/accessorSupport/decorators","core/reactiveUtils")
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{Ra as i}from"./IKEF7ZHH.js";async function n(a,t,e){if(e===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
2
+ import{Wa as i}from"./MU52B4SV.js";async function n(a,t,e){if(e===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
3
3
 
4
4
  If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
5
 
@@ -0,0 +1,18 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import c from"./RHM3WKYV.js";import b from"./VAX3IAC3.js";import a from"./HW2FV2RU.js";import{a as n}from"./3X7JLPXS.js";import{Va as N,a as I,b as S}from"./ON5PWODA.js";import{ca as $}from"./MU52B4SV.js";export default $arcgis.t(([,,,,,,P,U,{p:k,r:T},{C:M,D:z,E:L,F:D,G:F,H:O,a:A,m:w,n:R,o:y,p:V},b])=>{var W=async(e,t)=>(await n({text:"Exiting Data Exploration agent"},t),e),B=async(e,t)=>{await n({text:"Requesting LLM for layer filter results"},t);let a=await w("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:d,userTimezoneOffset:o}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},i=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:s,tools:F}),r=[...e.dataExplorationMessages,i];if(!((i.tool_calls?.length??0)>0))return await n({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:r};let c=r,l=i.content.toString();return await b(i,t),{...e,dataExplorationMessages:c,outputMessage:l}},H=async(e,t)=>{await n({text:"Requesting LLM for layer query results"},t);let a=await w("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:d,userTimezoneOffset:o}=L(),s=e.agentExecutionContext.sharedState,i=s.lastNavigatedFeatures?.value,r=s.lastResolvedLocation?.value,c="none";if(i!=null)try{c=JSON.stringify(i)}catch{c="none"}let l="none";if(r!=null)try{l=JSON.stringify({address:r.address,location:r.location})}catch{l="none"}let g={layerFieldInfo:e.layerFieldInfo,userTimezone:d,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:c,lastResolvedLocation:l},m=await T({promptText:a,modelTier:"advanced",config:t,messages:e.dataExplorationMessages,inputVariables:g,tools:D}),h=(m.tool_calls?.length??0)>0,f=m.content.toString();return await b(m,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,m],...h?{}:{outputMessage:f},status:"success",summary:f&&!h?R(f):"Query planning completed."}},J=async(e,t)=>{try{await n({text:"Requesting LLM for summary on query results"},t);let a=await w("summarize_query_response_prompt"),d={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await k({promptText:a,modelTier:"fast",config:t,messages:e.dataExplorationMessages,inputVariables:d}),s=typeof o=="string"?o:o.content,i=new $(s);await n({text:`Received response from LLM: ${s}`},t);let r=s;return{...e,outputMessage:r,status:"success",summary:r?R(r):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,i]}}catch(a){throw await n({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${a instanceof Error?a.message:String(a)}`)}};async function K(e,t){if((e.queryResponse??[]).some(d=>{let o=d.details;return typeof o=="object"&&o!==null&&"error"in o}))return await n({text:"Skipping layer filter tool because query response contains an error."},t),{...e};let a=await new A(F,{handleToolErrors:!1}).invoke({messages:e.dataExplorationMessages},t);return await n({text:`Finished executing layer filter tool: ${a.messages.map(d=>d.content).join(", ")}`},t),{...e}}var X=10,Y=["string","small-integer","integer"],Z=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:d=!0}={})=>{let o=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(o=await P({layer:e,field:t.name}));let i=t.domain?.type==="coded-value"?t.domain:null;d&&(Y.includes(t.type)||i)&&(s=(await U({layer:e,field:t.name})).uniqueValueInfos.sort((r,c)=>c.count-r.count).slice(0,X),i&&(s=s.map(r=>({...r,value:i.getName(r.value)??r.value}))))}}catch(i){console.error(`Error fetching statistics for field ${t.name}:`,i)}return{summaryStatistics:o,uniqueValues:s}};function ee(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function te(e,t,a,d=!0){let o=[],s=[],i=[];for(let r of e){let c=function(p){let u=t.get(p)?.layerItem;return u?[u.name&&`Name: ${u.name}`,u.title&&`Title: ${u.title}`,u.description&&`Description: ${u.description}`].filter(Boolean).join(" | "):p},{layerId:l,results:g}=r,m=a.map?.allLayers.find(p=>p.id===l),h=t.get(l)?.fieldRegistry;if(!h)continue;let f=o.find(p=>p.layerId===l);f||(f={layerId:l,layerSummary:c(l),fieldInfos:[]},o.push(f));for(let p of g){let u=h.get(p.name);if(!u)continue;let x=u.statistics,v=d&&!x?.summaryStatistics,q=ee(u.type,u.domain?.type)&&!x?.uniqueValues,_=v||q;if(i.push({layerId:l,fieldName:u.name,didFetchStatistics:_}),_){let G=Z(m,u,{includeSummaryStatistics:v,includeUniqueValues:q}).then(C=>{let E={summaryStatistics:x?.summaryStatistics??null,uniqueValues:x?.uniqueValues??null};v&&(E.summaryStatistics=C.summaryStatistics),q&&(E.uniqueValues=C.uniqueValues),h.set(u.name,{...u,statistics:E}),u.statistics=E});s.push(G)}f.fieldInfos.push(u)}}return await Promise.all(s),{layerFieldInfo:o,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:i}}var j=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function ae(e,t){return j.test(e)||j.test(t)}var se=async(e,t)=>{try{await n({text:"Preparing field information for vector search results"},t);let a=y(t,"layersAndFieldsRegistry"),{mapView:d}=z(t),{assignedTask:o,userRequest:s}=e.agentExecutionContext,i=ae(o,s),{layerFieldInfo:r,didFetchStatistics:c,fieldStatisticsFetchStatus:l}=await te(e.vectorSearchFieldResults,a,d,i);c?await n({text:"Statistics fetched"},t):await n({text:"Statistics skipped"},t);for(let g of l)await n({text:` - ${g.fieldName} - stats ${g.didFetchStatistics?"fetched":"skipped"}`},t);return await n({text:"Field information prepared"},t),{...e,layerFieldInfo:r}}catch(a){throw await n({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${a instanceof Error?a.message:String(a)}`)}},Q=.7,re=10,ie=async(e,t)=>{try{await n({text:"Similarity search to find fields"},t);let a=y(t,"fieldSearch"),d=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Q,topResults:re,embeddingCache:o}),i=s.map(({layerId:c,results:l})=>{let g=l.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
3
+ `);return`${d.get(c)?.layerItem.name??c}:
4
+ ${g}`}).join(`
5
+ `),r;return s.length>0?r=`Vector search completed. Matching layers and fields with scores:
6
+ ${i}`:r=`No vector search results found for score over ${Q}.`,await n({text:r},t),{...e,vectorSearchFieldResults:s}}catch(a){throw await n({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},oe=.7,ne=async(e,t)=>{try{await n({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=y(t,"layerSearch"),d=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),s=await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:oe,embeddingCache:o}),i=s.map(l=>l.id),r=s.map(({id:l,score:g})=>`${d.get(l)?.layerItem.name??l} (${g.toFixed(2)})`).join(`
7
+ `),c;return i.length>0?c=`Vector search completed. Matching layers with scores:
8
+ ${r}`:c="Vector search completed. No matching layers found.",await n({text:c},t),{...e,vectorSearchLayerIds:i}}catch(a){throw await n({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},le=(e,t)=>V(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),de=()=>new N(M).addNode("requireDataExplorationServices",le).addNode("vectorSearchLayers",ne).addNode("vectorSearchFields",ie).addNode("fieldStatistics",se).addNode("queryAgent",H).addNode("queryTools",O).addNode("summarizeQueryResponseLLM",J).addNode("filterAgent",B).addNode("filterTools",K).addNode("earlyExit",W).addEdge(I,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":S).addEdge("filterTools",S).addEdge("earlyExit",S),ce=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
9
+ The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
10
+ _Example: “Only show stations where Brand is Shell”_
11
+ _Example: “Make Shell stations stand out on the map”_
12
+ _Example: “Gray out all stations that aren’t Shell”_
13
+ This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
14
+ _Example: “How many features are there?”_
15
+ _Example: “What’s the average population?”_
16
+ _Example: “Which values are in the status field?”_
17
+
18
+ This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`,Fe={id:"dataExploration",name:"Data Exploration Agent",description:ce,createGraph:de,workspace:M};return Fe},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues",a,b,c)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{wc as u}from"./IKEF7ZHH.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.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{Bc as u}from"./MU52B4SV.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.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")
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./HOCTVCHH.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as i}from"./4RZPOYZ7.js";import{a as u,b as p,q as f,ta as S}from"./CJIV4KJZ.js";export default $arcgis.t(([,,,,,,{r:x},{A:_,B:h,a:w,m:E,o:y,p:I,q:L,r:v,s:F,t:$,u:C,v:N,w:R,x:T,y:b,z:A},q])=>{var V=.7,z=10,D=async(a,t)=>{try{await i({text:"Similarity search to find fields"},t);let e=y(t,"fieldSearch"),n=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),r=await e.searchFields({text:a.agentExecutionContext.assignedTask,layerIds:a.vectorSearchLayerIds,minScore:V,topResults:z,embeddingCache:o}),m=r.map(({layerId:d,results:c})=>{let g=c.map(s=>` - ${s.name} (${s.score.toFixed(2)})`).join(`
2
+ import c from"./RHM3WKYV.js";import b from"./VAX3IAC3.js";import a from"./HW2FV2RU.js";import{a as i}from"./3X7JLPXS.js";import{Va as S,a as u,b as p,s as f}from"./ON5PWODA.js";export default $arcgis.t(([,,,,,,{r:x},{A:_,B:h,a:w,m:E,o:y,p:I,q:L,r:v,s:F,t:$,u:C,v:N,w:R,x:T,y:b,z:A},q])=>{var V=.7,z=10,D=async(a,t)=>{try{await i({text:"Similarity search to find fields"},t);let e=y(t,"fieldSearch"),n=y(t,"layersAndFieldsRegistry"),o=y(t,"embeddingCache"),r=await e.searchFields({text:a.agentExecutionContext.assignedTask,layerIds:a.vectorSearchLayerIds,minScore:V,topResults:z,embeddingCache:o}),m=r.map(({layerId:d,results:c})=>{let g=c.map(s=>` - ${s.name} (${s.score.toFixed(2)})`).join(`
3
3
  `);return`${n.get(d)?.layerItem.name??d}:
4
4
  ${g}`}).join(`
5
5
  `),l;return r.length>0?l=`Vector search completed. Matching layers and fields with scores:
@@ -0,0 +1,56 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{J as qe,Ka as te,La as nt,Na as W,Oa as Et,Ra as Ie,S as xt,Ta as ge,U as tt,Ua as Oe,Va as At,Z as St,a as ut,b as A,f as $,j as L,k as H,qa as Ae,ta as kt,x as mt,y as ft}from"./ON5PWODA.js";import{$a as gt,$b as he,Ab as bt,I as Ge,Ib as F,Jb as le,Lb as vt,Ob as Se,Qb as Ct,Tb as a,U as T,Ua as Ke,Vb as Qe,Xa as z,Xb as ke,Ya as ie,Z as pt,_a as Ye,ac as K,bb as Xe,c as Je,ca as M,db as wt,dc as ce,fa as Ve,fc as Ee,oa as Q,ob as pe,pb as _e,sa as Ze,sb as xe,sc as et,ta as U,uc as _t,wb as Mt,yb as Tt,yc as ot,za as ht,zb as ee}from"./MU52B4SV.js";import{Dd as B,s as yt}from"./ZEYIBYSF.js";var rt=Symbol.for("AgentMiddleware");function O(e){return{[rt]:!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 Re=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.")}},Pe=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}},we=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(o=>`
3
+ - ${o}`).join("")}.`),this.toolName=e,this.errors=t}},je=class extends Error{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}},ye=class It extends Error{static"~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 mt(t)?t:new It(t,o)}static isInstance(t){return t instanceof Error&&"~brand"in t&&t["~brand"]==="MiddlewareError"}};function Me(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function de(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_getModelInstance"in e&&typeof e._getModelInstance=="function"}var Ot=!0,ho=0,G=class st{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(s){return s??`extract-${++ho}`}if(pe(t)||xe(t)){let s=ke(t);return new st(s,{type:"function",function:{name:n(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},o)}let r;return 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},new st(ke(t),{type:"function",function:r},o)}parse(t){let o=new Qe(this.schema).validate(t);if(!o.valid)throw new we(this.name,o.errors.map(n=>n.error));return t}},oe=class Rt{_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??Ot}else this.schema=t,this.strict=o??Ot}static fromSchema(t,o){return new Rt(ke(t),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 Qe(this.schema).validate(n).valid?n:void 0}catch{}}};function Pt(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 oe))return e;if(e.every(r=>pe(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)&&!pe(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 oe)return[e];let n=go(o);if(pe(e))return n?[oe.fromSchema(e)]:[G.fromSchema(e,t)];if(F(e))return n?[oe.fromSchema(e)]:[G.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return n?[oe.fromSchema(e)]:[G.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function go(e){return!e||!Me(e)||!("profile"in e)||typeof e.profile!="object"||!e.profile?!1:"structuredOutput"in e.profile&&e.profile.structuredOutput===!0}function wo(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 yo(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 Mo(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 To(e){return T.isInstance(e)?e.content:Mo(e)?e.kwargs?.content:e}function Te(e){return()=>{let t=Ae.local(),o=new Map;function n(r,s,i){if(o.has(r))return;let l=typeof i=="string"?JSON.parse(i):i,m,c,u,g,d=new Promise((x,y)=>{m=x,c=y}),f=new Promise(x=>{u=x}),h=new Promise(x=>{g=x});o.set(r,{resolveOutput:m,rejectOutput:c,resolveStatus:u,resolveError:g}),t.push({name:s,callId:r,input:l,output:d,status:f,error:h})}return{__native:!0,init:()=>({toolCalls:t}),process(r){if(!wo(r.params.namespace,e))return!0;if(r.method==="messages"){let s=r.params.data;if(s.event==="content-block-finish"){let i=s.contentBlock??s.content_block;i?.type==="tool_call"&&n(String(i.id??""),String(i.name??""),i.args??i.input)}}if(r.method==="tools"){let s=r.params.data,i=s.tool_call_id;s.event==="tool-started"&&n(i,s.tool_name??"unknown",s.input);let l=i?o.get(i):void 0;if(l){if(s.event==="tool-finished")l.resolveOutput(To(s.output)),l.resolveStatus("finished"),l.resolveError(void 0),o.delete(i);else if(s.event==="tool-error"){let m=s.message??"unknown error";if(yo(m))return!0;l.rejectOutput(new Error(m)),l.resolveStatus("error"),l.resolveError(m),o.delete(i)}}}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 Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(e){return e.join("\0")}function jt(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 Ne(e=[]){return()=>{let t=Ae.local(),o=new Map,n=new Map,r=new Map,s=new Map,i=e.length;function l(d,f){let h=be(d);if(o.has(h))return;let x=(Y(f)&&Y(f.metadata)?f.metadata:void 0)?.lc_agent_name;o.set(h,typeof x=="string"?x:void 0)}function m(d){if(!Y(d))return;let f=d.id;if(typeof f!="string")return;let h=d.input,x;if(Y(h)&&Y(h.tool_call)){let y=h.tool_call.id;typeof y=="string"&&(x=y)}else if(Array.isArray(h)){for(let y of h)if(Y(y)&&typeof y.id=="string"){x=y.id;break}}x!=null&&n.set(f,x)}function c(d){let f=r.get(be(d));if(typeof f=="string"&&f.length>0)return{type:"toolCall",tool_call_id:f};let h=d[d.length-1],x=h.indexOf(":");if(x===-1)return;let y=h.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 u(d){if(d.length!==i+1||!jt(d,e))return;let f=be(d);if(s.has(f))return;let h=o.get(f);if(typeof h!="string"||h.length===0)return;let x=kt(d),y=x.init(),w=Te(d)(),P=w.init(),I=Ne(d)(),j=I.init(),Z,N,b=new Promise((J,ae)=>{Z=J,N=ae});s.set(f,{key:f,path:d,name:h,messages:x,toolCall:w,nested:I,resolveOutput:Z,rejectOutput:N,latestValues:void 0,done:!1}),t.push({name:h,cause:c(d),output:b,messages:y.messages,toolCalls:P.toolCalls,subagents:j.subagents})}function g(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,h=d.params.data,x=d.method==="tasks"&&Y(h)&&"result"in h;d.method==="tools"&&Y(h)&&h.event==="tool-started"&&typeof h.tool_call_id=="string"&&h.tool_call_id.length>0&&r.set(be(f),h.tool_call_id),d.method==="tasks"&&!x&&(l(f,h),m(h),u(f));for(let y of s.values())if(!y.done&&jt(f,y.path)&&(y.messages.process(d),y.toolCall.process(d),y.nested.process(d),be(f)===y.key)){if(d.method==="values"&&Y(h))y.latestValues=h;else if(d.method==="lifecycle"&&Y(h)){let w=h.event;w==="completed"||w==="interrupted"?g(y,{type:"resolve"}):w==="failed"&&g(y,{type:"reject",error:new Error(`Subagent ${y.name} failed`)})}}return!0},finalize(){for(let d of s.values())g(d,{type:"resolve"});t.close()},fail(d){for(let f of s.values())g(f,{type:"reject",error:d});t.fail(d)}}}}var at=Symbol.for("langgraph-zod");at in globalThis||(globalThis[at]=new WeakSet);function Nt(e){let t=globalThis[at];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){let o=this;return{metadata(n){return Oe(o,{jsonSchemaExtra:n})},reducer(n,r){return Oe(o,{default:Se(o),reducer:{schema:r,fn:n}})}}}}),t.add(e))}try{Nt(a.ZodType.prototype),Nt(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 Lt=class extends yt{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let o=t[0];if(o&&!o?.default){let n=Se(e);n!=null&&(o.default=n)}return super.add(e,...t)}},bo=new Lt(ge);function Dt(e=!0,t,o=[]){let n={jumpTo:new nt},r={},s={},i=l=>{if(W.isInstance(l)){for(let[c,u]of Object.entries(l.fields))if(!(c in n)){if(n[c]=u,c.startsWith("_"))continue;te.isInstance(u)?(r[c]=u.inputSchema||u.valueSchema,s[c]=u.valueSchema):(r[c]=u,s[c]=u)}return}let m=le(l);for(let[c,u]of Object.entries(m)){let g=c.startsWith("_");if(!(c in n)){if(_e(u)){let d=ge.get(u);if(d?.reducer){d.reducer.schema?(n[c]=new te(u,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),g||(r[c]=d.reducer.schema,s[c]=u)):(n[c]=new te(u,{reducer:d.reducer.fn}),g||(r[c]=u,s[c]=u));continue}}n[c]=u,g||(r[c]=u,s[c]=u)}}};t&&(W.isInstance(t)||F(t))&&i(t);for(let l of o)l.stateSchema&&(W.isInstance(l.stateSchema)||F(l.stateSchema))&&i(l.stateSchema);return e&&(s.structuredResponse=new nt),{state:new W({messages:Ie,...n}),input:new W({messages:Ie,...r}),output:new W({messages:Ie,...s})}}var it=/<name>(.*?)<\/name>/s,lt=/<content>(.*?)<\/content>/s;function vo(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(xe(e))return ee(e,t);throw new Error(`Invalid state schema type: ${typeof e}`)}function Bt(e){if(!M.isInstance(e)||Ve.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content=="string")return new M({...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 M({...e.lc_kwargs,content:o,name:void 0})}function Ut(e){if(!M.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(it),s=n.text.match(lt);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(it),s=n.text.match(lt);return!r||!s?n:(o=r[1],{...n,text:s[1]})}return n});else{let n=e.content,r=n.match(it),s=n.match(lt);if(!r||!s)return e;o=r[1],t=s[1]}return new M({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:o})}function se(e){return he.isRunnable(e)}function $t(e){return Me(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}var ct=(e,t,o={})=>{if($t(e))return e.bindTools(t,o);if(K.isRunnableBinding(e)&&$t(e.bound)){let n=e.bound.bindTools(t,o);return K.isRunnableBinding(n)?new K({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new K({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Le(e){if(typeof e=="function")return;let t=e;if(ce.isRunnableSequence(t)&&(t=t.steps.find(o=>K.isRunnableBinding(o))||t),!de(t)){if(K.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 Re}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new Re}}function ue(e){return!!(M.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function zt(e){if(e==null)return new U("");if(U.isInstance(e))return e;if(typeof e=="string")return new U({content:[{type:"text",text:e}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof e}`)}async function Ft(e,t,o={}){let n=ct(e,t,o);if(n)return n;if(de(e)){let r=ct(await e._getModelInstance(),t,o);if(r)return r}if(ce.isRunnableSequence(e)){let r=e.steps.findIndex(s=>K.isRunnableBinding(s)||Me(s)||de(s));if(r>=0){let s=ct(e.steps[r],t,o);if(s){let i=e.steps.slice();return i.splice(r,1,s),ce.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function Co(e){if(e.length===0)return;if(e.length===1)return e[0];function t(n,r){return async(s,i)=>n(s,async m=>r(m,i))}let o=e[e.length-1];for(let n=e.length-2;n>=0;n--)o=t(e[n],o);return o}function Wt(e){let t=e.filter(o=>o.wrapToolCall);if(t.length!==0)return Co(t.map(o=>{let n=o.wrapToolCall;return async(s,i)=>{let l=s.state,m=async c=>{let u={...l,...c.state};return i({...c,state:u})};try{let c=await n({...s,state:{messages:l.messages,...o.stateSchema?vo(o.stateSchema,{...l}):{}}},m);if(!T.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 ye.wrap(c,o.name)}}}))}var _o=["tags","metadata","runName","maxConcurrency","recursionLimit","configurable"];function Ht(e){let t={};for(let o of _o){let n=e[o];n!==void 0&&(t[o]=n)}return t}async function Jt(e,t){let o={};for(let n of e){if(!n.stateSchema)continue;let r;if(W.isInstance(n.stateSchema)){let l={};for(let[m,c]of Object.entries(n.stateSchema.fields))te.isInstance(c)?l[m]=c.inputSchema||c.valueSchema:l[m]=c;r=B.object(l)}else if(F(n.stateSchema))r=n.stateSchema;else continue;let s=await Mt(Ct(r,l=>l.startsWith("_")),t);if(s.success){Object.assign(o,s.data);continue}let i=s.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
6
+ `);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
7
+ ${i}
8
+
9
+ To fix this, either:
10
+ 1. Provide default values in your middleware's state schema using .default():
11
+ stateSchema: z.object({
12
+ myField: z.string().default("default value")
13
+ })
14
+
15
+ 2. Or make the fields optional using .optional():
16
+ stateSchema: z.object({
17
+ myField: z.string().optional()
18
+ })
19
+
20
+ 3. Or ensure you pass these values when invoking the agent:
21
+ agent.invoke({
22
+ messages: [...],
23
+ ${s.error.issues[0]?.path.join(".")}: "value"
24
+ })`)}return o}function Gt(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))te.isInstance(s)?o[r]=s.inputSchema||s.valueSchema:o[r]=s}else if(F(e))o=le(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 Vt(e){if(F(e))return vt(e);if(W.isInstance(e)){let t={};for(let[o,n]of Object.entries(e.fields)){let r;te.isInstance(n)?r=n.inputSchema||n.valueSchema:r=n,t[o]=_e(r)?r.optional():B.any().optional()}return B.object(t)}return B.object({})}function V(e){if(e){if(["model_request","tools",A].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return A;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function De(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}var Be={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},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"}},Kt=Object.keys(Be);async function So(e,t){let o;if(t)o=Be[t];else{let n=Object.entries(Be).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 ko(e,t,o={}){let n=t||Eo(e);if(!n)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let r=Be[n];if(!r){let l=Kt.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
25
+
26
+ Supported model providers are: ${l}`)}let{modelProvider:s,...i}=o;return new(await So(r.className,n))({model:e,...i})}function Eo(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 Zt=class $e extends tt{_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 ko(r.model,r.modelProvider,r);for(let[i,l]of Object.entries(this._queuedMethodOperations))i in s&&typeof s[i]=="function"&&(s=await s[i](...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 $e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(t,...o)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[t,...o],new $e({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 i=this._removePrefix(r,this._configPrefix);n[i]=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 K({config:o,bound:new $e({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=ie(o);return n.invoke(t,r)}async stream(t,o){let n=new wt({generator:await(await this._getModelInstance(o)).stream(t,o),config:o});return await n.setup,Xe.fromAsyncGenerator(n)}async batch(t,o,n){return super.batch(t,o,n)}async*transform(t,o){let n=await this._getModelInstance(o),r=ie(o);yield*n.transform(t,r)}async*streamLog(t,o,n){let r=await this._getModelInstance(o),s=ie(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 i=this,l=o;async function*m(){let c=await i._getModelInstance(l),u={...ie(l),version:l.version,...l.encoding!==void 0?{encoding:l.encoding}:{}},g;l.version==="v1"&&l.encoding==="text/event-stream"||l.version==="v1"||l.version==="v2"&&l.encoding,g=c.streamEvents(t,u,n);for await(let d of g)yield d}return Xe.fromAsyncGenerator(m())}let r=this;async function*s(){let i=await r._getModelInstance(o),l=ie(o);yield*i.streamEvents(t,l)}return new xt(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,i]of Object.entries(n))s.startsWith("__pregel_")||(r[s]=i);o={...o,configurable:r}}return JSON.stringify(o)}};async function q(e,t){let{configurableFields:o,configPrefix:n,modelProvider:r,profile:s,...i}={configPrefix:"",...t??{}};if(r===void 0&&e?.includes(":")){let[u,...g]=e.split(":"),d=g.length===0?[u]:[u,g.join(":")];Kt.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 m={...i},c;return l===void 0?c=new Zt({defaultConfig:{...m,model:e,modelProvider:r},configPrefix:n,profile:s}):(e&&(m.model=e),r&&(m.modelProvider=r),c=new Zt({defaultConfig:m,configPrefix:n,configurableFields:l,profile:s})),await c._getModelInstance(),c}var me=class extends he{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=z(this.config,t),n=await Ke.runWithConfig(o,async()=>this.func(e,o));return he.isRunnable(n)&&this.recurse?await Ke.runWithConfig(o,async()=>n.invoke(e,o)):(this.#e=n,n)}};function Yt(e,t){let o,n;if(t==="inline")o=Bt,n=Ut;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function r(s){return s.map(o)}return ce.from([Ee.from(r),e,Ee.from(n)])}function Ao(e){return M.isInstance(e)||H(e)||typeof e=="object"&&e!==null&&"structuredResponse"in e&&"messages"in e}var R="model_request",Xt=class extends me{#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;de(e)?o=await e._getModelInstance():typeof e!="string"&&(o=e);let n=Pt(t,void 0,o);if(n.length!==0)return n.every(r=>r instanceof oe)?{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&&T.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:m,messages:c}=n;return{messages:[...e.messages,...c],structuredResponse:m}}let i=[],l=M.isInstance(n)?n:r;return l&&(l.name=this.name,l.lc_kwargs.name=this.name,this.#c(e,l)?i.push(new L({update:{messages:[new M({content:"Sorry, need more steps to process this request.",name:this.name,id:l.id})]}})):i.push(new L({update:{messages:[l]}}))),H(n)&&!s.includes(n)&&i.push(n),i.push(...s),i}#s(){if(typeof this.#e.model=="string")return q(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,i=null,l=[],m=async d=>{Le(d.model);let f=await this.#r(d.model,d.responseFormat),h=await this.#d(d.model,d,f),x=[...s.text===""?[]:[s],...d.messages],y=De(this.#e.signal,t.signal),w=await gt(h.invoke(x,{...t,signal:y}),y);if(i=w,f?.type==="native"){let j=f.strategy.parse(w);if(j)return{structuredResponse:j,messages:[w]};if(!w.tool_calls||w.tool_calls.length===0)throw new we(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 P=w.tool_calls.filter(j=>j.name in f.tools);if(P.length===0)return w;if(P.length>1)return this.#i(w,P,f);let I=f.tools[P[0].name]?.options?.toolMessageContent;return this.#l(w,P[0],f,I??o.lastMessage)},c=this.#e.wrapModelCallHookMiddleware??[],u=m;for(let d=c.length-1;d>=0;d--){let f=c[d],h=Array.isArray(f)?f[0]:f;if(h.wrapModelCall){let x=u,y=h;u=async w=>{let P=s,I=y.contextSchema?ee(y.contextSchema,r?.context||{}):r?.context,j=Object.freeze({context:I,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal}),Z={...w,state:{...h.stateSchema?ee(Vt(h.stateSchema),e):{},messages:e.messages},runtime:j},N=async b=>{s=P;let J=b.tools??[],ae=new Map(this.#e.toolClasses.filter(se).map(_=>[_.name,_])),Ce=J.filter(_=>se(_)&&!ae.has(_.name)),fe=J.filter(_=>{if(!se(_))return!1;let v=ae.get(_.name);return v!=null&&v!==_});if(Ce.length>0&&!this.#e.middleware?.some(_=>_.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${y.name}": ${Ce.map(_=>_.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(fe.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${y.name}": ${fe.map(_=>_.name).join(", ")}. This is not supported.`);let p=b,C=b.systemPrompt!==s.text,E=b.systemMessage!==s;if(C&&E)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");C&&(s=new U({content:[{type:"text",text:b.systemPrompt}]}),p={...b,systemPrompt:s.text,systemMessage:s}),E&&(s=new U({...b.systemMessage}),p={...b,systemPrompt:s.text,systemMessage:s});let k=await x(p);return H(k)&&i?(l.includes(k)||l.push(k),i):k};if(!y.wrapModelCall)return N(Z);try{let b=await y.wrapModelCall(Z,N);if(!Ao(b))throw new Error(`Invalid response from "wrapModelCall" in middleware "${y.name}": expected AIMessage or Command, got ${typeof b}`);return M.isInstance(b)?i=b:H(b)&&l.push(b),b}catch(b){throw ye.wrap(b,y.name)}}}}s=this.#o;let g={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 u(g),lastAiMessage:i,collectedCommands:l}}#i(e,t,o){let n=new Pe(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 T({tool_call_id:t.id??"",content:JSON.stringify(s),name:t.name}),new M(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(i=>i instanceof Pe))return new L({update:{messages:[t,new T({content:e.message,tool_call_id:s})]},goto:R});if(typeof r=="string")return new L({update:{messages:[t,new T({content:r,tool_call_id:s})]},goto:R});if(typeof r=="function"){let i=await r(e);if(typeof i!="string")throw new Error("Error handler must return a string.");return new L({update:{messages:[t,new T({content:i,tool_call_id:s})]},goto:R})}return new L({update:{messages:[t,new T({content:e.message,tool_call_id:s})]},goto:R})}#c(e,t){let o=M.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&&ue(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(m=>m.tool)],i=t?.toolChoice||(r.length>0?"any":void 0);if(o?.type==="native"){let m=t?.modelSettings?.strict??o?.strategy?.strict??!0,c={name:o.strategy.schema?.name??"extract",description:bt(o.strategy.schema),schema:o.strategy.schema,strict:m};Object.assign(n,{response_format:{type:"json_schema",json_schema:c},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 Ft(e,s,{...n,...t?.modelSettings,tool_choice:i});return this.#e.includeAgentName==="inline"?Yt(l,this.#e.includeAgentName):l}getState(){let e=super.getState();return{messages:[],...e&&!H(e)?e:{}}}};var Qt=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(", ")}].`,D="tools",qt=e=>Array.isArray(e)&&e.every(Ge.isInstance),Io=e=>typeof e=="object"&&e!=null&&"messages"in e&&qt(e.messages),Oo=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function Ro(e,t){return e instanceof je?new T({content:e.message,tool_call_id:t.id,name:t.name}):new T({content:`${e}
27
+ Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var eo=class extends me{tools;trace=!1;signal;handleToolErrors=Ro;wrapToolCall;constructor(e,t){let{name:o,tags:n,handleToolErrors:r,signal:s,wrapToolCall:i}=t??{};super({name:o,tags:n,func:(l,m)=>this.run(l,m)}),this.options=t,this.tools=e,this.handleToolErrors=r??this.handleToolErrors,this.signal=s,this.wrapToolCall=i}#e(e,t,o){if(ft(e)||this.signal?.aborted||o&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(e,t);if(n&&T.isInstance(n))return n;throw e}else if(this.handleToolErrors)return new T({name:t.name,content:`${e}
28
+ Please fix your mistakes.`,tool_call_id:t.id});throw e}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(m=>m.name===e.name),i=async m=>{let{toolCall:c,tool:u}=m,g=u??this.tools.find(f=>f.name===c.name);if(g===void 0){let f=this.tools.map(h=>h.name);return new T({content:Qt(c.name,f),tool_call_id:c.id,name:c.name,status:"error"})}let d=g;try{let f=await d.invoke({...c,type:"tool_call"},{...t,config:t,toolCallId:c.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:De(this.signal,t.signal)});return T.isInstance(f)||H(f)?f:new T({name:d.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:c.id})}catch(f){throw f instanceof pt?new je(f,c):f}},l={toolCall:e,tool:s,state:o,runtime:r};if(this.wrapToolCall)try{return await this.wrapToolCall(l,i)}catch(m){return this.#e(m,e,!0)}if(!s){let m=this.tools.map(c=>c.name);return new T({content:Qt(e.name,m),tool_call_id:e.id,name:e.name,status:"error"})}try{return await i(l)}catch(m){return this.#e(m,e,!1)}}async run(e,t){let o;if(Oo(e)){let{lg_tool_call:s,jumpTo:i,...l}=e;o=[await this.runTool(e.lg_tool_call,t,l)]}else{let s;if(qt(e))s=e;else if(Io(e))s=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(m=>m.getType()==="tool").map(m=>m.tool_call_id)),l;for(let m=s.length-1;m>=0;m-=1){let c=s[m];if(M.isInstance(c)){l=c;break}}if(!M.isInstance(l))throw new Error("ToolNode only accepts AIMessages as input.");o=await Promise.all(l.tool_calls?.filter(m=>m.id==null||!i.has(m.id)).map(m=>this.runTool(m,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(i=>Po(i))?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 Po(e){return e instanceof $}function Ue(e,t){let n=0;if(t&&t.length>0){let r=0;for(let s of t){let i=ot(s)?St(s):s;r+=JSON.stringify(i).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(i=>typeof i=="string"?i:i.type==="text"&&"text"in i?i.text:"").join(""):s="",M.isInstance(r)&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0&&(s+=JSON.stringify(r.tool_calls)),T.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 ne(e){return typeof e=="function"?e:e.hook}var jo=class{},No=class{},re=class extends me{constructor(e){super(e)}async invokeMiddleware(e,t){let o={};if(this.middleware.contextSchema&&F(this.middleware.contextSchema)){let m=le(this.middleware.contextSchema);if(m){let c={},u=t?.context||{};for(let g of Object.keys(m))g in u&&(c[g]=u[g]);o=ee(this.middleware.contextSchema,c)}}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 No,{...r,context:Object.freeze(Object.assign(new jo,o))})));if(!s)return{jumpTo:void 0};let i,l;if(this.name?.startsWith("BeforeAgentNode_")?(i=X(this.middleware.beforeAgent),l="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=X(this.middleware.beforeModel),l="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=X(this.middleware.afterAgent),l="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=X(this.middleware.afterModel),l="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!i?.includes(s.jumpTo)){let m=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:l?`no ${l} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${m}.`)}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:Gt(this.middleware.stateSchema)}}};var to=class extends re{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 ne(this.middleware.beforeAgent)(e,t)}};var oo=class extends re{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 ne(this.middleware.beforeModel)(e,t)}};var no=class extends re{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 ne(this.middleware.afterModel)(e,t)}};var ro=class extends re{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 ne(this.middleware.afterAgent)(e,t)}};var so=class ao{#e;#o="v2";#r;#t;constructor(t,o){if(this.options=t,this.#t=z(o??{},{metadata:{ls_integration:"langchain_create_agent"},configurable:{ls_agent_type:"root"}}),t.name&&(this.#t=z(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"&&Le(t.model);let n=this.options.middleware?.filter(p=>p.tools).flatMap(p=>p.tools)??[],r=[...t.tools??[],...n],s=new Set(r.filter(se).filter(p=>"returnDirect"in p&&p.returnDirect).map(p=>p.name)),i=!!this.options.middleware?.some(p=>p.wrapModelCall),{state:l,input:m,output:c}=Dt(this.options.responseFormat!==void 0||i,this.options.stateSchema,this.options.middleware),u=new At(l,{input:m,output:c,context:this.options.contextSchema}),g=[],d=[],f=[],h=[],x=[];this.#r=new Xt({model:this.options.model,systemMessage:zt(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,E,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 to(v);let S=`${v.name}.before_agent`;g.push({index:p,name:S,allowed:X(v.beforeAgent)}),u.addNode(S,C,C.nodeOptions)}if(v.beforeModel){E=new oo(v);let S=`${v.name}.before_model`;d.push({index:p,name:S,allowed:X(v.beforeModel)}),u.addNode(S,E,E.nodeOptions)}if(v.afterModel){k=new no(v);let S=`${v.name}.after_model`;f.push({index:p,name:S,allowed:X(v.afterModel)}),u.addNode(S,k,k.nodeOptions)}if(v.afterAgent){_=new ro(v);let S=`${v.name}.after_agent`;h.push({index:p,name:S,allowed:X(v.afterAgent)}),u.addNode(S,_,_.nodeOptions)}v.wrapModelCall&&x.push(v)}u.addNode(R,this.#r);let P=w.some(p=>p.wrapToolCall),I=r.filter(se);if(I.length>0||P){let p=new eo(I,{signal:this.options.signal,wrapToolCall:Wt(w)});u.addNode(D,p)}let j;g.length>0?j=g[0].name:d.length>0?j=d[0].name:j=R;let Z=d.length>0?d[0].name:R,N=h.length>0?h[h.length-1].name:A;u.addEdge(ut,j);let b=I.length>0||P;for(let p=0;p<g.length;p++){let C=g[p],E=C.name,k=p===g.length-1?Z: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,..._.map(S=>S===A?N:S)]));u.addConditionalEdges(E,this.#c(I,k,N,b),v)}else u.addEdge(E,k)}for(let p=0;p<d.length;p++){let C=d[p],E=C.name,k=p===d.length-1?R: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,..._]));u.addConditionalEdges(E,this.#d(I,k,b),v)}else u.addEdge(E,k)}let J=f.at(-1);if(f.length>0&&J)u.addEdge(R,J.name);else{let p=this.#s(I,!1,b).map(C=>C===A?N:C);p.length===1?u.addEdge(R,p[0]):u.addConditionalEdges(R,this.#i(N),p)}for(let p=f.length-1;p>0;p--){let C=f[p],E=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,..._]));u.addConditionalEdges(E,this.#n(I,C.allowed,k,b),v)}else u.addEdge(E,k)}if(f.length>0){let p=f[0],C=p.name,E=this.#s(I,!0,b).filter(v=>v!=="tools"||b),k=!!(p.allowed&&p.allowed.length>0),_=E.map(v=>v===A?N:v);u.addConditionalEdges(C,this.#l(I,k,N,b),_)}for(let p=h.length-1;p>0;p--){let C=h[p],E=C.name,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,..._]));u.addConditionalEdges(E,this.#n(I,C.allowed,k,b),v)}else u.addEdge(E,k)}if(h.length>0){let p=h[0],C=p.name;if(p.allowed&&p.allowed.length>0){let E=p.allowed.map(_=>V(_)).filter(_=>_!=="tools"||b),k=Array.from(new Set([A,...E]));u.addConditionalEdges(C,this.#n(I,p.allowed,A,b),k)}else u.addEdge(C,A)}if(b){let p=Z;s.size>0?u.addConditionalEdges(D,this.#a(s,N,p),[p,N]):u.addEdge(D,p)}let ae=(this.options.middleware??[]).flatMap(p=>p.streamTransformers??[]),Ce=[Te([]),Ne([]),...ae,...this.options.streamTransformers??[]];this.#e=u.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description,transformers:Ce});let fe=Ht(this.#t);Object.keys(fe).length>0&&(this.#e=this.#e.withConfig(fe))}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 ao(this.options,z(this.#t,t))}#s(t,o=!1,n=t.length>0){let r=[];return n&&r.push(D),o&&r.push(R),r.push(A),r}#a(t,o,n){return r=>{let s=r.messages,i=s[s.length-1];return T.isInstance(i)&&i.name&&t.has(i.name)?this.options.responseFormat?n:o:n}}#i(t=A){return o=>{let n=o.messages.at(-1);if(!M.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 i=>{let l=i,m=l.messages,c=m.at(-1);if(M.isInstance(c)&&(!c.tool_calls||c.tool_calls.length===0))return n;if(o&&l.jumpTo){let w=V(l.jumpTo);return w===A?n:w==="tools"?r?new $(D,{...i,jumpTo:void 0}):n:new $(R,{...i,jumpTo:void 0})}let u=m.filter(T.isInstance),g=m.filter(M.isInstance).at(-1),d=g?.tool_calls?.filter(w=>!u.some(P=>P.tool_call_id===w.id));if(d&&d.length>0)return this.#o==="v1"?D:d.map(w=>new $(D,{...i,lg_tool_call:w}));let f=g?.tool_calls?.some(w=>w.name.startsWith("extract-"));if(d&&d.length===0&&!f&&s)return R;if(!M.isInstance(c)||!c.tool_calls||c.tool_calls.length===0)return n;let h=c.tool_calls.every(w=>w.name.startsWith("extract-")),x=c.tool_calls.some(w=>!w.name.startsWith("extract-"));if(h||!x)return n;if(this.#o==="v1")return D;let y=c.tool_calls.filter(w=>!w.name.startsWith("extract-"));return y.length===0?n:y.map(w=>new $(D,{...i,lg_tool_call:w}))}}#n(t,o,n,r=t.length>0){let s=new Set(o.map(i=>V(i)));return i=>{let l=i;if(l.jumpTo){let m=V(l.jumpTo);if(m===A&&s.has(A))return A;if(m==="tools"&&s.has("tools"))return r?new $(D,{...i,jumpTo:void 0}):A;if(m==="model_request"&&s.has("model_request"))return new $(R,{...i,jumpTo:void 0})}return n}}#c(t,o,n,r=t.length>0){return s=>{let i=s;if(!i.jumpTo)return o;let l=V(i.jumpTo);return l===A?n:l==="tools"?r?new $(D,{...s,jumpTo:void 0}):n:new $(R,{...s,jumpTo:void 0})}}#d(t,o,n=t.length>0){return r=>{let s=r;if(!s.jumpTo)return o;let i=V(s.jumpTo);return i===A?A:i==="tools"?n?new $(D,{...r,jumpTo:void 0}):A:new $(R,{...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 Jt(this.options.middleware,t),r={...(await this.#e.getState(o).catch(()=>({values:{}}))).values,...t};if(!r)return r;for(let[s,i]of Object.entries(n))s in r||(r[s]=i);return r}async invoke(t,o){let n=z(this.#t,o),r=await this.#u(t,n);return this.#e.invoke(r,n)}async stream(t,o){let n=z(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=z(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,...i}=o??{},l=z(this.#t,i),m=await this.#u(t,l);return await this.#e.streamEvents(m,{...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 Lo(e){return new so(e)}var $o=a.function().args(a.custom()).returns(a.union([a.boolean(),a.promise(a.boolean())])),Bo=a.function().args(a.custom(),a.custom(),a.custom()).returns(a.union([a.string(),a.promise(a.string())])),Uo=["approve","edit","reject"],zo=a.enum(Uo),Fo=a.object({allowedDecisions:a.array(zo),description:a.union([a.string(),Bo]).optional(),argsSchema:a.record(a.any()).optional(),when:$o.optional()}),fa=a.object({interruptOn:a.record(a.union([a.boolean(),Fo])).optional(),descriptionPrefix:a.string().default("Tool execution requires approval")});var ze=`<role>
29
+ Context Extraction Assistant
30
+ </role>
31
+
32
+ <primary_objective>
33
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
34
+ </primary_objective>
35
+
36
+ <objective_information>
37
+ You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
38
+ This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
39
+ </objective_information>
40
+
41
+ <instructions>
42
+ The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
43
+ You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
44
+ </instructions>
45
+
46
+ The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
47
+
48
+ With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
49
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
50
+
51
+ <messages>
52
+ Messages to summarize:
53
+ {messages}
54
+ </messages>`,Wo="Here is a summary of the conversation to date:",Fe=20,Ho=4e3,Jo=15,io=5,Go=a.function().args(a.array(a.custom())).returns(a.union([a.number(),a.promise(a.number())])),ve=a.object({fraction:a.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:a.number().positive("Tokens must be greater than 0").optional(),messages:a.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"}),dt=a.object({fraction:a.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:a.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:a.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"}),lo=a.object({model:a.custom(),trigger:a.union([ve,a.array(ve)]).optional(),keep:dt.optional(),tokenCounter:Go.optional(),summaryPrompt:a.string().default(ze),trimTokensToSummarize:a.number().optional(),summaryPrefix:a.string().optional(),maxTokensBeforeSummary:a.number().optional(),messagesToKeep:a.number().optional()});function We(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 et(e.model);if("modelName"in e&&typeof e.modelName=="string")return et(e.modelName)}function Vo(e){let{data:t,error:o}=Tt(lo,e);if(o)throw new Error(`Invalid summarization middleware options: ${B.prettifyError(o)}`);return O({name:"SummarizationMiddleware",contextSchema:lo.extend({model:a.custom().optional()}),beforeModel:async(n,r)=>{let s=t.trigger,i=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."),(!i||i&&"messages"in i&&i.messages===Fe)&&(i={messages:t.messagesToKeep}));let l=r.context?.trigger!==void 0?r.context.trigger:s,m=r.context?.keep!==void 0?r.context.keep:i??{messages:Fe},c=dt.parse(m),u=[];l===void 0?u=[]:Array.isArray(l)?u=l.map(J=>ve.parse(J)):u=[ve.parse(l)];let g=u.some(J=>"fraction"in J)||"fraction"in c,d=typeof t.model=="string"?await q(t.model):t.model;if(g&&!We(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");let f=r.context?.summaryPrompt===ze?t.summaryPrompt??ze:r.context?.summaryPrompt??t.summaryPrompt??ze,h=r.context.summaryPrefix??t.summaryPrefix??Wo,x=r.context?.trimTokensToSummarize!==void 0?r.context.trimTokensToSummarize:t.trimTokensToSummarize??Ho;Zo(n.messages);let y=r.context?.tokenCounter!==void 0?r.context.tokenCounter:t.tokenCounter??Ue,w=await y(n.messages);if(!await Xo(n.messages,w,u,d))return;let{systemPrompt:P,conversationMessages:I}=Ko(n.messages),j=await Qo(I,c,y,d);if(j<=0)return;let{messagesToSummarize:Z,preservedMessages:N}=Yo(P,I,j),b=new Q({content:`${h}
55
+
56
+ ${await tn(Z,d,f,y,x,r)}`,id:Je(),additional_kwargs:{lc_source:"summarization"}});return{messages:[new Ze({id:Et}),b,...N]}}})}function Zo(e){for(let t of e)t.id||(t.id=Je())}function Ko(e){return e.length>0&&U.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function Yo(e,t,o){let n=t.slice(0,o),r=t.slice(o);return e&&n.unshift(e),{messagesToSummarize:n,preservedMessages:r}}async function Xo(e,t,o,n){if(o.length===0)return!1;for(let r of o){let s=!0,i=!1;if(r.messages!==void 0&&(i=!0,e.length<r.messages&&(s=!1)),r.tokens!==void 0&&(i=!0,t<r.tokens&&(s=!1)),r.fraction!==void 0){i=!0;let l=We(n);typeof l=="number"?t<Math.floor(l*r.fraction)&&(s=!1):s=!1}if(i&&s)return!0}return!1}async function Qo(e,t,o,n){if("tokens"in t||"fraction"in t){let r=await qo(e,t,o,n);return typeof r=="number"?r:co(e,Fe)}return co(e,t.messages??Fe)}async function qo(e,t,o,n){if(e.length===0)return 0;let r;if("fraction"in t&&t.fraction!==void 0){let u=We(n);if(typeof u!="number")return;r=Math.floor(u*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,i=e.length,l=e.length,m=Math.floor(Math.log2(e.length))+1;for(let u=0;u<m&&!(s>=i);u++){let g=Math.floor((s+i)/2);await o(e.slice(g))<=r?(l=g,i=g):s=g+1}if(l===e.length&&(l=s),l>=e.length){if(e.length===1)return 0;l=e.length-1}let c=fo(e,l);if(c<=l)return c;for(let u=l;u>=0;u--)if(uo(e,u))return u;return 0}function co(e,t){if(e.length<=t)return 0;let o=e.length-t,n=fo(e,o);if(n<=o)return n;for(let r=o;r>=0;r--)if(uo(e,r))return r;return 0}function uo(e,t){if(t>=e.length)return!0;if(t<e.length&&M.isInstance(e[t])&&ue(e[t]))return!1;let o=Math.max(0,t-io),n=Math.min(e.length,t+io);for(let r=o;r<n;r++){if(!ue(e[r]))continue;let s=mo(e[r]);if(en(e,r,t,s))return!1}return!0}function mo(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 fo(e,t){if(t>=e.length||!T.isInstance(e[t]))return t;let o=new Set,n=t;for(;n<e.length&&T.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(M.isInstance(s)&&ue(s)){let i=mo(s);for(let l of o)if(i.has(l))return r}}return n}function en(e,t,o,n){for(let r=t+1;r<e.length;r++){let s=e[r];if(T.isInstance(s)&&n.has(s.tool_call_id)&&t<o!=r<o)return!0}return!1}async function tn(e,t,o,n,r,s){if(!e.length)return"No previous conversation history.";let i=await on(e,n,r);if(!i.length)return"Previous conversation was too long to summarize.";let l=ht(i);try{let m=o.replace("{messages}",l),c=z(Ye(s)??{},{metadata:{lc_source:"summarization"}}),u=(await t.invoke(m,c)).content;return typeof u=="string"?u.trim():Array.isArray(u)?u.map(g=>typeof g=="string"?g:typeof g=="object"&&g!==null&&"text"in g?g.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(m){return`Error generating summary: ${m}`}}async function on(e,t,o){if(o===void 0)return e;try{return await qe(e,{maxTokens:o,tokenCounter:async n=>t(n),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-Jo)}}var Da=a.object({model:a.string().or(a.instanceof(_t)).optional(),systemPrompt:a.string().optional(),maxTools:a.number().optional(),alwaysInclude:a.array(a.string()).optional()});var Ha=a.object({applyToInput:a.boolean().optional(),applyToOutput:a.boolean().optional(),applyToToolResults:a.boolean().optional()});var Ka=a.object({rules:a.record(a.string(),a.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var nn=["continue","error","end"],rn="continue";var sn=a.enum(nn).default(rn);a.object({toolName:a.string().optional(),threadLimit:a.number().optional(),runLimit:a.number().optional(),exitBehavior:sn});var si=a.object({threadToolCallCount:a.record(a.string(),a.number()).default({}),runToolCallCount:a.record(a.string(),a.number()).default({})});var an=a.enum(["pending","in_progress","completed"]).describe("Status of the todo"),ln=a.object({content:a.string().describe("Content of the todo item"),status:an}),fi=a.object({todos:a.array(ln).default([])});var cn="end",dn=a.object({threadLimit:a.number().optional(),runLimit:a.number().optional(),exitBehavior:a.enum(["error","end"]).optional()}),un=a.object({threadModelCallCount:a.number().default(0),runModelCallCount:a.number().default(0)}),po=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 mn(e){return O({name:"ModelCallLimitMiddleware",contextSchema:dn,stateSchema:un,beforeModel:{canJumpTo:["end"],hook:(t,o)=>{let n=o.context.exitBehavior??e?.exitBehavior??cn;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,i=t.threadModelCallCount,l=t.runModelCallCount;if(typeof r=="number"&&r<=i){let m=new po({threadLimit:r,threadCount:i});if(n==="end")return{jumpTo:"end",messages:[new M(m.message)]};throw m}if(typeof s=="number"&&s<=l){let m=new po({runLimit:s,runCount:l});if(n==="end")return{jumpTo:"end",messages:[new M(m.message)]};throw m}return t}},afterModel:t=>({runModelCallCount:t.runModelCallCount+1,threadModelCallCount:t.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}var He=a.object({maxRetries:a.number().min(0).default(2),retryOn:a.union([a.function().args(a.instanceof(Error)).returns(a.boolean()),a.array(a.custom())]).default(()=>()=>!0),backoffFactor:a.number().min(0).default(2),initialDelayMs:a.number().min(0).default(1e3),maxDelayMs:a.number().min(0).default(6e4),jitter:a.boolean().default(!0)});var Ri=a.object({onFailure:a.union([a.literal("error"),a.literal("continue"),a.function().args(a.instanceof(Error)).returns(a.string())]).default("continue")}).merge(He);var Ui=a.object({tools:a.array(a.union([a.custom(),a.custom(),a.string()])).optional(),onFailure:a.union([a.literal("error"),a.literal("continue"),a.literal("raise"),a.literal("return_message"),a.function().args(a.instanceof(Error)).returns(a.string())]).default("continue")}).merge(He);var tl=a.object({enableCaching:a.boolean().optional(),ttl:a.enum(["5m","1h"]).optional(),minMessagesToCache:a.number().optional(),unsupportedModelBehavior:a.enum(["ignore","warn","raise"]).optional()});var sl=a.object({enableCaching:a.boolean().optional(),ttl:a.enum(["5m","1h"]).optional(),minMessagesToCache:a.number().optional(),unsupportedModelBehavior:a.enum(["ignore","warn","raise"]).optional()});export{O as a,Lo as b,Vo as c,mn as d};
@@ -1,3 +1,3 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as E}from"./PBTINZTK.js";import b from"./E7TMP4YV.js";import{a as I}from"./434TAA3J.js";import{a as D}from"./E2HENO3T.js";import"./QSA4T3BU.js";import a from"./EBRNMPPO.js";import{a as R}from"./5W7S2RS4.js";import"./NXKKG5TK.js";import{g as $,h as c,k as C,l as P,n as d,t as _,u as y,v as T,x as k,z as A}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([N,{whenOnce:U,watch:B,when:V},j,q,,,H,{property:m,subclass:F},,{b:L}])=>{var G=$`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%);--calcite-panel-content-bottom-space: 0}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%;background:var(--calcite-panel-background-color, var(--calcite-color-background))}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}.interrupt-waiting-message{font-style:italic;color:var(--calcite-color-text-2)}`;function S(o){return o.trim()?E.lexer(o).filter(t=>t.type!=="space").map(t=>E.parser([t])):[]}var f=class{constructor(){this._stableParts=[],this._stableText="",this._rawText=""}push(t){return this._rawText+=t,this._advanceStableBoundary(),this.getParts()}finalize(){let t=this._rawText.slice(this._stableText.length);return t.trim()&&(this._stableParts.push(...S(t)),this._stableText=this._rawText),this._stableParts}getParts(){let t=this._trimIncompleteTail(this._rawText.slice(this._stableText.length)),s=t.trim()?S(t):[];return[...this._stableParts,...s]}reset(){this._stableParts=[],this._stableText="",this._rawText=""}_advanceStableBoundary(){let t=this._rawText.slice(this._stableText.length),s=this._lastSafeBoundary(t);if(s<=0)return;let i=t.slice(0,s);this._stableParts.push(...S(i)),this._stableText+=i}_lastSafeBoundary(t){let s=t.split(`
2
+ import{a as E}from"./PBTINZTK.js";import b from"./SHFSDORL.js";import{a as I}from"./434TAA3J.js";import{a as D}from"./E2HENO3T.js";import"./QSA4T3BU.js";import a from"./HW2FV2RU.js";import{a as R}from"./5W7S2RS4.js";import"./NXKKG5TK.js";import{g as $,h as c,k as C,l as P,n as d,t as _,u as y,v as T,x as k,z as A}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./3X7JLPXS.js";import"./BLKXZEPZ.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([N,{whenOnce:U,watch:B,when:V},j,q,,,H,{property:m,subclass:F},,{b:L}])=>{var G=$`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%);--calcite-panel-content-bottom-space: 0}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%;background:var(--calcite-panel-background-color, var(--calcite-color-background))}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}.interrupt-waiting-message{font-style:italic;color:var(--calcite-color-text-2)}`;function S(o){return o.trim()?E.lexer(o).filter(t=>t.type!=="space").map(t=>E.parser([t])):[]}var f=class{constructor(){this._stableParts=[],this._stableText="",this._rawText=""}push(t){return this._rawText+=t,this._advanceStableBoundary(),this.getParts()}finalize(){let t=this._rawText.slice(this._stableText.length);return t.trim()&&(this._stableParts.push(...S(t)),this._stableText=this._rawText),this._stableParts}getParts(){let t=this._trimIncompleteTail(this._rawText.slice(this._stableText.length)),s=t.trim()?S(t):[];return[...this._stableParts,...s]}reset(){this._stableParts=[],this._stableText="",this._rawText=""}_advanceStableBoundary(){let t=this._rawText.slice(this._stableText.length),s=this._lastSafeBoundary(t);if(s<=0)return;let i=t.slice(0,s);this._stableParts.push(...S(i)),this._stableText+=i}_lastSafeBoundary(t){let s=t.split(`
3
3
  `),i=!1,e=0,n=0;for(let r of s)/^\s*(```|~~~)/u.test(r)&&(i=!i),n+=r.length+1,r.trim()===""&&!i&&(e=n);return e<t.length?e:0}_trimIncompleteTail(t){let s=t.lastIndexOf("<");if(s!==-1&&!t.includes(">",s))return t.slice(0,s);let i=this._earliestUnclosedTag(t);if(i!==-1)return t.slice(0,i);let e=t.lastIndexOf("[");if(e!==-1){let n=t.slice(e);if(!/\[[^\]]*\]\([^)]*\)/u.test(n))return t.slice(0,e)}return t}_earliestUnclosedTag(t){let s=new Set(["br","img","hr","input","meta","link","area","base","col","embed","source","track","wbr"]),i=/<(\/?)([a-zA-Z][\w-]*)\b[^>]*?(\/?)>/gu,e=[];for(let n=i.exec(t);n;n=i.exec(t)){let[,r,a,l]=n,h=a.toLowerCase();if(!(s.has(h)||l==="/"))if(r==="/"){for(let g=e.length-1;g>=0;g--)if(e[g].name===h){e.splice(g);break}}else e.push({name:h,index:n.index})}return e.length?e[0].index:-1}};function W(o){let t=new f;return t.push(o),t.finalize()}var Y=async o=>await new Promise(t=>setTimeout(t,o));async function*Z(o,{chunkSize:t=15,delay:s=50}={}){let i=new f;for(let e=0;e<o.length;e+=t)yield i.push(o.slice(e,e+t)),await Y(s);yield i.finalize()}var J=Object.defineProperty,K=Object.getOwnPropertyDescriptor,u=(o,t,s,i)=>{for(var e=i>1?void 0:i?K(t,s):t,n=o.length-1,r;n>=0;n--)(r=o[n])&&(e=(i?r(t,s,e):r(e))||e);return i&&e&&J(t,s,e),e},O=o=>!o||typeof o!="object"?!1:o.name==="AbortError";async function*z(o,t,s,i,e=!1){if(e){if(i?.aborted){yield{type:"cancelled",log:s,runId:t};return}yield{type:"block-data",blockType:"text",data:{parts:W(o)},runId:t};return}for await(let n of Z(o)){if(i?.aborted){yield{type:"cancelled",log:s,runId:t};return}yield{type:"block-data",blockType:"text",data:{parts:n},runId:t}}}var p=class extends H{constructor(o){super(o),this.view=null,this.streamingDisabled=!1,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await U(()=>!this.view.updating),this._set("orchestrator",await L.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([B(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(o,t){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let s=[],i,e="pending";try{let n=this.orchestrator.ask(o);for await(let r of n)switch(e=r.runId,r.type){case"trace":{this._set("processingStep",r.data.text),s.push(r.data.text);break}case"completed":{this._set("processing",!1),this._set("processingStep","");let a=r.result,l=!!a.content.length,h=!!i?.length;if(!l&&!h){yield{type:"completed",error:"No response received.",log:s,runId:e};return}let g=a.content;if(yield{type:"block-start",blockType:"text",runId:e},yield*z(g,e,s,t,this.streamingDisabled),yield{type:"block-end",blockType:"text",runId:e},h)for(let v of i){if(t?.aborted){yield{type:"cancelled",log:s,runId:e};return}let{type:b,data:w}=v;if(yield{type:"block-start",blockType:b,runId:e},b==="text"){let M=typeof w?.content=="string"?w.content:"";yield*z(M,e,s,t,this.streamingDisabled)}else yield{type:"block-data",blockType:b,data:w,runId:e};yield{type:"block-end",blockType:b,runId:e}}yield{type:"completed",response:g,blocks:i,log:s,runId:e};return}case"ux-suggestion":{let a=r.suggestion;i=i?[...i,a]:[a];break}case"interrupt":{let{kind:a,message:l,metadata:h}=r.interrupt,g=Array.isArray(h)?h.filter(b=>typeof b=="string"):[],v=(()=>{switch(a){case"booleanChoice":return{type:"boolean-choice",message:l,options:g};case"singleSelection":return{type:"single-select",message:l,options:g};case"multipleSelection":return{type:"multi-select",message:l,options:g};case"textInput":return{type:"text-input",message:l};default:return{type:a,message:l,options:g}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:v,runId:e};break}case"cancelled":{yield{type:"cancelled",log:s,runId:e};return}case"error":{if(t?.aborted||O(r.error)){yield{type:"cancelled",log:s,runId:e};return}yield{type:"completed",error:r.error.message,log:s,runId:e};return}default:{console.warn("Unknown event type:",r);break}}}catch(n){if(t?.aborted||O(n)){yield{type:"cancelled",log:s,runId:e};return}console.warn("Error during message processing:",n),yield{type:"completed",error:"An error occurred during message processing.",log:s,runId:"error"};return}finally{this._set("processing",!1)}}cancel(){this.orchestrator?.cancel()}};u([m({readOnly:!0})],p.prototype,"orchestrator",2);u([m()],p.prototype,"agents",2);u([m()],p.prototype,"portal",2);u([m()],p.prototype,"view",2);u([m()],p.prototype,"streamingDisabled",2);u([m({readOnly:!0})],p.prototype,"loading",2);u([m({readOnly:!0})],p.prototype,"processing",2);u([m({readOnly:!0})],p.prototype,"processingStep",2);p=u([F("OrchestratorController")],p);var Q="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",X="Embeddings not found for this web map.",tt="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",x=class extends T{constructor(){super(...arguments),this._messages=D({blocking:!0}),this.#t=_(),this.#l=_(),this.#s=_(),this.#e=null,this.#r=new Map,this.#i=j.getDefault(),this.#a=t=>{t.stopPropagation(),this.cancelInterrupt()},this.#n=t=>{t.stopPropagation();let s=t.detail;this.submitInterrupt(s)},this.#c=t=>{t.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let s=t.detail;this._inputValue="",this.arcgisSubmit.emit(s),this.submitMessage(s)},this.#h=t=>{if(this._canceling=!0,t.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this._orchestratorController?.cancel(),this.#e?.abort(),this.#e=null},this.#g=t=>{t.stopPropagation();let s=t.detail;this.arcgisFeedback.emit(s)},this.#d=t=>{t.stopPropagation();let s=t.detail;this._inputValue=s.prompt,this.arcgisPromptSelect.emit(s)},this.#p=t=>{this.arcgisSlottableRequest.emit(t.detail)},this._orchestratorController=null,this._interrupt=null,this._interruptDetails=[],this._error=null,this._inputValue="",this._isAnswering=!1,this._canceling=!1,this.messages=new N([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.streamingDisabled=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.assistantAvatarEnabled=!1,this.arcgisCancel=d(),this.arcgisError=d(),this.arcgisFeedback=d(),this.arcgisInterrupt=d(),this.arcgisInterruptCancel=d(),this.arcgisInterruptSubmit=d(),this.arcgisPromptSelect=d(),this.arcgisReady=d(),this.arcgisSubmit=d(),this.arcgisSlottableRequest=d({bubbles:!1,composed:!1}),this.arcgisResponse=d()}static{this.properties={_orchestratorController:16,_interrupt:16,_interruptDetails:16,_error:16,_inputValue:16,_isAnswering:16,_signedInUserId:16,_canceling:16,_isSignedIn:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,streamingDisabled:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5,assistantAvatarEnabled:5}}static{this.styles=G}#t;#l;#s;#e;#r;#i;#a;#n;#c;#h;#g;#d;#p;async#o(){try{let t=R(this.el,this.referenceElement);await t?.componentOnReady();let s=[...this.#r.values()];return s.length?(this._orchestratorController?.destroy(),this._orchestratorController=new p({agents:s,portal:this.#i,streamingDisabled:this.streamingDisabled,view:t?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(t){return this._error=t?.message??"Error initializing orchestrator.",P(this)(t),!1}}get _isSignedIn(){return!!this.#i?.user||!!this._signedInUserId}get _user(){return this.#i?.user?.fullName||this.#i?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(t){this.#r.set(t.agent.id,t),this._orchestratorController&&this.#o()}unregister(t){this.#r.delete(t),this._orchestratorController&&this.#o()}async submitMessage(t){let s=t.trim();if(!s||(this.messages.push({id:Date.now().toString(),role:"user",content:s}),!this._orchestratorController))return;this.#e=new AbortController,this._orchestratorController.streamingDisabled=this.streamingDisabled;let i=this._orchestratorController.ask(s,this.#e?.signal);for await(let e of i){let n=e.runId,r=this.messages.at(-1);switch(e.type){case"block-start":{this._isAnswering=!0;let a={type:e.blockType,isPending:!0};if(r?.role==="assistant"&&r.id===n){let l=[...r.blocks??[],a];this.messages.splice(-1,1,{...r,blocks:l})}else this.messages.push({role:"assistant",blocks:[a],id:n,isStreaming:!0,interrupts:this._interruptDetails}),this._interruptDetails=[];break}case"block-data":{if(r?.role!=="assistant"||r?.id!==n)break;let a=[...r.blocks??[]],l=a[a.length-1],{blockType:h,data:g}=e;if(l?.type!==h||!l.isPending)break;h==="text"?a[a.length-1]={...l,data:{...l.data,parts:g?.parts}}:a[a.length-1]={...l,data:{...l.data,...g??{}}},this.messages.splice(-1,1,{...r,blocks:a});break}case"block-end":{if(r?.role!=="assistant"||r?.id!==n)break;let a=[...r.blocks??[]],l=a[a.length-1];if(l?.type!==e.blockType||!l.isPending)break;let h=l;a[a.length-1]={...h,data:{...h.data},isPending:!1},this.messages.splice(-1,1,{...r,blocks:a});break}case"completed":e.error?(this.messages.push({role:"assistant",log:e.log,error:e.error,id:n,interrupts:this._interruptDetails}),this._interruptDetails=[]):r?.role==="assistant"&&r.id===n&&this.messages.splice(-1,1,{...r,content:e.response,blocks:r.blocks?.map(a=>({...a,data:{...a.data},isPending:!1}))??[],isStreaming:!1,log:e.log}),this._isAnswering=!1,this.#e=null,this._canceling=!1;break;case"interrupt":this._interrupt={...e.payload,id:n},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":r?.role==="assistant"&&r.id===n?this.messages.splice(-1,1,{...r,blocks:r.blocks?.filter(a=>a.type==="text"||!a.isPending)??[],isStreaming:!1,log:e.log,error:"(Stopped by user)"}):(this.messages.push({role:"assistant",log:e.log,error:"(Stopped by user)",id:n,interrupts:this._interruptDetails}),this._interruptDetails=[]),this._isAnswering=!1,this.#e=null,this._canceling=!1;break}}}submitInterrupt(t){this.arcgisInterruptSubmit.emit(t),this._interrupt&&(this._interruptDetails=[...this._interruptDetails,{interrupt:this._interrupt,response:t}]),this.orchestrator?.resumeInterrupt(t),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#t.value?.addEventListener("arcgisPromptSelect",this.#d),this.#t.value?.addEventListener("arcgisSubmit",this.#c),this.#t.value?.addEventListener("arcgisCancel",this.#h),this.#t.value?.addEventListener("arcgisFeedback",this.#g);let t=V(()=>!!this._interrupt&&!!this.#s.value,()=>{let i=this.#s.value;i.removeEventListener("arcgisSubmit",this.#n),i.removeEventListener("arcgisCancel",this.#a),i.addEventListener("arcgisSubmit",this.#n,{once:!0}),i.addEventListener("arcgisCancel",this.#a,{once:!0})}),s=this.messages.on("after-add",i=>{let e=i.item;e.role==="assistant"&&(e.error||e.content)&&this.arcgisResponse.emit(e)});return queueMicrotask(()=>{this.#o().then(i=>{i?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{t.remove(),s.remove(),this.#t.value?.removeEventListener("arcgisPromptSelect",this.#d),this.#s.value?.removeEventListener("arcgisSubmit",this.#n),this.#s.value?.removeEventListener("arcgisCancel",this.#a),this.#t.value?.removeEventListener("arcgisSubmit",this.#c),this.#t.value?.removeEventListener("arcgisCancel",this.#h),this.#t.value?.removeEventListener("arcgisFeedback",this.#g),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this._orchestratorController?.cancel(),this.#e?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue="",this._signedInUserId=void 0}_renderEntryMessage(){return this._isSignedIn?this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:c`<calcite-notice open kind=brand closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:c`<slot name=entry-message></slot>`:this._renderSignInNotice()}_renderSignInNotice(){let t=this.#i;return c`<calcite-notice slot=entry-message open kind=brand icon width=full><div slot=message>You need to sign in to use the assistant chat.</div>${t?c`<calcite-link slot=link @click=${async()=>{try{let s=await q.getCredential(`${t.url}/sharing`);this._signedInUserId=s.userId,this._error=null,this.requestUpdate(),await this.#o()?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))}catch(s){this._error=s?.message??"Error signing in.",this.arcgisError.emit(new Error(this._error)),C("error",this,"Error signing in:",{detail:{error:s}})}}} target=_blank title="Sign in to ArcGIS Online">Sign in</calcite-link>`:c`<div slot=link>No portal information available</div>`}</calcite-notice>`}_renderErrorNotice(){return this._error?c`<calcite-notice slot=entry-message open kind=brand icon width=full>${this._error===Q?c`<div slot=message>${X}</div><calcite-link slot=link .href=${tt} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:c`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}render(){return c`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${y(this.#t)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages} .interrupt=${this._interrupt}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(t=>t.role==="assistant"?c`<arcgis-assistant-message .message=${t} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#p} .assistantAvatarEnabled=${this.assistantAvatarEnabled}>${t.blocks?.map((s,i)=>c`<slot name=${I(t.id,i)??k} slot=${I(t.id,i)??k}><arcgis-assistant-message-block .block=${s}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:c`<arcgis-assistant-user-message .message=${t} .user=${this._user}></arcgis-assistant-user-message>`)}</slot>${this._interrupt?c`<div slot=message-loading><div class="interrupt-waiting-message">waiting for user input...</div></div>`:c`<slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep} .assistantAvatarEnabled=${this.assistantAvatarEnabled} .interrupts=${this._interruptDetails}></arcgis-assistant-message-loading></slot>`}</arcgis-assistant-chat></div>${this._interrupt?c`<slot name=interrupt><arcgis-assistant-interrupt slot=content-bottom .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${y(this.#s)}></arcgis-assistant-interrupt></slot>`:this.suggestedPrompts?.length?c`<div class="suggested-prompts-container" slot=content-bottom><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse||this._isAnswering} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} .disabled=${this._canceling||!this._isSignedIn||!!this._interrupt} ${y(this.#l)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse||this._isAnswering?"circle-stop":"send"} @click=${()=>{this.#l.value?.submitMessage()}} round>${this.awaitingResponse||this._isAnswering?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};A("arcgis-assistant",x);return x},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","config","layers/FeatureLayer","core/Accessor","core/accessorSupport/decorators",a,b)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import e from"./PKHQW7QU.js";import d from"./HOCTVCHH.js";import c from"./AFLQZIKS.js";import b from"./EBRNMPPO.js";import{a,c as s}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=a(this,"arcgis-assistant-data-exploration-agent"),this.#i=s(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-data-exploration-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",b,c,d,e)
2
+ import e from"./53TGCGSX.js";import d from"./RHM3WKYV.js";import c from"./VAX3IAC3.js";import b from"./HW2FV2RU.js";import{a,c as s}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./3X7JLPXS.js";import"./BLKXZEPZ.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=a(this,"arcgis-assistant-data-exploration-agent"),this.#i=s(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-data-exploration-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",b,c,d,e)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import k from"./PKHQW7QU.js";import j from"./HBYZSLEZ.js";import i from"./HXOSLGWU.js";import f from"./S27EJSLC.js";import e from"./HOCTVCHH.js";import d from"./TSEQVE2H.js";import c from"./AFLQZIKS.js";import b from"./E7TMP4YV.js";import a from"./EBRNMPPO.js";import"./ADYIXCSG.js";import{a as g,b as h}from"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([C,I,{b:u,c:y,f:w,i:v,j:A,k:S,l:b,m:d,n:p,o:M,p:E,q:P,r:T,s:W,t:x},{a:f,b:V},,O,,L,D,k,R])=>{var U=async e=>{let a=e.allLayers.toArray(),s=[],o=new Map;for(let t of a)if(t instanceof C){let i=(async()=>{let n=await W(t),r=await x(t,n);o.set(t.id,{layerItem:r,fieldRegistry:n})})();s.push(i)}return await Promise.all(s),o},j=async e=>{await I.whenOnce(()=>e.ready);let a=await U(e.map),{layers:s}=await q(a),o={schemaVersion:v,modified:Date.now(),embeddings:{modelProvider:S,model:b,dimensions:A,templates:{layer:d,field:p}},layers:s},t=M.safeParse(o);if(!t.success)throw console.error("Schema Mismatch:",t.error.format()),new Error("Webmap embedding generation failed validation.");return t.data},q=async e=>{let a=[],s=[];for(let[i,{fieldRegistry:n,layerItem:r}]of e.entries()){let l=H(d,{name:r.name,title:r.title,description:r.description});a.push(l);let m={id:i,name:r.name??"",title:r.title,description:r.description,vector:[],fields:[]};for(let[,c]of n.entries()){let N=H(p,{name:c.name,alias:c.alias,description:c.description});a.push(N),m.fields.push({name:c.name,alias:c.alias,description:c.description,vector:[]})}s.push(m)}let o=await f(a),t=0;return{layers:s.map(i=>(i.vector=o[t++],i.fields.forEach(n=>{n.vector=o[t++]}),i))}},H=(e,a)=>e.replace(/\{(\w+)\}/gu,(s,o)=>a[o]??""),z=(e,a)=>{if(e.length!==a.length)throw new Error("Vectors must be the same length");let s=0,o=0,t=0;for(let r=0;r<e.length;++r){let l=e[r],m=a[r];s+=l*m,o+=l*l,t+=m*m}let i=Math.sqrt(o*t);if(i===0)return 0;let n=s/i;return Math.max(-1,Math.min(1,n))},_=E,ee=P,ae=T,te=g,se=f,re=z,oe=O,ie=L,ne=R,me=k,ce=D,le=j,de=()=>u(),pe=()=>y(),fe=async(e,a)=>await h(e,a),ge=async({modelTier:e="default",temperature:a=0,config:s}={})=>await w({modelTier:e,temperature:a,config:s});return{ArcgisKnowledgeAgent:ce,DataExplorationAgent:ne,HelpAgent:me,LayerStylingAgent:ie,NavigationAgent:oe,Orchestrator:V,cosineSimilarity:re,createAgentRuntimeState:de,createAgentRuntimeStateWithSharedState:pe,createChatModel:ge,createWebmapEmbeddings:le,getEmbeddings:se,invokeStructuredPrompt:ee,invokeTextPrompt:_,invokeToolPrompt:ae,sendTraceMessage:te,sendUXSuggestion:fe}},"layers/FeatureLayer","core/reactiveUtils",a,b,c,d,e,f,i,j,k)
2
+ import k from"./53TGCGSX.js";import j from"./Y7KEZCVG.js";import i from"./TKSWXCCJ.js";import f from"./B7W5WD4R.js";import e from"./RHM3WKYV.js";import d from"./32B6ZVYG.js";import c from"./VAX3IAC3.js";import b from"./SHFSDORL.js";import a from"./HW2FV2RU.js";import"./ADYIXCSG.js";import{a as g,b as h}from"./3X7JLPXS.js";import"./BLKXZEPZ.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([C,I,{b:u,c:y,f:w,i:v,j:A,k:S,l:b,m:d,n:p,o:M,p:E,q:P,r:T,s:W,t:x},{a:f,b:V},,O,,L,D,k,R])=>{var U=async e=>{let a=e.allLayers.toArray(),s=[],o=new Map;for(let t of a)if(t instanceof C){let i=(async()=>{let n=await W(t),r=await x(t,n);o.set(t.id,{layerItem:r,fieldRegistry:n})})();s.push(i)}return await Promise.all(s),o},j=async e=>{await I.whenOnce(()=>e.ready);let a=await U(e.map),{layers:s}=await q(a),o={schemaVersion:v,modified:Date.now(),embeddings:{modelProvider:S,model:b,dimensions:A,templates:{layer:d,field:p}},layers:s},t=M.safeParse(o);if(!t.success)throw console.error("Schema Mismatch:",t.error.format()),new Error("Webmap embedding generation failed validation.");return t.data},q=async e=>{let a=[],s=[];for(let[i,{fieldRegistry:n,layerItem:r}]of e.entries()){let l=H(d,{name:r.name,title:r.title,description:r.description});a.push(l);let m={id:i,name:r.name??"",title:r.title,description:r.description,vector:[],fields:[]};for(let[,c]of n.entries()){let N=H(p,{name:c.name,alias:c.alias,description:c.description});a.push(N),m.fields.push({name:c.name,alias:c.alias,description:c.description,vector:[]})}s.push(m)}let o=await f(a),t=0;return{layers:s.map(i=>(i.vector=o[t++],i.fields.forEach(n=>{n.vector=o[t++]}),i))}},H=(e,a)=>e.replace(/\{(\w+)\}/gu,(s,o)=>a[o]??""),z=(e,a)=>{if(e.length!==a.length)throw new Error("Vectors must be the same length");let s=0,o=0,t=0;for(let r=0;r<e.length;++r){let l=e[r],m=a[r];s+=l*m,o+=l*l,t+=m*m}let i=Math.sqrt(o*t);if(i===0)return 0;let n=s/i;return Math.max(-1,Math.min(1,n))},_=E,ee=P,ae=T,te=g,se=f,re=z,oe=O,ie=L,ne=R,me=k,ce=D,le=j,de=()=>u(),pe=()=>y(),fe=async(e,a)=>await h(e,a),ge=async({modelTier:e="default",temperature:a=0,config:s}={})=>await w({modelTier:e,temperature:a,config:s});return{ArcgisKnowledgeAgent:ce,DataExplorationAgent:ne,HelpAgent:me,LayerStylingAgent:ie,NavigationAgent:oe,Orchestrator:V,cosineSimilarity:re,createAgentRuntimeState:de,createAgentRuntimeStateWithSharedState:pe,createChatModel:ge,createWebmapEmbeddings:le,getEmbeddings:se,invokeStructuredPrompt:ee,invokeTextPrompt:_,invokeToolPrompt:ae,sendTraceMessage:te,sendUXSuggestion:fe}},"layers/FeatureLayer","core/reactiveUtils",a,b,c,d,e,f,i,j,k)
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import a from"./WAVKMZA6.js";import{a as C,c as N}from"./CVHJMR5X.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.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"./QA7IATZC.js";import{a as C,c as N}from"./XNITXZDU.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.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
 
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./TSEQVE2H.js";import b from"./AFLQZIKS.js";import a from"./EBRNMPPO.js";import{a as s,c as o}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,a])=>{var t=class extends i{constructor(){super(...arguments),this.agent=a}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=s(this,"arcgis-assistant-navigation-agent"),this.#i=o(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-navigation-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c)
2
+ import c from"./32B6ZVYG.js";import b from"./VAX3IAC3.js";import a from"./HW2FV2RU.js";import{a as s,c as o}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./3X7JLPXS.js";import"./BLKXZEPZ.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,a])=>{var t=class extends i{constructor(){super(...arguments),this.agent=a}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=s(this,"arcgis-assistant-navigation-agent"),this.#i=o(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-navigation-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,b,c)
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import{$ as K,$a as Ha,A as z,Aa as ja,B as A,Ba as ka,C as B,D as C,Da as la,E as D,Ea as ma,F as E,Fa as na,G as F,Ga as oa,H as G,Ha as pa,I as H,Ia as qa,Ja as ra,Ka as sa,La as ta,Ma as ua,Na as va,Oa as wa,Pa as xa,Qa as ya,Ra as za,S as I,Sa as Aa,Va as Ba,Wa as Ca,Xa as Da,Ya as Ea,Za as Fa,_ as J,_a as Ga,a,aa as L,ab as Ia,b,ba as M,bb as Ja,c,ca as N,cb as Ka,d,da as O,db as La,e,ea as P,f,fa as Q,ga as R,h as g,ha as S,i as h,ia as T,j as i,ja as U,k as j,ka as V,l as k,la as W,m as l,ma as X,n as m,na as Y,o as n,oa as Z,p as o,pa as _,q as p,qa as $,r as q,ra as aa,s as r,sa as ba,t as s,ta as ca,u as t,ua as da,v as u,va as ea,w as v,wa as fa,x as w,xa as ga,y as x,ya as ha,z as y,za as ia}from"./ON5PWODA.js";import"./MU52B4SV.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export{S as Annotation,O as AsyncBatchedStore,Q as BaseChannel,L as BaseCheckpointSaver,k as BaseLangGraphError,N as BaseStore,R as BinaryOperatorAggregate,d as COMMAND_SYMBOL,I as ChatModelStreamImpl,i as Command,e as CommandInstance,Ca as CompiledStateGraph,qa as DeltaChannel,ua as DeltaValue,b as END,B as EmptyChannelError,A as EmptyInputError,$ as EventLog,la as Graph,l as GraphBubbleUp,o as GraphDrained,q as GraphInterrupt,m as GraphRecursionError,ha as GraphRunStream,n as GraphValueError,c as INTERRUPT,P as InMemoryStore,C as InvalidUpdateError,M as MemorySaver,Da as MessageGraph,Ia as MessagesAnnotation,Aa as MessagesDeltaValue,za as MessagesValue,Ja as MessagesZodMeta,Ka as MessagesZodState,D as MultipleSubgraphsError,s as NodeError,r as NodeInterrupt,y as NodeTimeoutError,g as Overwrite,u as ParentCommand,wa as REMOVE_ALL_MESSAGES,sa as ReducedValue,F as RemoteException,X as RunControl,a as START,Y as STREAM_EVENTS_V3_MODES,f as Send,Ba as StateGraph,G as StateGraphInputError,va as StateSchema,$ as StreamChannel,ia as SubgraphRunStream,E as UnreachableNodeError,ta as UntrackedValue,ra as UntrackedValueChannel,xa as addMessages,_ as convertToProtocolEvent,K as copyCheckpoint,ja as createGraphRunStream,ba as createLifecycleTransformer,ca as createMessagesTransformer,ea as createSubgraphDiscoveryTransformer,fa as createValuesTransformer,J as emptyCheckpoint,Ga as entrypoint,aa as filterLifecycleEntries,da as filterSubgraphHandles,V as getConfig,W as getCurrentTaskInput,oa as getJsonSchemaFromSchema,Ha as getPreviousState,pa as getSchemaDefaultGetter,T as getStore,H as getSubgraphsSeenSet,U as getWriter,ka as interrupt,Z as isCheckpointEnvelope,j as isCommand,w as isGraphBubbleUp,p as isGraphDrained,x as isGraphInterrupt,h as isInterrupted,ga as isNativeTransformer,t as isNodeError,z as isNodeTimeoutError,v as isParentCommand,na as isSerializableSchema,ma as isStandardSchema,ya as messagesDeltaReducer,xa as messagesStateReducer,Ea as pushMessage,Fa as task,La as writer};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import a from"./WAVKMZA6.js";import"./CVHJMR5X.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([{property:l,subclass:w},{c:p,d:d}])=>{var y=Object.defineProperty,m=Object.getOwnPropertyDescriptor,f=e=>{throw TypeError(e)},h=(e,t,o,n)=>{for(var r=n>1?void 0:n?m(t,o):t,s=e.length-1,g;s>=0;s--)(g=e[s])&&(r=(n?g(t,o,r):g(r))||r);return n&&r&&y(t,o,r),r},k=(e,t,o)=>t.has(e)||f("Cannot "+o),b=(e,t,o)=>t.has(e)?f("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,o),c=(e,t,o)=>(k(e,t,"access private method"),o),a,i,u=class extends d{constructor(e){super(e),b(this,a)}getAgents(){return c(this,a,i).call(this),[this.routerAgent,...Object.values(this.agentsMap)]}buildEdges(e){c(this,a,i).call(this);let t=p(this.routerAgent,0),o=new Map;for(let[n,[r]]of Object.entries(this.agentsMap).entries())o.set(r,p(e[n+1],n+1));return[{from:t,decide:n=>{let r=n[this.routerOutputKey];if(typeof r!="string"||!r)throw new Error("RouterWorkflow decideRoute could not determine next agent from state.");let s=o.get(r);if(!s)throw new Error(`RouterWorkflow decideRoute returned unknown agent: ${r}. Expected one of: ${Object.keys(this.agentsMap).join(", ")||"(none)"}.`);return s}}]}getEntryNode(){return c(this,a,i).call(this),p(this.routerAgent,0)}isTerminalAgent(e,t){return t>0}validateAgents(e){c(this,a,i).call(this),super.validateAgents(e)}};a=new WeakSet;i=function(){if(!Object.keys(this.agentsMap).length)throw new Error("RouterWorkflow requires a non-empty agentsMap.")};h([l()],u.prototype,"agentsMap",2);h([l()],u.prototype,"routerAgent",2);h([l()],u.prototype,"routerOutputKey",2);u=h([w("RouterWorkflow")],u);return u},"core/accessorSupport/decorators",a)
2
+ import a from"./QA7IATZC.js";import"./XNITXZDU.js";import"./ON5PWODA.js";import"./MU52B4SV.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([{property:l,subclass:w},{c:p,d:d}])=>{var y=Object.defineProperty,m=Object.getOwnPropertyDescriptor,f=e=>{throw TypeError(e)},h=(e,t,o,n)=>{for(var r=n>1?void 0:n?m(t,o):t,s=e.length-1,g;s>=0;s--)(g=e[s])&&(r=(n?g(t,o,r):g(r))||r);return n&&r&&y(t,o,r),r},k=(e,t,o)=>t.has(e)||f("Cannot "+o),b=(e,t,o)=>t.has(e)?f("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,o),c=(e,t,o)=>(k(e,t,"access private method"),o),a,i,u=class extends d{constructor(e){super(e),b(this,a)}getAgents(){return c(this,a,i).call(this),[this.routerAgent,...Object.values(this.agentsMap)]}buildEdges(e){c(this,a,i).call(this);let t=p(this.routerAgent,0),o=new Map;for(let[n,[r]]of Object.entries(this.agentsMap).entries())o.set(r,p(e[n+1],n+1));return[{from:t,decide:n=>{let r=n[this.routerOutputKey];if(typeof r!="string"||!r)throw new Error("RouterWorkflow decideRoute could not determine next agent from state.");let s=o.get(r);if(!s)throw new Error(`RouterWorkflow decideRoute returned unknown agent: ${r}. Expected one of: ${Object.keys(this.agentsMap).join(", ")||"(none)"}.`);return s}}]}getEntryNode(){return c(this,a,i).call(this),p(this.routerAgent,0)}isTerminalAgent(e,t){return t>0}validateAgents(e){c(this,a,i).call(this),super.validateAgents(e)}};a=new WeakSet;i=function(){if(!Object.keys(this.agentsMap).length)throw new Error("RouterWorkflow requires a non-empty agentsMap.")};h([l()],u.prototype,"agentsMap",2);h([l()],u.prototype,"routerAgent",2);h([l()],u.prototype,"routerOutputKey",2);u=h([w("RouterWorkflow")],u);return u},"core/accessorSupport/decorators",a)
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as u,b as g,c as S}from"./LODKJRS4.js";import a from"./L77BTGXY.js";import{b as m,c as f}from"./CVHJMR5X.js";import{u as p}from"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([{property:h,subclass:l},{watch:w},d])=>{var v=Object.defineProperty,y=Object.getOwnPropertyDescriptor,o=(t,e,s,r)=>{for(var i=r>1?void 0:r?y(e,s):e,a=t.length-1,c;a>=0;a--)(c=t[a])&&(i=(r?c(e,s,i):c(i))||i);return r&&i&&v(e,s,i),i},n=class extends d{constructor(t){super(t)}initialize(){this.addHandles(w(()=>[this.name,this.description,this.inputSchema,this.outputSchema,this.execute],()=>{this.generate()},{initial:!0,sync:!0}))}getSchemas(){return[this.inputSchema,this.outputSchema].filter(Boolean)}generate(){let t=m(this.getSchemas());this._set("workspace",t);let e=`${this.id}-execute`,s={[e]:this._invokeExecuteNode.bind(this)},r=[{from:e,decide:()=>{}}];this._set("createGraph",()=>f(s,r,t,{agent:this,entryNode:e,middlewares:this.middlewares}))}async _invokeExecuteNode(t,e){try{return this.outputSchema?await this._invokeStructured(t,e):await this._invokeUnstructured(t,e)}catch(s){if(p(s))throw s;let r=s instanceof Error?s.message:String(s);return u({outputMessage:r},"failed",r)}}async _invokeStructured(t,e){if(!this.outputSchema)throw new Error("Output schema is required for structured invocation.");let s=this._validateInputState(t),r=await this.execute(s,e);if(typeof r=="string")throw new Error("Expected execute function to return an object matching the output schema, but received a string.");return g(r,this.outputSchema,t.agentExecutionContext.messages)}async _invokeUnstructured(t,e){let s=this._validateInputState(t),r=await this.execute(s,e),i=typeof r=="string"?r:JSON.stringify(r),a=i.trim()||"FunctionAgent completed.";return u({outputMessage:i},"success",a)}_validateInputState(t){if(!this.inputSchema)return t;let e=this.inputSchema.safeParse(S(t,this.inputSchema));if(!e.success)throw new Error(`FunctionAgent input schema validation failed: ${e.error.message}`);return{...t,...e.data}}};o([h()],n.prototype,"inputSchema",2);o([h()],n.prototype,"outputSchema",2);o([h()],n.prototype,"execute",2);n=o([l("FunctionAgent")],n);return n},"core/accessorSupport/decorators","core/reactiveUtils",a)
2
+ import{a as u,b as g,c as S}from"./PA5W5PWE.js";import a from"./3RPE2QMJ.js";import{b as m,c as f}from"./XNITXZDU.js";import{y as p}from"./ON5PWODA.js";import"./MU52B4SV.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([{property:h,subclass:l},{watch:w},d])=>{var v=Object.defineProperty,y=Object.getOwnPropertyDescriptor,o=(t,e,s,r)=>{for(var i=r>1?void 0:r?y(e,s):e,a=t.length-1,c;a>=0;a--)(c=t[a])&&(i=(r?c(e,s,i):c(i))||i);return r&&i&&v(e,s,i),i},n=class extends d{constructor(t){super(t)}initialize(){this.addHandles(w(()=>[this.name,this.description,this.inputSchema,this.outputSchema,this.execute],()=>{this.generate()},{initial:!0,sync:!0}))}getSchemas(){return[this.inputSchema,this.outputSchema].filter(Boolean)}generate(){let t=m(this.getSchemas());this._set("workspace",t);let e=`${this.id}-execute`,s={[e]:this._invokeExecuteNode.bind(this)},r=[{from:e,decide:()=>{}}];this._set("createGraph",()=>f(s,r,t,{agent:this,entryNode:e,middlewares:this.middlewares}))}async _invokeExecuteNode(t,e){try{return this.outputSchema?await this._invokeStructured(t,e):await this._invokeUnstructured(t,e)}catch(s){if(p(s))throw s;let r=s instanceof Error?s.message:String(s);return u({outputMessage:r},"failed",r)}}async _invokeStructured(t,e){if(!this.outputSchema)throw new Error("Output schema is required for structured invocation.");let s=this._validateInputState(t),r=await this.execute(s,e);if(typeof r=="string")throw new Error("Expected execute function to return an object matching the output schema, but received a string.");return g(r,this.outputSchema,t.agentExecutionContext.messages)}async _invokeUnstructured(t,e){let s=this._validateInputState(t),r=await this.execute(s,e),i=typeof r=="string"?r:JSON.stringify(r),a=i.trim()||"FunctionAgent completed.";return u({outputMessage:i},"success",a)}_validateInputState(t){if(!this.inputSchema)return t;let e=this.inputSchema.safeParse(S(t,this.inputSchema));if(!e.success)throw new Error(`FunctionAgent input schema validation failed: ${e.error.message}`);return{...t,...e.data}}};o([h()],n.prototype,"inputSchema",2);o([h()],n.prototype,"outputSchema",2);o([h()],n.prototype,"execute",2);n=o([l("FunctionAgent")],n);return n},"core/accessorSupport/decorators","core/reactiveUtils",a)