@arcgis/portal-components 5.2.0-next.59 → 5.2.0-next.60

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 (80) hide show
  1. package/dist/cdn/23EOLRF6.js +2 -0
  2. package/dist/cdn/25BWGJFT.js +2 -0
  3. package/dist/cdn/{SUBBPVRW.js → 2YEGKG66.js} +1 -1
  4. package/dist/cdn/{LDRIWXTO.js → 3527GI5O.js} +1 -1
  5. package/dist/cdn/{RKT7WCDH.js → 3LBJM7GA.js} +1 -1
  6. package/dist/cdn/3Y33UPZ6.js +2 -0
  7. package/dist/cdn/{YR5FO6PO.js → 44XITKIX.js} +1 -1
  8. package/dist/cdn/{JCIDQZ6X.js → 456GBBRQ.js} +1 -1
  9. package/dist/cdn/{VMNR4TQZ.js → 52B4FWCM.js} +1 -1
  10. package/dist/cdn/{CYEC77HO.js → 5VMPZXL3.js} +1 -1
  11. package/dist/cdn/{3WH3ENZP.js → 6LMJGR6F.js} +1 -1
  12. package/dist/cdn/{3VDVNPZ7.js → 744FUP4K.js} +1 -1
  13. package/dist/cdn/{E6STCC7O.js → 7NVVHX75.js} +1 -1
  14. package/dist/cdn/{OFDH6CTA.js → 7ZXEX3LI.js} +1 -1
  15. package/dist/cdn/{K7NCYRPX.js → AEZFDUSX.js} +1 -1
  16. package/dist/cdn/{UCCRV44E.js → AT2DLVEF.js} +1 -1
  17. package/dist/cdn/{6ROVXNLV.js → CG6FLLXZ.js} +1 -1
  18. package/dist/cdn/{SJGVHRK2.js → DUKSWZKG.js} +1 -1
  19. package/dist/cdn/{ILBX6R25.js → E6MGDW3D.js} +1 -1
  20. package/dist/cdn/{OTC37DGK.js → EB4XGKGD.js} +1 -1
  21. package/dist/cdn/EE7XFMJG.js +2 -0
  22. package/dist/cdn/{XSUXR4WJ.js → F3PB42AG.js} +1 -1
  23. package/dist/cdn/{NADYAODN.js → FF24VDOG.js} +1 -1
  24. package/dist/cdn/GBW3NV7Y.js +2 -0
  25. package/dist/cdn/HEA66RTI.js +2 -0
  26. package/dist/cdn/{UXLENIDB.js → IQFYKVRG.js} +1 -1
  27. package/dist/cdn/{RL7X3ACG.js → JPHGWARN.js} +1 -1
  28. package/dist/cdn/{CU34VHCE.js → JUNNQTQU.js} +1 -1
  29. package/dist/cdn/{OK75ZZ2M.js → KTTTBLZ6.js} +1 -1
  30. package/dist/cdn/M7T6DKL2.js +2 -0
  31. package/dist/cdn/MNU537SB.js +2 -0
  32. package/dist/cdn/{CF7ZMRAH.js → NITKS6KJ.js} +1 -1
  33. package/dist/cdn/{IVATGXII.js → NMAP3FYP.js} +1 -1
  34. package/dist/cdn/{3MIY7CNH.js → NYFFDBSL.js} +1 -1
  35. package/dist/cdn/{X6N7Y4IA.js → OECTWB22.js} +1 -1
  36. package/dist/cdn/{IZTK4QQL.js → PMCTFA5D.js} +1 -1
  37. package/dist/cdn/PP7GTURX.js +2 -0
  38. package/dist/cdn/{OYX64HG5.js → Q7SDLUZ6.js} +1 -1
  39. package/dist/cdn/{ZP6MVFXR.js → QQ432AB6.js} +1 -1
  40. package/dist/cdn/{FPYIRCJO.js → R2CAXYXG.js} +59 -59
  41. package/dist/cdn/{BUKOHPY6.js → SKUPHVNO.js} +1 -1
  42. package/dist/cdn/{PBH3JZCG.js → SVRIKNKJ.js} +1 -1
  43. package/dist/cdn/{O6QBY4ST.js → SWAVECPM.js} +1 -1
  44. package/dist/cdn/{T7GD53BL.js → TAB5C3RK.js} +1 -1
  45. package/dist/cdn/{HHA5STNZ.js → THRK2DGY.js} +1 -1
  46. package/dist/cdn/{XQJNAQVO.js → TNLGQ7HL.js} +1 -1
  47. package/dist/cdn/{P6P7SKFX.js → U5B2LAPJ.js} +1 -1
  48. package/dist/cdn/{B36VBHAI.js → UL2NWFFH.js} +1 -1
  49. package/dist/cdn/{HV3BRK66.js → V4IAC7WR.js} +1 -1
  50. package/dist/cdn/{IFYHXRHA.js → VD6VGWCQ.js} +1 -1
  51. package/dist/cdn/{S2JZ5KTI.js → VLHHC25R.js} +1 -1
  52. package/dist/cdn/{IF2LNWBA.js → VRCB4BN4.js} +1 -1
  53. package/dist/cdn/{IOVOCADO.js → WWMB4NWC.js} +1 -1
  54. package/dist/cdn/{FDQ3EJUR.js → XCJPHHX2.js} +1 -1
  55. package/dist/cdn/{UPSYDUD6.js → XHFAXT2P.js} +1 -1
  56. package/dist/cdn/XMUR4HRH.js +2 -0
  57. package/dist/cdn/XX4U6IRN.js +2 -0
  58. package/dist/cdn/Y3RUZTB3.js +2 -0
  59. package/dist/cdn/{I5GDSNYE.js → Y7FCEDRU.js} +1 -1
  60. package/dist/cdn/{Z2ZW4FY2.js → YIU7GBUN.js} +1 -1
  61. package/dist/cdn/{EYTAC4Z4.js → ZOEF7HBV.js} +1 -1
  62. package/dist/cdn/index.js +1 -1
  63. package/dist/components/arcgis-portal-ai-assistant/customElement.js +43 -56
  64. package/dist/docs/api.json +1 -1
  65. package/dist/docs/docs.json +1 -1
  66. package/dist/docs/web-types.json +1 -1
  67. package/package.json +4 -4
  68. package/dist/cdn/2H7Y7RJV.js +0 -2
  69. package/dist/cdn/32FQ7WJE.js +0 -2
  70. package/dist/cdn/3Q3EP3BN.js +0 -2
  71. package/dist/cdn/5CT433EX.js +0 -2
  72. package/dist/cdn/7JQ6D224.js +0 -2
  73. package/dist/cdn/GLDJPWRZ.js +0 -2
  74. package/dist/cdn/IRK4UW2F.js +0 -2
  75. package/dist/cdn/ODJRHB2N.js +0 -2
  76. package/dist/cdn/RZPKVJMB.js +0 -2
  77. package/dist/cdn/TFFZ425X.js +0 -2
  78. package/dist/cdn/UUSJCAH5.js +0 -2
  79. package/dist/cdn/WBNJYBQD.js +0 -2
  80. /package/dist/cdn/{STZRXY35.js → TSTTPCWU.js} +0 -0
@@ -1,12 +1,12 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import c from"./55FL7WQV.js";import b from"./5KDFY5KE.js";import{a as ml,c as fl,e as hl,f as gl,g as yl}from"./UZCHLKLO.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import a from"./DALGPO36.js";import{a as Gn,b as Ui,d as qi}from"./2GBRZSEC.js";import{a as Bi}from"./OFDH6CTA.js";import"./BUKOHPY6.js";import"./XQJNAQVO.js";import{K as Bn,L as Kn,M as Di,S as Fi,h as Ni,j as pr,n as zi,w as ji,z as Li}from"./STZRXY35.js";import{$ as Ji,Aa as Ko,Ba as Go,Bb as Wo,Ca as al,Cb as Vo,Da as fr,Db as pe,Ea as hr,Fa as v,Ga as $,Ha as aa,J as Gi,K as De,L as Wi,M as No,N as Xs,O as ea,P as zo,Q as Wn,R as U,Ra as O,S as ta,T as D,U as et,V as tt,W as jo,X as Vi,Y as Hi,Z as ra,_ as Lo,a as de,aa as Zi,b as B,ba as Vn,ca as Do,da as Qi,ea as Yi,fa as Xi,g as Ki,ga as Fo,ha as el,ia as Tt,j as Le,ja as na,k as vt,ka as Uo,kb as il,la as N,ma as A,na as St,oa as rt,pa as qo,qa as tl,ra as rl,s as Ro,sa as Bo,ta as oa,ua as mr,va as sa,wa as nl,xa as ol,xb as Hn,y as $o,za as sl}from"./IZOGASBD.js";import"./UZLQALHY.js";export default $arcgis.t(([MK,$K,ad,qh,Bh,ng,FK,qK,YV,kb,wd,ur,fi,Sd,,bd,ig,{addressToLocations:lg},ug,cg,kd,{createRenderer:dg},{getSchemesByTag:pg,getSchemes:mg},{getBackgroundColorTheme:xd},{createAgeRenderer:fg,createContinuousRenderer:hg},{getSchemesByTag:vi},{createContinuousRenderer:gg},{createRenderer:yg},{getSchemesByTag:_g},{createRenderer:wg},{getSchemesByTag:bg},{createRenderer:xg},{getSchemesByTag:Ag},{createRenderer:Ig},{getSchemesByTag:vg},{createAgeRenderer:Tg,createContinuousRenderer:Sg},{createRenderer:kg},{getSchemesByTag:Cg},Eg,Cd,Ed,{formatDateOnly:Pg,convertDateFormatToIntlOptions:Ds,formatTimeOnly:Og,formatDate:Ad},Mg,Rg,$g,Ng,zg,Pd,,{fetchKnowledgeGraph:Id,executeQueryStreaming:jg,executeSearchStreaming:Lg},Dg,{getBindParametersFromCypherQuery:Fg},,,,,,,,,,,,,,,,,,,,,,,,,YW,eV,,,,,,,,,,,,,Cb,Bd,,{a:dl,b:pl},{a:ll,b:ul,c:cl}])=>{var c=v;async function ia(t,e,r){if(r===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 c from"./55FL7WQV.js";import b from"./5KDFY5KE.js";import{a as ml,c as fl,e as hl,f as gl,g as yl}from"./UZCHLKLO.js";import"./VMQIDO4Z.js";import"./QS3GXAIH.js";import a from"./DALGPO36.js";import{a as Gn,b as Ui,d as qi}from"./2GBRZSEC.js";import{a as Bi}from"./7ZXEX3LI.js";import"./SKUPHVNO.js";import"./TNLGQ7HL.js";import{K as Bn,L as Kn,M as Di,S as Fi,h as Ni,j as pr,n as zi,w as ji,z as Li}from"./TSTTPCWU.js";import{$ as Ji,Aa as Ko,Ba as Go,Bb as Wo,Ca as al,Cb as Vo,Da as fr,Db as pe,Ea as hr,Fa as v,Ga as $,Ha as aa,J as Gi,K as De,L as Wi,M as No,N as Xs,O as ea,P as zo,Q as Wn,R as U,Ra as O,S as ta,T as D,U as et,V as tt,W as jo,X as Vi,Y as Hi,Z as ra,_ as Lo,a as de,aa as Zi,b as B,ba as Vn,ca as Do,da as Qi,ea as Yi,fa as Xi,g as Ki,ga as Fo,ha as el,ia as Tt,j as Le,ja as na,k as vt,ka as Uo,kb as il,la as N,ma as A,na as St,oa as rt,pa as qo,qa as tl,ra as rl,s as Ro,sa as Bo,ta as oa,ua as mr,va as sa,wa as nl,xa as ol,xb as Hn,y as $o,za as sl}from"./IZOGASBD.js";import"./UZLQALHY.js";export default $arcgis.t(([$K,zK,ad,qh,Bh,Kh,og,qK,KK,eH,Cb,wd,ur,bd,fi,Sd,,lg,{addressToLocations:ug},cg,dg,kd,{createRenderer:pg},{getSchemesByTag:mg,getSchemes:fg},{getBackgroundColorTheme:xd},{createAgeRenderer:hg,createContinuousRenderer:gg},{getSchemesByTag:vi},{createContinuousRenderer:yg},{createRenderer:_g},{getSchemesByTag:wg},{createRenderer:bg},{getSchemesByTag:xg},{createRenderer:Ag},{getSchemesByTag:Ig},{createRenderer:vg},{getSchemesByTag:Tg},{createAgeRenderer:Sg,createContinuousRenderer:kg},{createRenderer:Cg},{getSchemesByTag:Eg},Pg,Cd,Ed,{formatDateOnly:Og,convertDateFormatToIntlOptions:Ds,formatTimeOnly:Mg,formatDate:Ad},Rg,$g,Ng,zg,jg,Pd,,{fetchKnowledgeGraph:Id,executeQueryStreaming:Lg,executeSearchStreaming:Dg},Fg,{getBindParametersFromCypherQuery:Ug},,,,,,,,,,,,,,,,,,,,,,,,,eV,rV,,,,,,,,,,,,,Eb,Bd,,{a:dl,b:pl},{a:ll,b:ul,c:cl}])=>{var c=v;async function ia(t,e,r){if(r===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
 
6
6
  Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
7
7
  |`,`
8
8
  \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
9
- `].join(" "));let n=await Zi(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var H=async(t,e)=>{await ia("trace_message",t,e)},me=async(t,e)=>{await ia("graph_ux_suggestion",t,e)};var pp={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"}},cA=Object.keys(pp);var ca=Symbol.for("langgraph-zod");ca in globalThis||(globalThis[ca]=new WeakSet);function bl(t){let e=globalThis[ca];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return Vo(r,{jsonSchemaExtra:n})},reducer(n,o){return Vo(r,{default:Uo(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{bl(A.ZodType.prototype),bl(v.ZodType.prototype)}catch(t){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:t})}var xl=class extends Yi{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=Uo(t);n!=null&&(r.default=n)}return super.add(t,...e)}},gp=new xl(Wo);var Mp=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Rp=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),$p=["approve","edit","reject"],Np=A.enum($p),zp=A.object({allowedDecisions:A.array(Np),description:A.union([A.string(),Rp]).optional(),argsSchema:A.record(A.any()).optional(),when:Mp.optional()}),wT=A.object({interruptOn:A.record(A.union([A.boolean(),zp])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var Dp=`<role>
9
+ `].join(" "));let n=await Zi(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var H=async(t,e)=>{await ia("trace_message",t,e)},me=async(t,e)=>{await ia("graph_ux_suggestion",t,e)};var pp={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"}},dA=Object.keys(pp);var ca=Symbol.for("langgraph-zod");ca in globalThis||(globalThis[ca]=new WeakSet);function bl(t){let e=globalThis[ca];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return Vo(r,{jsonSchemaExtra:n})},reducer(n,o){return Vo(r,{default:Uo(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{bl(A.ZodType.prototype),bl(v.ZodType.prototype)}catch(t){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:t})}var xl=class extends Yi{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=Uo(t);n!=null&&(r.default=n)}return super.add(t,...e)}},gp=new xl(Wo);var Mp=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Rp=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),$p=["approve","edit","reject"],Np=A.enum($p),zp=A.object({allowedDecisions:A.array(Np),description:A.union([A.string(),Rp]).optional(),argsSchema:A.record(A.any()).optional(),when:Mp.optional()}),bT=A.object({interruptOn:A.record(A.union([A.boolean(),zp])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var Dp=`<role>
10
10
  Context Extraction Assistant
11
11
  </role>
12
12
 
@@ -32,7 +32,7 @@ Respond ONLY with the extracted context. Do not include any additional informati
32
32
  <messages>
33
33
  Messages to summarize:
34
34
  {messages}
35
- </messages>`;var Fp=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),ga=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(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Pl=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(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),jT=A.object({model:A.custom(),trigger:A.union([ga,A.array(ga)]).optional(),keep:Pl.optional(),tokenCounter:Fp.optional(),summaryPrompt:A.string().default(Dp),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var HT=A.object({model:A.string().or(A.instanceof(tl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var tS=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var aS=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Up=["continue","error","end"],qp="continue";var Bp=A.enum(Up).default(qp);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Bp});var yS=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Kp=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Gp=A.object({content:A.string().describe("Content of the todo item"),status:Kp}),TS=A.object({todos:A.array(Gp).default([])});var PS=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),OS=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var Ho=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 GS=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(Ho);var XS=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(Ho);var fk=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var _k=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function Jn(t,e){return t.lc_error_code=e,t.message=`${t.message}
35
+ </messages>`;var Fp=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),ga=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(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Pl=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(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),LT=A.object({model:A.custom(),trigger:A.union([ga,A.array(ga)]).optional(),keep:Pl.optional(),tokenCounter:Fp.optional(),summaryPrompt:A.string().default(Dp),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var JT=A.object({model:A.string().or(A.instanceof(tl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var rS=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var iS=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Up=["continue","error","end"],qp="continue";var Bp=A.enum(Up).default(qp);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Bp});var _S=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Kp=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Gp=A.object({content:A.string().describe("Content of the todo item"),status:Kp}),SS=A.object({todos:A.array(Gp).default([])});var OS=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),MS=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var Ho=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 WS=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(Ho);var ek=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(Ho);var hk=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var wk=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function Jn(t,e){return t.lc_error_code=e,t.message=`${t.message}
36
36
 
37
37
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
38
38
  `,t}function C(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function _(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var ya=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return ya=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Zn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Qn=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var k=class extends Error{},G=class t extends k{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new ot({message:n,cause:Qn(r)});let s=r?.error;return e===400?new yr(e,s,n,o):e===401?new _r(e,s,n,o):e===403?new wr(e,s,n,o):e===404?new br(e,s,n,o):e===409?new xr(e,s,n,o):e===422?new Ar(e,s,n,o):e===429?new Ir(e,s,n,o):e>=500?new vr(e,s,n,o):new t(e,s,n,o)}},W=class extends G{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ot=class extends G{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ee=class extends ot{constructor({message:e}={}){super({message:e??"Request timed out."})}},yr=class extends G{},_r=class extends G{},wr=class extends G{},br=class extends G{},xr=class extends G{},Ar=class extends G{},Ir=class extends G{},vr=class extends G{},Tr=class extends k{constructor(){super("Could not parse response content as the length limit was reached")}},Sr=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Pe=class extends Error{constructor(e){super(e)}},Ct=class extends G{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},Yn=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var tm=/^[a-z][a-z0-9+.-]*:/i,Ol=t=>tm.test(t),ie=t=>(ie=Array.isArray,ie(t)),_a=ie;function Jo(t){return typeof t!="object"?{}:t??{}}function wa(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ml(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Xn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Rl=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e};var $l=t=>{try{return JSON.parse(t)}catch{return}};var Oe=t=>new Promise(e=>setTimeout(e,t));var st="6.45.0";var Ll=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function rm(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var nm=()=>{let t=rm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"X-Stainless-OS":zl(Deno.build.os),"X-Stainless-Arch":Nl(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"X-Stainless-OS":zl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=om();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":st,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function om(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var Nl=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",zl=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),jl,Dl=()=>jl??(jl=nm());function Zo(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ba(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Qo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return ba({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function xa(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Aa(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Ul=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ia="RFC3986",va=t=>String(t),Ta={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:va},ql="RFC1738";var Yo=(t,e)=>(Yo=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Yo(t,e)),Me=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Sa=1024,Bl=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=Sa){let u=s.length>=Sa?s.slice(i,i+Sa):s,l=[];for(let d=0;d<u.length;++d){let m=u.charCodeAt(d);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===ql&&(m===40||m===41)){l[l.length]=u.charAt(d);continue}if(m<128){l[l.length]=Me[m];continue}if(m<2048){l[l.length]=Me[192|m>>6]+Me[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Me[224|m>>12]+Me[128|m>>6&63]+Me[128|m&63];continue}d+=1,m=65536+((m&1023)<<10|u.charCodeAt(d)&1023),l[l.length]=Me[240|m>>18]+Me[128|m>>12&63]+Me[128|m>>6&63]+Me[128|m&63]}a+=l.join("")}return a};function Kl(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ka(t,e){if(ie(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Wl={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Vl=function(t,e){Array.prototype.push.apply(t,ie(e)?e:[e])},Gl,X={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Bl,encodeValuesOnly:!1,format:Ia,formatter:va,indices:!1,serializeDate(t){return(Gl??(Gl=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function am(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Ca={};function Hl(t,e,r,n,o,s,a,i,u,l,d,m,f,I,w,b,y,h){let x=t,S=h,E=0,F=!1;for(;(S=S.get(Ca))!==void 0&&!F;){let Z=S.get(t);if(E+=1,typeof Z<"u"){if(Z===E)throw new RangeError("Cyclic object value");F=!0}typeof S.get(Ca)>"u"&&(E=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&ie(x)&&(x=ka(x,function(Z){return Z instanceof Date?f?.(Z):Z})),x===null){if(s)return u&&!b?u(e,X.encoder,y,"key",I):e;x=""}if(am(x)||Kl(x)){if(u){let Z=b?e:u(e,X.encoder,y,"key",I);return[w?.(Z)+"="+w?.(u(x,X.encoder,y,"value",I))]}return[w?.(e)+"="+w?.(String(x))]}let q=[];if(typeof x>"u")return q;let K;if(r==="comma"&&ie(x))b&&u&&(x=ka(x,u)),K=[{value:x.length>0?x.join(",")||null:void 0}];else if(ie(l))K=l;else{let Z=Object.keys(x);K=d?Z.sort(d):Z}let V=i?String(e).replace(/\./g,"%2E"):String(e),ae=n&&ie(x)&&x.length===1?V+"[]":V;if(o&&ie(x)&&x.length===0)return ae+"[]";for(let Z=0;Z<K.length;++Z){let Y=K[Z],Ri=typeof Y=="object"&&typeof Y.value<"u"?Y.value:x[Y];if(a&&Ri===null)continue;let Ys=m&&i?Y.replace(/\./g,"%2E"):Y,cp=ie(x)?typeof r=="function"?r(ae,Ys):ae:ae+(m?"."+Ys:"["+Ys+"]");h.set(t,E);let $i=new WeakMap;$i.set(Ca,h),Vl(q,Hl(Ri,cp,r,n,o,s,a,i,r==="comma"&&b&&ie(x)?null:u,l,d,m,f,I,w,b,y,$i))}return q}function im(t=X){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||X.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Ia;if(typeof t.format<"u"){if(!Yo(Ta,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Ta[r],o=X.filter;(typeof t.filter=="function"||ie(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Wl?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=X.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:X.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:X.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:X.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:X.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?X.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:X.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:X.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:X.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:X.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:X.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:X.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:X.strictNullHandling}}function Jl(t,e={}){let r=t,n=im(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ie(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=Wl[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let f=0;f<o.length;++f){let I=o[f];n.skipNulls&&r[I]===null||Vl(a,Hl(r[I],I,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let d=a.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),d.length>0?m+d:""}function Zl(t){return Jl(t,{arrayFormat:"brackets"})}function Xl(t){let e=0;for(let o of t)e+=o.length;let r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var Ql;function kr(t){let e;return(Ql??(e=new globalThis.TextEncoder,Ql=e.encode.bind(e)))(t)}var Yl;function Ea(t){let e;return(Yl??(e=new globalThis.TextDecoder,Yl=e.decode.bind(e)))(t)}var he,ge,Et=class{constructor(){he.set(this,void 0),ge.set(this,void 0),C(this,he,new Uint8Array,"f"),C(this,ge,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kr(e):e;C(this,he,Xl([_(this,he,"f"),r]),"f");let n=[],o;for(;(o=um(_(this,he,"f"),_(this,ge,"f")))!=null;){if(o.carriage&&_(this,ge,"f")==null){C(this,ge,o.index,"f");continue}if(_(this,ge,"f")!=null&&(o.index!==_(this,ge,"f")+1||o.carriage)){n.push(Ea(_(this,he,"f").subarray(0,_(this,ge,"f")-1))),C(this,he,_(this,he,"f").subarray(_(this,ge,"f")),"f"),C(this,ge,null,"f");continue}let s=_(this,ge,"f")!==null?o.preceding-1:o.preceding,a=Ea(_(this,he,"f").subarray(0,s));n.push(a),C(this,he,_(this,he,"f").subarray(o.index),"f"),C(this,ge,null,"f")}return n}flush(){return _(this,he,"f").length?this.decode(`
@@ -65,19 +65,19 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
65
65
  ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
66
66
  ]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
67
67
  `:`[${o[l]}\r
68
- ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Es(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Cs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function Ac(t,e){if(e.mapStrategy==="record")return Es(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ic(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function vc(){return{not:{}}}function Tc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ao={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function kc(t,e){if(e.target==="openApi3")return Sc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ao&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Ao[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Sc(t,e)}var Sc=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Cc(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Ao[t.innerType._def.typeName],nullable:!0}:{type:[Ao[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=M(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Ec(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ni(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function lh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Pc(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=M(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:lh(t,e)};return r.required.length||delete r.required,r}var Oc=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return M(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Mc=(t,e,r)=>{if(e.pipeStrategy==="input")return M(t.in._def,e,r);if(e.pipeStrategy==="output")return M(t.out._def,e,r);let n=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Rc(t,e,r){return M(t.type._def,e,r)}function $c(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&L(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&L(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Nc(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function zc(){return{not:{}}}function jc(){return{}}var Lc=(t,e,r)=>M(t.innerType._def,e,r);function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==ac)return s}if(n&&!r){let s=uh(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=ph(t,t.typeName,e,r);return s&&mh(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var uh=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((n,o)=>o===0?n:ch(n)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:dh(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Dc="_x_",ch=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Dc))return t;let e=Dc;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},dh=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},ph=(t,e,r,n)=>{switch(e){case N.ZodString:return Cs(t,r);case N.ZodNumber:return Ec(t,r);case N.ZodObject:return Pc(t,r);case N.ZodBigInt:return pc(t,r);case N.ZodBoolean:return mc();case N.ZodDate:return oi(t,r);case N.ZodUndefined:return zc();case N.ZodNull:return Tc(r);case N.ZodArray:return dc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return kc(t,r);case N.ZodIntersection:return wc(t,r);case N.ZodTuple:return Nc(t,r);case N.ZodRecord:return Es(t,r);case N.ZodLiteral:return bc(t,r);case N.ZodEnum:return _c(t);case N.ZodNativeEnum:return Ic(t);case N.ZodNullable:return Cc(t,r,n);case N.ZodOptional:return Oc(t,r,n);case N.ZodMap:return Ac(t,r);case N.ZodSet:return $c(t,r);case N.ZodLazy:return M(t.getter()._def,r,n);case N.ZodPromise:return Rc(t,r,n);case N.ZodNaN:case N.ZodNever:return vc();case N.ZodEffects:return yc(t,r,n);case N.ZodAny:return cc();case N.ZodUnknown:return jc();case N.ZodDefault:return gc(t,r,n);case N.ZodBranded:return fc(t,r,n);case N.ZodReadonly:return Lc(t,r,n);case N.ZodCatch:return hc(t,r,n);case N.ZodPipeline:return Mc(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},mh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ai=(t,e)=>{let r=uc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=M(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(lc(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,I]of m)u[f]=M(xo(I),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function Fc(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return Ze(e,[],e)}function ii(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(ii(e))return!0;for(let e of t.anyOf??[])if(ii(e))return!0;return!1}function Ze(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ar(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(ar(n))for(let[f,I]of Object.entries(n))Ze(I,[...e,"$defs",f],r);let o=t.definitions;if(ar(o))for(let[f,I]of Object.entries(o))Ze(I,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(ar(i)){for(let[f,I]of Object.entries(i))if(!ii(I)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(i),t.properties=Object.fromEntries(Object.entries(i).map(([f,I])=>[f,Ze(I,[...e,"properties",f],r)]))}let u=t.items;ar(u)&&(t.items=Ze(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,I)=>Ze(f,[...e,"anyOf",String(I)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=Ze(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,I)=>Ze(f,[...e,"allOf",String(I)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&hh(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=fh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!ar(f))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,Ze(t,e,r)}return t}function fh(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!ar(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function ar(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function gh(t,e){return ai(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function yh(t){return Fc(Xi(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function _h(t){return"_zod"in t}function Uc(t,e,r){return uu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:_h(t)?yh(t):gh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var qc=["jsonSchema","functionCalling","jsonMode"];function Bc(t,e){if(typeof e<"u"&&!qc.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${qc.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function wh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Kc(t,e,r){if(el(t))return Uc(t,e,r);if(Fo(t))return wh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:St(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Qi(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function Gc(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var Wc={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Rn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var ir=class extends Ko{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??De("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??De("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!He(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Tt(t.json_schema.schema)?Kc(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=bt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=xt(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return or(t)?oc(t.metadata.customTool):qo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Hu(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if(Mn(n)||or(n))return n;if(Qu(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return hr(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Je(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,d=s;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=Ju(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw ve(o)}})}get profile(){return Wc[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Bc(this.model,e?.method);if(i==="jsonMode"){n=sa(o);let u=St(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=St(o),l={name:s??"extract",description:na(u),schema:Tt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),Tt(o)||Do(o)){let d=sa(o);n=rt.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d.invoke(m.content))}else n=new rl}else{let u=s??"extract",l=St(o),d;Tt(o)||Do(o)?d={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(d=o,u=o.name):(u=o.title??u,d={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=nl(o,u)}return ol(r,n,a)}};var Ps={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=ea({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=Xs(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Xs(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=ea({dataUrl:t.url}),r=nr(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=nr(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},li=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(Bo(l,{returnId:!0}))}catch(d){a.push(mr(l,d.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new D({content:Gc(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new jo(t.content||"",t.role??"unknown")}},ui=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new ra({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new tt({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new Lo({content:s,response_metadata:i}):o==="developer"?new Lo({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Hi({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new ta({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new Vi({content:s,role:o,response_metadata:i})},Vc=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=Ji(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=nr(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},Hc=({message:t,model:e})=>{let r=Je(t);if(r==="system"&&He(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return D.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(oa):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&U.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=Vc(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},$n=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Hc({message:r});let n=Je(r);n==="system"&&He(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>No(a)?zo(a,Ps):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),D.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(oa):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),U.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var Os=class extends ir{constructor(t,e){super(Rn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Ss(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),He(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=$n({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let I of a){I.message.response_metadata={...I.generationInfo,...I.message.response_metadata};let w=I.generationInfo?.completion??0;i[w]===void 0?i[w]=I:i[w]=i[w].concat(I)}let u=Object.entries(i).sort(([I],[w])=>parseInt(I,10)-parseInt(w,10)).map(([I,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:m}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(n.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let I of a?.choices??[]){let w={text:I.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(I.message??{role:"assistant"},a)};w.generationInfo={...I.finish_reason?{finish_reason:I.finish_reason}:{},...I.logprobs?{logprobs:I.logprobs}:{}},et(w.message)&&(w.message.usage_metadata=n),w.message=new D(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=$n({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),a=this.streamUsage??e.streamUsage;yield*Go(async function*(u,l){for await(let d of u){if(l?.aborted)return;yield d}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=$n({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:d}=l;if(!d)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let I={...f};l.finish_reason!=null&&(I.finish_reason=l.finish_reason,I.system_fingerprint=u.system_fingerprint,I.model_name=u.model,I.service_tier=u.service_tier),this.logprobs&&(I.logprobs=l.logprobs);let w=new Vn({message:m,text:m.content,generationInfo:I});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},d=new Vn({message:new tt({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield d,await r?.handleLLMNewToken(d.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:d})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw ve(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return ui({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return li({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Ms="__openai_function_call_ids__",Rs="__openai_custom_tool_call_ids__";function td(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function xh(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var Io=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},$s=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],n=[],o=t.output.map(i=>{if(i.type==="function_call"&&"parsed_arguments"in i){let u={...i};return delete u.parsed_arguments,u}return i}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let i of t.output)if(i.type==="message")e.push(...i.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(td),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(Bo(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),n.push(mr(u,d))}a[Ms]??={},i.id&&(a[Ms][i.call_id]=i.id)}else if(i.type==="reasoning"){a.reasoning=i;let u=i.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(i.type==="custom_tool_call"){let u=Xu(i);u?(r.push(u),a[Rs]??={},i.id&&i.call_id&&(a[Rs][i.call_id]=i.id)):n.push(mr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=ec(i);u?r.push(u):n.push(mr(i,"Malformed computer call"))}else i.type==="image_generation_call"?(i.result&&e.push({type:"image",mimeType:"image/png",data:i.result,id:i.id,metadata:{status:i.status}}),a.tool_outputs??=[],a.tool_outputs.push(i)):(a.tool_outputs??=[],a.tool_outputs.push(i));return new D({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Io(t.usage),additional_kwargs:a,response_metadata:s})},rd=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},ci=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[td(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Ms]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Rs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")i=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){i=t.response.id;let u=$s(t.response);if(n=Io(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{a.parsed??=JSON.parse(u.text)}catch{}for(let[l,d]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=d)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,u,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:u,status:l}}}else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((d,m)=>({...d,index:m})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(d=>d.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new Vn({text:e.map(u=>u.text).join(""),message:new tt({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},nd=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Te(()=>{try{let h=Je(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let d=(h,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},m=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{let x=Te(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:x,file_id:h.fileId};if(h.url)return{type:"input_image",detail:x,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},I=h=>{if(h.fileId){let x=vs(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=vs(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=nr(h),S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${S}`,filename:x}}},w=h=>{let x=Te(()=>{if(Array.isArray(h.summary)){let E=h.summary?.map(F=>F?.text).filter(F=>typeof F=="string")??[];if(E.length>0)return E}return h.reasoning?[h.reasoning]:[]}),S=x.length>0?x.map(E=>({type:"summary_text",text:E})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:S}},b=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:m(h.args)}),y=h=>{let x=m(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:x,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let x=Te(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});d([{type:"input_text",text:h.text}],x)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield w(h);else if(h.type==="tool_call"){yield*l();let x=h.id??"";x&&(s.add(x),i.delete(x)),yield b(h)}else if(h.type==="tool_call_chunk"){if(h.id){let x=i.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),i.set(h.id,x)}}else if(h.type==="server_tool_call"){yield*l();let x=h.id??"";x&&(a.add(x),u.delete(x)),yield b(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let x=u.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),u.set(h.id,x)}}else if(h.type==="server_tool_call_result")yield*l(),yield y(h);else if(h.type!=="audio")if(h.type==="file"){let x=I(h);x&&d([x])}else if(h.type==="image"){let x=f(h);x&&d([x])}else if(h.type==="video"){let x=I(h);x&&d([x])}else h.type==="text-plain"?h.text&&d([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,x]of i){if(!h||s.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}for(let[h,x]of u){if(!h||a.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}}return Array.from(r())},vo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return nd(n);let s=n.additional_kwargs,a=Je(n);if(a==="system"&&He(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(f=>f.type==="input_image");if(l)return l;let d=i.content.find(f=>f.type==="computer_screenshot");if(d)return d;let m=i.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(b=>"type"in b))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=rd(u);i.push(b)}let{content:d}=n;if(s?.refusal&&(typeof d=="string"&&(d=[{type:"output_text",text:d,annotations:[]}]),d=[...d,{type:"refusal",refusal:s.refusal}]),typeof d=="string"||d.length>0){let b={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Te(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let h=y;return{type:"output_text",text:h.text,annotations:(h.annotations??[]).map(xh)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Te(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let m=s?.[Ms],f=s?.[Rs];D.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(b=>rc(b,f)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:f?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:tc(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:m?.[b.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:m?.[b.id]}})));let I=o?.output?.length?o?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(I!=null){let b=I?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),No(l)){if(l.type==="file"){let d=vs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...d?{filename:d}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...d?{filename:d}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:nr(l)}}return zo(l,Ps)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Te(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Te(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*di(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,a=0,i=!1,u,l,d,m,f=new Set,I=(y,h)=>{let x=s.get(y);if(x!==void 0)return{index:x,isNew:!1};let S=a++;return s.set(y,S),o.set(S,{...h}),{index:S,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let h=o.get(y);h&&(f.add(y),yield{event:"content-block-finish",index:y,content:sl(h)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:h,isNew:x}=I(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let S=o.get(h);S.text=(S.text??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:h,isNew:x}=I(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let S=o.get(h);S.reasoning=(S.reasoning??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"reasoning-delta",reasoning:y.delta}};continue}if(y.type==="response.output_item.added"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="custom_tool_call",S=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:E,isNew:F}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index,...x?{isCustomTool:!0}:{}});if(F&&(yield{event:"content-block-start",index:E,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index}}),S){let q=o.get(E);yield{event:"content-block-delta",index:E,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...q.id!=null?{id:q.id}:{},...q.name!=null?{name:q.name}:{},args:q.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:h,isNew:x}=I(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:h,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let S=o.get(h);S.args=(S.args??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:S,isNew:E}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index});if(E)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index}};else{let F=o.get(S);F.args=x,F.id=y.item.call_id,F.name=y.item.name}yield*b(S);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=Ah(y.response.status,y.type),m={model_provider:n,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=Io(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of o)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function Ah(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Ns=class extends ir{constructor(t,e){super(Rn(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Yu(t?.tool_choice)?t?.tool_choice:(()=>{let o=Ss(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:$s(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*di(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of n){if(e.signal?.aborted)return;let s=ci(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(o){throw ve(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw ve(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Mn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(or(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(qo(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else ks(n)&&r.push(nc(n));return r}};var zs=class od extends ir{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Rn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Ns(n),this.completions=n?.completions??new Os(n)}_useResponsesApi(e){let r=e?.tools?.some(Mn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(ks)||e?.tools?.some(or);return this.useResponsesApi||r||n||o||Gu(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamChatModelEvents(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new od(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var kh=v.object({type:v.literal("screenshot")}),Ch=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Eh=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Ph=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),Oh=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),Mh=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),Rh=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),$h=v.object({type:v.literal("type"),text:v.string()}),Nh=v.object({type:v.literal("wait"),duration:v.number().optional()}),zh=v.union([kh,Ch,Eh,Ph,Oh,Mh,Rh,$h,Nh]),qq=v.object({action:zh});var jh=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),Wq=v.union([jh]);var Zq=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var Lh=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),Dh=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),Fh=v.object({type:v.literal("delete_file"),path:v.string()}),eB=v.union([Lh,Dh,Fh]);var id={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Kh={default:"text-embedding-ada-002"},pi=new Map,js=null,Gh=()=>{let t=ad.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},Wh=async t=>{let e=Gh();pi.size===0&&(js||(js=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>pi.set(o.name,o))}catch(n){throw js=null,n}})()),await js);let r=pi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Vh=async(t="default")=>await Wh(id[t]);var zn=(t,e)=>e,ld=(t,e)=>({...t,...e}),ud=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
68
+ ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Es(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Cs(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function Ac(t,e){if(e.mapStrategy==="record")return Es(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Ic(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function vc(){return{not:{}}}function Tc(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ao={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function kc(t,e){if(e.target==="openApi3")return Sc(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ao&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=Ao[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Sc(t,e)}var Sc=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Cc(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Ao[t.innerType._def.typeName],nullable:!0}:{type:[Ao[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=M(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Ec(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ni(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?L(r,"minimum",n.value,n.message,e):L(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),L(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?L(r,"maximum",n.value,n.message,e):L(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),L(r,"maximum",n.value,n.message,e));break;case"multipleOf":L(r,"multipleOf",n.value,n.message,e);break}return r}function lh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Pc(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=M(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:lh(t,e)};return r.required.length||delete r.required,r}var Oc=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return M(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Mc=(t,e,r)=>{if(e.pipeStrategy==="input")return M(t.in._def,e,r);if(e.pipeStrategy==="output")return M(t.out._def,e,r);let n=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Rc(t,e,r){return M(t.type._def,e,r)}function $c(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&L(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&L(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Nc(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function zc(){return{not:{}}}function jc(){return{}}var Lc=(t,e,r)=>M(t.innerType._def,e,r);function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==ac)return s}if(n&&!r){let s=uh(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=ph(t,t.typeName,e,r);return s&&mh(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var uh=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((n,o)=>o===0?n:ch(n)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:dh(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Dc="_x_",ch=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Dc))return t;let e=Dc;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},dh=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},ph=(t,e,r,n)=>{switch(e){case N.ZodString:return Cs(t,r);case N.ZodNumber:return Ec(t,r);case N.ZodObject:return Pc(t,r);case N.ZodBigInt:return pc(t,r);case N.ZodBoolean:return mc();case N.ZodDate:return oi(t,r);case N.ZodUndefined:return zc();case N.ZodNull:return Tc(r);case N.ZodArray:return dc(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return kc(t,r);case N.ZodIntersection:return wc(t,r);case N.ZodTuple:return Nc(t,r);case N.ZodRecord:return Es(t,r);case N.ZodLiteral:return bc(t,r);case N.ZodEnum:return _c(t);case N.ZodNativeEnum:return Ic(t);case N.ZodNullable:return Cc(t,r,n);case N.ZodOptional:return Oc(t,r,n);case N.ZodMap:return Ac(t,r);case N.ZodSet:return $c(t,r);case N.ZodLazy:return M(t.getter()._def,r,n);case N.ZodPromise:return Rc(t,r,n);case N.ZodNaN:case N.ZodNever:return vc();case N.ZodEffects:return yc(t,r,n);case N.ZodAny:return cc();case N.ZodUnknown:return jc();case N.ZodDefault:return gc(t,r,n);case N.ZodBranded:return fc(t,r,n);case N.ZodReadonly:return Lc(t,r,n);case N.ZodCatch:return hc(t,r,n);case N.ZodPipeline:return Mc(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},mh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ai=(t,e)=>{let r=uc(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=M(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(lc(r.definitions))return;let u={},l=new Set;for(let d=0;d<500;d++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,I]of m)u[f]=M(xo(I),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function Fc(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return Ze(e,[],e)}function ii(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(ii(e))return!0;for(let e of t.anyOf??[])if(ii(e))return!0;return!1}function Ze(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ar(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(ar(n))for(let[f,I]of Object.entries(n))Ze(I,[...e,"$defs",f],r);let o=t.definitions;if(ar(o))for(let[f,I]of Object.entries(o))Ze(I,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(ar(i)){for(let[f,I]of Object.entries(i))if(!ii(I)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(i),t.properties=Object.fromEntries(Object.entries(i).map(([f,I])=>[f,Ze(I,[...e,"properties",f],r)]))}let u=t.items;ar(u)&&(t.items=Ze(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,I)=>Ze(f,[...e,"anyOf",String(I)],r)));let d=t.allOf;if(Array.isArray(d))if(d.length===1){let f=Ze(d[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=d.map((f,I)=>Ze(f,[...e,"allOf",String(I)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&hh(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=fh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!ar(f))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,Ze(t,e,r)}return t}function fh(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!ar(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function ar(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hh(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function gh(t,e){return ai(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function yh(t){return Fc(Xi(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function _h(t){return"_zod"in t}function Uc(t,e,r){return uu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:_h(t)?yh(t):gh(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var qc=["jsonSchema","functionCalling","jsonMode"];function Bc(t,e){if(typeof e<"u"&&!qc.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${qc.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function wh(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Kc(t,e,r){if(el(t))return Uc(t,e,r);if(Fo(t))return wh({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:St(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Qi(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function Gc(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var Wc={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Rn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var ir=class extends Ko{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??De("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??De("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!He(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Tt(t.json_schema.schema)?Kc(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=bt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=xt(r.defaultHeaders),this.client=new P(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return or(t)?oc(t.metadata.customTool):qo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Hu(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if(Mn(n)||or(n))return n;if(Qu(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return hr(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Je(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,d=s;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=Ju(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw ve(o)}})}get profile(){return Wc[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=Bc(this.model,e?.method);if(i==="jsonMode"){n=sa(o);let u=St(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=St(o),l={name:s??"extract",description:na(u),schema:Tt(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),Tt(o)||Do(o)){let d=sa(o);n=rt.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d.invoke(m.content))}else n=new rl}else{let u=s??"extract",l=St(o),d;Tt(o)||Do(o)?d={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(d=o,u=o.name):(u=o.title??u,d={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=nl(o,u)}return ol(r,n,a)}};var Ps={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=ea({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=Xs(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Xs(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=ea({dataUrl:t.url}),r=nr(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=nr(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},li=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(Bo(l,{returnId:!0}))}catch(d){a.push(mr(l,d.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new D({content:Gc(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new jo(t.content||"",t.role??"unknown")}},ui=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new ra({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new tt({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new Lo({content:s,response_metadata:i}):o==="developer"?new Lo({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Hi({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new ta({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new Vi({content:s,role:o,response_metadata:i})},Vc=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=Ji(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=nr(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},Hc=({message:t,model:e})=>{let r=Je(t);if(r==="system"&&He(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return D.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(oa):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&U.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=Vc(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},$n=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Hc({message:r});let n=Je(r);n==="system"&&He(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>No(a)?zo(a,Ps):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),D.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(oa):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),U.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var Os=class extends ir{constructor(t,e){super(Rn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:Ss(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),He(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=$n({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let I of a){I.message.response_metadata={...I.generationInfo,...I.message.response_metadata};let w=I.generationInfo?.completion??0;i[w]===void 0?i[w]=I:i[w]=i[w].concat(I)}let u=Object.entries(i).sort(([I],[w])=>parseInt(I,10)-parseInt(w,10)).map(([I,w])=>w),{functions:l,function_call:d}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,d),f=await this._getNumTokensFromGenerations(u);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:m}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(n.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let I of a?.choices??[]){let w={text:I.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(I.message??{role:"assistant"},a)};w.generationInfo={...I.finish_reason?{finish_reason:I.finish_reason}:{},...I.logprobs?{logprobs:I.logprobs}:{}},et(w.message)&&(w.message.usage_metadata=n),w.message=new D(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=$n({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),a=this.streamUsage??e.streamUsage;yield*Go(async function*(u,l){for await(let d of u){if(l?.aborted)return;yield d}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=$n({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:d}=l;if(!d)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(d,u,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let I={...f};l.finish_reason!=null&&(I.finish_reason=l.finish_reason,I.system_fingerprint=u.system_fingerprint,I.model_name=u.model,I.service_tier=u.service_tier),this.logprobs&&(I.logprobs=l.logprobs);let w=new Vn({message:m,text:m.content,generationInfo:I});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},d=new Vn({message:new tt({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield d,await r?.handleLLMNewToken(d.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:d})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw ve(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return ui({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return li({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Ms="__openai_function_call_ids__",Rs="__openai_custom_tool_call_ids__";function td(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function xh(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var Io=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},$s=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],n=[],o=t.output.map(i=>{if(i.type==="function_call"&&"parsed_arguments"in i){let u={...i};return delete u.parsed_arguments,u}return i}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let i of t.output)if(i.type==="message")e.push(...i.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(td),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(Bo(u,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),n.push(mr(u,d))}a[Ms]??={},i.id&&(a[Ms][i.call_id]=i.id)}else if(i.type==="reasoning"){a.reasoning=i;let u=i.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(i.type==="custom_tool_call"){let u=Xu(i);u?(r.push(u),a[Rs]??={},i.id&&i.call_id&&(a[Rs][i.call_id]=i.id)):n.push(mr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=ec(i);u?r.push(u):n.push(mr(i,"Malformed computer call"))}else i.type==="image_generation_call"?(i.result&&e.push({type:"image",mimeType:"image/png",data:i.result,id:i.id,metadata:{status:i.status}}),a.tool_outputs??=[],a.tool_outputs.push(i)):(a.tool_outputs??=[],a.tool_outputs.push(i));return new D({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Io(t.usage),additional_kwargs:a,response_metadata:s})},rd=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},ci=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[td(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Ms]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Rs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")i=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){i=t.response.id;let u=$s(t.response);if(n=Io(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{a.parsed??=JSON.parse(u.text)}catch{}for(let[l,d]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=d)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,u,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:u,status:l}}}else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((d,m)=>({...d,index:m})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(d=>d.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new Vn({text:e.map(u=>u.text).join(""),message:new tt({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},nd=t=>{let e=D.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Te(()=>{try{let h=Je(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let h=o.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield o),o=void 0}let d=(h,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...h]:[...h]:o.content.push(...h)},m=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{let x=Te(()=>{let S=h.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(h.fileId)return{type:"input_image",detail:x,file_id:h.fileId};if(h.url)return{type:"input_image",detail:x,image_url:h.url};if(h.data){let S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${h.mimeType??"image/png"};base64,${S}`}}},I=h=>{if(h.fileId){let x=vs(h);return{type:"input_file",file_id:h.fileId,...x?{filename:x}:{}}}if(h.url){let x=vs(h);return{...x?{filename:x}:{},type:"input_file",file_url:h.url}}if(h.data){let x=nr(h),S=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${S}`,filename:x}}},w=h=>{let x=Te(()=>{if(Array.isArray(h.summary)){let E=h.summary?.map(F=>F?.text).filter(F=>typeof F=="string")??[];if(E.length>0)return E}return h.reasoning?[h.reasoning]:[]}),S=x.length>0?x.map(E=>({type:"summary_text",text:E})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:S}},b=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:m(h.args)}),y=h=>{let x=m(h.output),S=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:x,...S?{status:S}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let x=Te(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});d([{type:"input_text",text:h.text}],x)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*l(),yield w(h);else if(h.type==="tool_call"){yield*l();let x=h.id??"";x&&(s.add(x),i.delete(x)),yield b(h)}else if(h.type==="tool_call_chunk"){if(h.id){let x=i.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),i.set(h.id,x)}}else if(h.type==="server_tool_call"){yield*l();let x=h.id??"";x&&(a.add(x),u.delete(x)),yield b(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let x=u.get(h.id)??{name:h.name,args:[]};h.name&&(x.name=h.name),h.args&&x.args.push(h.args),u.set(h.id,x)}}else if(h.type==="server_tool_call_result")yield*l(),yield y(h);else if(h.type!=="audio")if(h.type==="file"){let x=I(h);x&&d([x])}else if(h.type==="image"){let x=f(h);x&&d([x])}else if(h.type==="video"){let x=I(h);x&&d([x])}else h.type==="text-plain"?h.text&&d([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*l(),yield h.value)}yield*l();for(let[h,x]of i){if(!h||s.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}for(let[h,x]of u){if(!h||a.has(h))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:h,name:x.name??"",arguments:S})}}return Array.from(r())},vo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return nd(n);let s=n.additional_kwargs,a=Je(n);if(a==="system"&&He(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(f=>f.type==="input_image");if(l)return l;let d=i.content.find(f=>f.type==="computer_screenshot");if(d)return d;let m=i.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(b=>"type"in b))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let b=rd(u);i.push(b)}let{content:d}=n;if(s?.refusal&&(typeof d=="string"&&(d=[{type:"output_text",text:d,annotations:[]}]),d=[...d,{type:"refusal",refusal:s.refusal}]),typeof d=="string"||d.length>0){let b={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Te(()=>typeof d=="string"?d:d.flatMap(y=>{if(y.type==="text"){let h=y;return{type:"output_text",text:h.text,annotations:(h.annotations??[]).map(xh)}}return y.type==="output_text"||y.type==="refusal"?y:[]})),phase:Te(()=>{if(Array.isArray(d))return d.find(y=>"phase"in y&&typeof y.phase=="string")?.phase})};i.push(b)}let m=s?.[Ms],f=s?.[Rs];D.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(b=>rc(b,f)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:f?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:tc(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:m?.[b.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:m?.[b.id]}})));let I=o?.output?.length?o?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(I!=null){let b=I?.filter(y=>w.includes(y.type));b.length>0&&i.push(...b)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),No(l)){if(l.type==="file"){let d=vs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...d?{filename:d}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...d?{filename:d}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:nr(l)}}return zo(l,Ps)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Te(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Te(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*di(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,a=0,i=!1,u,l,d,m,f=new Set,I=(y,h)=>{let x=s.get(y);if(x!==void 0)return{index:x,isNew:!1};let S=a++;return s.set(y,S),o.set(S,{...h}),{index:S,isNew:!0}},w=function*(){i||(i=!0,yield{event:"message-start",id:u})},b=function*(y){if(f.has(y))return;let h=o.get(y);h&&(f.add(y),yield{event:"content-block-finish",index:y,content:sl(h)})};for await(let y of t){if(y.type==="response.created"){u=y.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:y.response.model,id:y.response.id}};continue}if(y.type==="response.output_text.delta"){yield*w();let{index:h,isNew:x}=I(`text:${y.output_index}:${y.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let S=o.get(h);S.text=(S.text??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:y.delta}};continue}if(y.type==="response.reasoning_summary_text.delta"){yield*w();let{index:h,isNew:x}=I(`reasoning:${y.output_index}:${y.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let S=o.get(h);S.reasoning=(S.reasoning??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"reasoning-delta",reasoning:y.delta}};continue}if(y.type==="response.output_item.added"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="custom_tool_call",S=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:E,isNew:F}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index,...x?{isCustomTool:!0}:{}});if(F&&(yield{event:"content-block-start",index:E,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:S,index:y.output_index}}),S){let q=o.get(E);yield{event:"content-block-delta",index:E,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...q.id!=null?{id:q.id}:{},...q.name!=null?{name:q.name}:{},args:q.args}}}}continue}if(y.type==="response.function_call_arguments.delta"||y.type==="response.custom_tool_call_input.delta"){yield*w();let{index:h,isNew:x}=I(`tool:${y.output_index}`,{type:"tool_call_chunk",args:"",index:y.output_index,...y.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:h,content:{type:"tool_call_chunk",args:"",index:y.output_index}});let S=o.get(h);S.args=(S.args??"")+y.delta,yield{event:"content-block-delta",index:h,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(y.type==="response.output_item.done"&&(y.item.type==="function_call"||y.item.type==="custom_tool_call")){yield*w();let h=`tool:${y.output_index}`,x=y.item.type==="function_call"?y.item.arguments??"":y.item.input??"",{index:S,isNew:E}=I(h,{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index});if(E)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:y.item.call_id,name:y.item.name,args:x,index:y.output_index}};else{let F=o.get(S);F.args=x,F.id=y.item.call_id,F.name=y.item.name}yield*b(S);continue}if(y.type==="response.completed"||y.type==="response.incomplete"){yield*w(),u=y.response.id,d=Ah(y.response.status,y.type),m={model_provider:n,id:y.response.id,model:y.response.model,status:y.response.status},r&&y.response.usage&&(l=Io(y.response.usage),yield{event:"usage",usage:l});continue}y.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:y.type,payload:y})}i||(yield{event:"message-start"});for(let[y]of o)f.has(y)||(yield*b(y));yield{event:"message-finish",reason:d,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function Ah(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Ns=class extends ir{constructor(t,e){super(Rn(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Yu(t?.tool_choice)?t?.tool_choice:(()=>{let o=Ss(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:$s(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*di(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:vo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of n){if(e.signal?.aborted)return;let s=ci(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(o){throw ve(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw ve(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Mn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(or(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(qo(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else ks(n)&&r.push(nc(n));return r}};var zs=class od extends ir{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Rn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Ns(n),this.completions=n?.completions??new Os(n)}_useResponsesApi(e){let r=e?.tools?.some(Mn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(ks)||e?.tools?.some(or);return this.useResponsesApi||r||n||o||Gu(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamChatModelEvents(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new od(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var kh=v.object({type:v.literal("screenshot")}),Ch=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Eh=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Ph=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),Oh=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),Mh=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),Rh=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),$h=v.object({type:v.literal("type"),text:v.string()}),Nh=v.object({type:v.literal("wait"),duration:v.number().optional()}),zh=v.union([kh,Ch,Eh,Ph,Oh,Mh,Rh,$h,Nh]),Bq=v.object({action:zh});var jh=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),Vq=v.union([jh]);var Qq=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var Lh=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),Dh=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),Fh=v.object({type:v.literal("delete_file"),path:v.string()}),tB=v.union([Lh,Dh,Fh]);var id={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Gh={default:"text-embedding-ada-002"},pi=new Map,js=null,Wh=()=>{let t=ad.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},Vh=async t=>{let e=Wh();pi.size===0&&(js||(js=(async()=>{try{(await qh(`${e}/models`)).data.models.forEach(n=>pi.set(n.name,n))}catch(n){throw js=null,n}})()),await js);let r=pi.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Hh=async(t="default")=>await Vh(id[t]);var zn=(t,e)=>e,ld=(t,e)=>({...t,...e}),ud=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
69
69
 
70
70
  `);return o[o.length-1]?.trim()===r?t:`${t}
71
71
 
72
- ${r}`},cd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),lr=()=>({agentExecutionContext:O({reducer:ld,default:cd}),outputMessage:O({reducer:ud,default:()=>""}),summary:O({reducer:zn,default:()=>""}),status:O({reducer:zn})}),Ls=()=>({...lr(),sharedStatePatch:O({reducer:zn})}),Hh=O.Root({agentExecutionContext:O({default:cd,reducer:ld}),currentIntent:O({default:()=>"none",reducer:zn}),lastExecutedAgent:O({default:()=>"",reducer:zn}),requiresFollowUp:O({default:()=>!0,reducer:zn}),stepCount:O({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:O({default:()=>"",reducer:ud})});var Jh=t=>typeof t=="string"&&t.length>0?t:void 0,Zh=()=>Li(),Qh=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Yh=t=>{let e=t?.configurable;return{conversationId:Jh(e?.thread_id),abortSignal:t?.signal,requestId:Zh(),requestSource:Qh(Bh.applicationName)}},Xh=async({config:t})=>{let e=ad.getDefault(),r=(await qh.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Yh(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",u)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i);let d=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:l,signal:d})}},mi=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=id[e],s=await Vh(e);return new zs({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await Xh({config:n})}})};var eg=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(eg);var dd="0.1",Nn=1536,pd="openai",md=Kh.default,fd=`Name: {name}
72
+ ${r}`},cd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),lr=()=>({agentExecutionContext:O({reducer:ld,default:cd}),outputMessage:O({reducer:ud,default:()=>""}),summary:O({reducer:zn,default:()=>""}),status:O({reducer:zn})}),Ls=()=>({...lr(),sharedStatePatch:O({reducer:zn})}),Jh=O.Root({agentExecutionContext:O({default:cd,reducer:ld}),currentIntent:O({default:()=>"none",reducer:zn}),lastExecutedAgent:O({default:()=>"",reducer:zn}),requiresFollowUp:O({default:()=>!0,reducer:zn}),stepCount:O({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:O({default:()=>"",reducer:ud})});var Zh=t=>typeof t=="string"&&t.length>0?t:void 0,Qh=()=>Li(),Yh=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Xh=t=>{let e=t?.configurable;return{conversationId:Zh(e?.thread_id),abortSignal:t?.signal,requestId:Qh(),requestSource:Yh(Kh.applicationName)}},eg=async({config:t})=>{let e=ad.getDefault(),r=(await Bh.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=Xh(t),l=new Headers(o?.headers);for(let m of[...l.keys()]){let f=m.toLowerCase();(f==="authorization"||f==="api-key"||f.startsWith("x-stainless-"))&&l.delete(m)}r&&r.length>0&&l.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(u&&u.length>0&&l.set("X-Esri-Request-Source",u),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i));let d=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:l,signal:d})}},mi=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=id[e],s=await Hh(e);return new zs({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await eg({config:n})}})};var tg=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(tg);var dd="0.1",Nn=1536,pd="openai",md=Gh.default,fd=`Name: {name}
73
73
  Title: {title}
74
74
  Description: {description}`,hd=`Name: {name}
75
75
  Alias: {alias}
76
- Description: {description}`,gd=v.object({schemaVersion:v.literal(dd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(pd),model:v.literal(md),dimensions:v.literal(Nn),templates:v.object({layer:v.string().default(fd),field:v.string().default(hd)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Nn,{message:`Layer vector must be exactly ${Nn} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Nn,{message:`Field vector must be exactly ${Nn} dimensions`})}))})).default([])});var tg=(t,e)=>{let r=al.fromTemplate(t);return fr.fromMessages([r,...e])};var To=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=tg(e,o??[]),l=(await mi({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var rg=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),IK=c.object({fields:c.array(rg)});var vK=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var _d=t=>Array.isArray(t)&&t.every(Wn),og=t=>typeof t=="object"&&t!=null&&"messages"in t&&_d(t.messages),sg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,Qe=class extends il{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e,r){let n=this.tools.find(o=>o.name===t.name);try{if(n===void 0)throw new Error(`Tool "${t.name}" not found.`);let o={...t,type:"tool_call"},s={...e,state:r,toolCallId:t.id??"",config:e,context:e.context,store:e.store??null,writer:e.writer??e.configurable?.writer??null},a=await n.invoke(o,s);return Wn(a)&&a.getType()==="tool"||vt(a)?a:new U({status:"success",name:n.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||$o(o))throw o;return new U({status:"error",content:`Error: ${o.message}
77
- Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(sg(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(_d(t))s=t;else if(og(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(et(l)){i=l;break}}if(i==null||!et(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(vt))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)vt(s)?s.graph===Le.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Ki(a))?o?o.goto.push(...s.goto):o=new Le({graph:Le.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var TG=O.Root({llmInputMessages:O({reducer:(t,e)=>Hn([],e),default:()=>[]})});var So=(t,e)=>e??t,Ug=O.Root({...Ls(),intent:O({reducer:So}),vectorSearchLayerResults:O({reducer:So,default:()=>[]}),vectorSearchFieldResults:O({reducer:So}),navigationInternalState:O({reducer:So,default:()=>({toolCallMessage:void 0})})});async function qg(t,e){let r=ur.getDefault().helperServices,n=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${fi.assetsPath?.endsWith("/")?fi.assetsPath:`${fi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await lg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new ug({url:s,width:24,height:24}),u=new ig({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Bg=["mapView"];function je(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Bg.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Kg({address:t},e){let{mapView:r}=je(e);return await qg(t,r)}var Gg=c.object({address:c.string().describe("The full address or place name to locate.")}),Wg=$(Kg,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Gg});async function Vg(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Hg({bookmarkName:t},e){let{mapView:r}=je(e);return await Promise.resolve(Vg(t,r))}var Jg=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),Zg=$(Hg,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Jg});async function Qg(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function Yg({layerId:t,where:e},r){let{mapView:n}=je(r);return await Qg(t,e,n)}var Xg=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),ey=$(Yg,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Xg});async function ty(t){let e=new cg({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function ry(t,e){let{mapView:r}=je(e);return await ty(r)}var ny=v.object({}),oy=$(ry,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ny});async function sy(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function ay(t,e){let{mapView:r}=je(e);return await sy(r)}var iy=c.object({}),ly=$(ay,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:iy});async function uy(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function cy({layerId:t},e){let{mapView:r}=je(e);return await uy(t,r)}var dy=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),py=$(cy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:dy});async function my(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function fy({scale:t},e){let{mapView:r}=je(e);return await my(t,r)}var hy=c.object({scale:c.number().describe("The map scale of the view to go to.")}),gy=$(fy,{name:"goToScale",description:"Go to the specified view scale.",schema:hy});async function yy(t,e,r){let n={target:new kd({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function _y({center:t,zoom:e,scale:r},n){let{mapView:o}=je(n);return await yy(t,o,{zoom:e,scale:r})}var wy=c.object({center:c.object({longitude:c.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:c.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:c.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:c.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),by=$(_y,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:wy});async function xy(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Ay({zoom:t},e){let{mapView:r}=je(e);return await xy(t,r)}var Iy=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),vy=$(Ay,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:Iy}),vd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function Ye(t){let e=Object.entries(vd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
76
+ Description: {description}`,gd=v.object({schemaVersion:v.literal(dd),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(pd),model:v.literal(md),dimensions:v.literal(Nn),templates:v.object({layer:v.string().default(fd),field:v.string().default(hd)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Nn,{message:`Layer vector must be exactly ${Nn} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Nn,{message:`Field vector must be exactly ${Nn} dimensions`})}))})).default([])});var rg=(t,e)=>{let r=al.fromTemplate(t);return fr.fromMessages([r,...e])};var To=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=rg(e,o??[]),l=(await mi({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var ng=c.object({name:c.string(),description:c.string(),valueType:c.string(),alias:c.string()}),TK=c.object({fields:c.array(ng)});var SK=c.object({title:c.string(),description:c.string(),name:c.string().nullable()});var _d=t=>Array.isArray(t)&&t.every(Wn),sg=t=>typeof t=="object"&&t!=null&&"messages"in t&&_d(t.messages),ag=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,Qe=class extends il{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e,r){let n=this.tools.find(o=>o.name===t.name);try{if(n===void 0)throw new Error(`Tool "${t.name}" not found.`);let o={...t,type:"tool_call"},s={...e,state:r,toolCallId:t.id??"",config:e,context:e.context,store:e.store??null,writer:e.writer??e.configurable?.writer??null},a=await n.invoke(o,s);return Wn(a)&&a.getType()==="tool"||vt(a)?a:new U({status:"success",name:n.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||$o(o))throw o;return new U({status:"error",content:`Error: ${o.message}
77
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(ag(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(_d(t))s=t;else if(sg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(et(l)){i=l;break}}if(i==null||!et(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(vt))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)vt(s)?s.graph===Le.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Ki(a))?o?o.goto.push(...s.goto):o=new Le({graph:Le.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var kG=O.Root({llmInputMessages:O({reducer:(t,e)=>Hn([],e),default:()=>[]})});var So=(t,e)=>e??t,qg=O.Root({...Ls(),intent:O({reducer:So}),vectorSearchLayerResults:O({reducer:So,default:()=>[]}),vectorSearchFieldResults:O({reducer:So}),navigationInternalState:O({reducer:So,default:()=>({toolCallMessage:void 0})})});async function Bg(t,e){let r=ur.getDefault().helperServices,n=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${fi.assetsPath?.endsWith("/")?fi.assetsPath:`${fi.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await ug(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new cg({url:s,width:24,height:24}),u=new lg({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var Kg=["mapView"];function je(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=Kg.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Gg({address:t},e){let{mapView:r}=je(e);return await Bg(t,r)}var Wg=c.object({address:c.string().describe("The full address or place name to locate.")}),Vg=$(Gg,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Wg});async function Hg(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Jg({bookmarkName:t},e){let{mapView:r}=je(e);return await Promise.resolve(Hg(t,r))}var Zg=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),Qg=$(Jg,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Zg});async function Yg(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function Xg({layerId:t,where:e},r){let{mapView:n}=je(r);return await Yg(t,e,n)}var ey=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),ty=$(Xg,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:ey});async function ry(t){let e=new dg({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await t.goTo(e),{text:"Successfully zoomed to world extent"}}async function ny(t,e){let{mapView:r}=je(e);return await ry(r)}var oy=v.object({}),sy=$(ny,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:oy});async function ay(t){let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;if(e)await t.goTo(e);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function iy(t,e){let{mapView:r}=je(e);return await ay(r)}var ly=c.object({}),uy=$(iy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:ly});async function cy(t,e){await e.when();let r=e.map?.allLayers.find(o=>o.id===t);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${t}`),{text:`Could not find layer for: ${t}`};let n;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&e.map?.activeLinkChartLayer?n=e.map.diagramNodesExtent:n=r.fullExtent,n?(await e.goTo(n),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function dy({layerId:t},e){let{mapView:r}=je(e);return await cy(t,r)}var py=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),my=$(dy,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:py});async function fy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function hy({scale:t},e){let{mapView:r}=je(e);return await fy(t,r)}var gy=c.object({scale:c.number().describe("The map scale of the view to go to.")}),yy=$(hy,{name:"goToScale",description:"Go to the specified view scale.",schema:gy});async function _y(t,e,r){let n={target:new kd({longitude:t.longitude,latitude:t.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(n.zoom=r.zoom),r?.scale!==void 0&&(n.scale=r.scale),await e.goTo(n),{text:`Successfully navigated to: ${[`(${t.latitude}\xB0, ${t.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function wy({center:t,zoom:e,scale:r},n){let{mapView:o}=je(n);return await _y(t,o,{zoom:e,scale:r})}var by=c.object({center:c.object({longitude:c.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:c.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:c.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:c.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),xy=$(wy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:by});async function Ay(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Iy({zoom:t},e){let{mapView:r}=je(e);return await Ay(t,r)}var vy=c.object({zoom:c.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Ty=$(Iy,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:vy}),vd=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function Ye(t){let e=Object.entries(vd).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
78
78
  Available prompts:
79
79
  ${Object.keys(vd).join(`
80
- `)}`);return await e[1]()}var Dn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Ty(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=pg({basemapTheme:await xd(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=mg({basemapTheme:await xd(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function Sy(t){return await dg(t)}async function ky({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await Ty(u),d=await Sy(l);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Cy=["mapView"];function Ce(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Cy.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Ey({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await ky({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Py=c.object({layerId:c.string().describe("The id of the layer to apply the chart renderer to"),fields:c.array(c.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Oy=$(Ey,{name:"chart",description:`Label: Charts
80
+ `)}`);return await e[1]()}var Dn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Sy(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=mg({basemapTheme:await xd(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=fg({basemapTheme:await xd(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function ky(t){return await pg(t)}async function Cy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await Sy(u),d=await ky(l);return i.renderer=d.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var Ey=["mapView"];function Ce(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Ey.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Py({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Cy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Oy=c.object({layerId:c.string().describe("The id of the layer to apply the chart renderer to"),fields:c.array(c.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),My=$(Py,{name:"chart",description:`Label: Charts
81
81
  Description: Show the values of two or more categories as a proportion of the total using a pie chart.
82
82
  Keywords: pie, chart, all categories, breakdown, proportion
83
83
  Example: Show the total number of homes built in each decade using a pie chart for each feature.
@@ -87,19 +87,19 @@ ${Object.keys(vd).join(`
87
87
  Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
88
88
  Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
89
89
  Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
90
- Fields: This style requires 2-8 number fields.`,schema:Py});function My(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=vi({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function Ry(t){return await fg(t)}async function $y({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=My(u),d=await Ry(l);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Ny({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await $y({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var zy=c.object({layerId:c.string().describe("The id of the layer to apply the color-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),jy=$(Ny,{name:"color-age",description:`Label: Age (color)
90
+ Fields: This style requires 2-8 number fields.`,schema:Oy});function Ry(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=vi({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function $y(t){return await hg(t)}async function Ny({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Ry(u),d=await $y(l);return i.renderer=d.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function zy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Ny({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var jy=c.object({layerId:c.string().describe("The id of the layer to apply the color-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Ly=$(zy,{name:"color-age",description:`Label: Age (color)
91
91
  Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
92
92
  Keywords: since, age, how old, how long
93
93
  Example: Show the age of each feature based on its reported date.
94
- Fields: This style requires at least one field with a date type.`,schema:zy});function Ly(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=vi({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function Dy(t){return await hg(t)}async function Fy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Ly(u),d=await Dy(l);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function Uy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Fy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var qy=c.object({layerId:c.string().describe("The id of the layer to apply the color renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),By=$(Uy,{name:"color",description:`Label: Counts and Amounts (color)
94
+ Fields: This style requires at least one field with a date type.`,schema:jy});function Dy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=vi({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function Fy(t){return await gg(t)}async function Uy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Dy(u),d=await Fy(l);return i.renderer=d.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function qy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Uy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var By=c.object({layerId:c.string().describe("The id of the layer to apply the color renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the color renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Ky=$(qy,{name:"color",description:`Label: Counts and Amounts (color)
95
95
  Description: Vary color along a continuous color ramp to represent numeric or ranked data.
96
96
  Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
97
97
  Example: Color each feature based on the population density.
98
- Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:qy});function Ky(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=vi({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function Gy(t){return await gg(t)}async function Wy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Ky(u),d=await Gy(l);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function Vy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Wy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Hy=c.object({layerId:c.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:c.array(c.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Jy=$(Vy,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
98
+ Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:By});function Gy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=vi({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function Wy(t){return await yg(t)}async function Vy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Gy(u),d=await Wy(l);return i.renderer=d.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function Hy({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await Vy({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Jy=c.object({layerId:c.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:c.array(c.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Zy=$(Hy,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
99
99
  Description: Vary symbol size and color based on the values of two numeric attributes.
100
100
  Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
101
101
  Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
102
- Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:Hy});function Zy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=_g({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function Qy(t){return await yg(t)}async function Yy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=Zy(i),l=await Qy(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function Xy({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await Yy({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var e_=c.object({layerId:c.string().describe("The id of the layer to apply the dot density renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),t_=$(Xy,{name:"dot-density",description:`Dot Density
102
+ Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:Jy});function Qy(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=wg({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function Yy(t){return await _g(t)}async function Xy({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=Qy(i),l=await Yy(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function e_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await Xy({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var t_=c.object({layerId:c.string().describe("The id of the layer to apply the dot density renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),r_=$(e_,{name:"dot-density",description:`Dot Density
103
103
  Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
104
104
  **Use cases:**
105
105
  - Population distribution visualization
@@ -110,11 +110,11 @@ ${Object.keys(vd).join(`
110
110
  - Visualize distribution of different crops across regions
111
111
  - Display demographic patterns within census tracts
112
112
  **Fields:** Requires 2-8 number fields.
113
- **Keywords:** density, how much, how many, total, number, amount`,schema:e_});function r_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=bg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function n_(t){return await wg(t)}async function o_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=r_(i),l=await n_(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function s_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await o_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var a_=c.object({layerId:c.string().describe("The id of the layer to apply the heatmap renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),i_=$(s_,{name:"heatmap",description:`Label: Heat Map
113
+ **Keywords:** density, how much, how many, total, number, amount`,schema:t_});function n_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=xg({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function o_(t){return await bg(t)}async function s_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=n_(i),l=await o_(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function a_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await s_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var i_=c.object({layerId:c.string().describe("The id of the layer to apply the heatmap renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),l_=$(a_,{name:"heatmap",description:`Label: Heat Map
114
114
  Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
115
115
  Keywords: density, heatmap, hot spots, pattern, cluster
116
116
  Example: Create a heatmap
117
- Fields: This typically requires zero or one field of type number.`,schema:a_});function l_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Ag({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function u_(t){return await xg(t)}async function c_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=l_(u),d=await u_(l);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function d_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await c_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var p_=c.object({layerId:c.string().describe("The id of the layer to apply the predominance renderer to"),fields:c.array(c.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),m_=$(d_,{name:"predominance",description:`Label: Predominant category
117
+ Fields: This typically requires zero or one field of type number.`,schema:i_});function u_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Ig({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function c_(t){return await Ag(t)}async function d_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=u_(u),d=await c_(l);return i.renderer=d.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function p_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await d_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var m_=c.object({layerId:c.string().describe("The id of the layer to apply the predominance renderer to"),fields:c.array(c.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),includeSize:c.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),f_=$(p_,{name:"predominance",description:`Label: Predominant category
118
118
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
119
119
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
120
120
  Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
@@ -124,15 +124,15 @@ Fields: This typically requires zero or one field of type number.`,schema:a_});f
124
124
  Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
125
125
  Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
126
126
  Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
127
- Fields: This style relies on 2-10 number fields.`,schema:p_});function f_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=vg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function h_(t){return await Ig(t)}async function g_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=f_(i),l=await h_(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function y_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await g_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var __=c.object({layerId:c.string().describe("The id of the layer to apply the relationship renderer to"),fields:c.array(c.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),w_=$(y_,{name:"relationship",description:`Label: Relationship
127
+ Fields: This style relies on 2-10 number fields.`,schema:m_});function h_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=Tg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function g_(t){return await vg(t)}async function y_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=h_(i),l=await g_(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function __({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ce(n);return await me({type:"show-legend",data:{layerIds:[t]}},n),await y_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var w_=c.object({layerId:c.string().describe("The id of the layer to apply the relationship renderer to"),fields:c.array(c.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use")}),b_=$(__,{name:"relationship",description:`Label: Relationship
128
128
  Description: Overlays two color ramps to represent the relationship between two numeric attributes.
129
129
  Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
130
130
  Example: Show the relationship between tree height and carbon storage
131
- Fields: This style requires two number fields.`,schema:__});function b_(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function x_(t){return await Tg(t)}async function A_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=b_(u),d=await x_(l);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function I_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await A_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var v_=c.object({layerId:c.string().describe("The id of the layer to apply the size-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),T_=$(I_,{name:"size-age",description:`Label: Age (size)
131
+ Fields: This style requires two number fields.`,schema:w_});function x_(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function A_(t){return await Sg(t)}async function I_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=x_(u),d=await A_(l);return i.renderer=d.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function v_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await I_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var T_=c.object({layerId:c.string().describe("The id of the layer to apply the size-age renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),S_=$(v_,{name:"size-age",description:`Label: Age (size)
132
132
  Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
133
133
  Keywords: since, age, how old, how long
134
134
  Example: Change the size of features so older features are larger than new features.
135
- Fields: This style requires at least one field with a date type.`,schema:v_});function S_(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function k_(t){return await Sg(t)}async function C_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=S_(u),d=await k_(l);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function E_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await C_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var P_=c.object({layerId:c.string().describe("The id of the layer to apply the size renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),O_=$(E_,{name:"size",description:`Label: Counts and Amounts (size)
135
+ Fields: This style requires at least one field with a date type.`,schema:T_});function k_(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function C_(t){return await kg(t)}async function E_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=k_(u),d=await C_(l);return i.renderer=d.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function P_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await E_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var O_=c.object({layerId:c.string().describe("The id of the layer to apply the size renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),M_=$(P_,{name:"size",description:`Label: Counts and Amounts (size)
136
136
  Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
137
137
  Keywords: graduated size, proportional size, how much, total, number, amount, size
138
138
  Example: Vary the size of each point based on the total population.
@@ -142,11 +142,11 @@ Fields: This typically requires zero or one field of type number.`,schema:a_});f
142
142
  Description: Vary symbol sizes along a continuous ramp to represent dates.
143
143
  Keywords: graduated size, proportional size, classed size, how much, total, number, when
144
144
  Example: Vary the size of each feature based on the date a ticket was completed.
145
- Fields: This style requires a single field with a date type.`,schema:P_});function M_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Cg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function R_(t){return await kg(t)}async function $_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=M_(u),d=await R_(l);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function N_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await $_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var z_=c.object({layerId:c.string().describe("The id of the layer to apply the type renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),j_=$(N_,{name:"type",description:`Label: Types (unique symbols)
145
+ Fields: This style requires a single field with a date type.`,schema:O_});function R_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Eg({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function $_(t){return await Cg(t)}async function N_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=R_(u),d=await $_(l);return i.renderer=d.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function z_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ce(o);return await me({type:"show-legend",data:{layerIds:[t]}},o),await N_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var j_=c.object({layerId:c.string().describe("The id of the layer to apply the type renderer to"),fields:c.array(c.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:c.array(c.string()).optional().describe("Optional color scheme tags to use"),theme:c.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),L_=$(z_,{name:"type",description:`Label: Types (unique symbols)
146
146
  Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
147
147
  Keywords: categorical, category, type, unique, discrete, point of interest, region, group
148
148
  Example: Color each feature based on the region it belongs to
149
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:z_}),L_=O.Root({...lr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),selectedLayerId:O()}),D_=O.Root({...lr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),queryResponse:O(),dataExplorationMessages:O({reducer:Hn,default:()=>[]})}),F_=["mapView"];function At(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=F_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var U_=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},q_=async(t,e)=>{let{mapView:r}=At(e);return U_(r)},N2=$(q_,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:c.object({})}),B_=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},K_=async(t,e)=>{let{mapView:r}=At(e);return await B_(r)},z2=$(K_,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:c.object({})}),Td=750;function qs(t){return"point"in t&&t.point!==void 0}function ko(t){return"layerId"in t&&t.layerId!==void 0}var Gs=async(t,e)=>{if(qs(t)){let{point:r}=t;return{geometry:new kd({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(ko(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Td+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Td)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:Ed.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},G_=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},W_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(m=>m.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let m=await Gs(o,e);if("error"in m)return m.error;i=m.geometry}if(a.featureEffect=null,a.featureEffect=new Eg({filter:new Cd({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await G_(e,t.layerId,u,i,o?.distance,o?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},V_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],It=c.enum(V_),H_=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=At(s);return await W_(t,a,n,o,e,r)},J_=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Z_=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Q_=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer on which to set a feature effect."),where:c.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:c.array(c.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:c.union([J_,Z_]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:c.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:c.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:c.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),j2=$(H_,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Q_}),Y_=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Od=t=>{if(!t)return!1;let e=t.toLowerCase();return Y_.has(e)},gi=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},X_=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,ew=t=>{if(typeof t=="string"&&t)return t;let e=gi(t);return e?e.toISOString().slice(0,10):null};var tw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Od(n))return t;if(n==="date-only"){let s=ew(t);return s?Pg(s,Ds("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Og(t,Ds("long-time"));let s=gi(t);return s?Ad(s,{...Ds("long-time"),timeZone:"UTC"}):t}let o=gi(t);return o?Ad(o,{...Ds("short-date-short-time"),timeZone:X_(r)}):t},Md=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},rw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,nw=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},ow=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},sw=(t,e,r)=>{let n=nw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=rw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Rd=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,$d=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?ow(r,s):s?.type==="date-time"?!n||Od(n)?sw(r,s,o):r:tw(r,n,o)},aw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Md(e,r,t)??r;return $d(t,e,s,o?.type,n)},iw=(t,e)=>Rd(t,e),Nd=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let d=i[l.name];if(l.name===n){u[l.name]=d;return}let m=Md(l.name,d,t)??d,f=Rd(t,l.name);u[f]=$d(t,l.name,m,l.type,r)}),u});return{objectIds:o,attributes:s}},lw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},uw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(d=>d.id===t),s=lw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=aw(o,e,i,n.timeZone),l=iw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function cw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=At(n),s=await uw(t,e,r,o);return JSON.stringify(s,null,2)}var dw=c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:c.string().describe("The name of the field/attribute from which to get a field value."),query:c.object({where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),pw=$(cw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:dw}),Ti=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function Bs(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var mw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(h=>h.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(a){let h=await Gs(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw ko(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(ko(a)){let x=o.map?.allLayers.find(S=>S.id===a.layerId);m={geometryLayerName:x?.title??x?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else qs(a)&&(m={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new Cd({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let I=Ti(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Bs(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await Mg(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await Rg({layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Bs(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((E,F)=>F.count-E.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(E=>({...E,value:S?S.getName(E.value)??E.value:E.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:m}}};async function fw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Dn(o,"layersAndFieldsRegistry"),{mapView:a}=At(o),i=await mw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var hw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),gw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),yw=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:c.union([hw,gw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:c.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:c.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),_w=$(fw,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
149
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:j_}),D_=O.Root({...lr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),selectedLayerId:O()}),F_=O.Root({...lr(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),queryResponse:O(),dataExplorationMessages:O({reducer:Hn,default:()=>[]})}),U_=["mapView"];function At(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=U_.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var q_=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},B_=async(t,e)=>{let{mapView:r}=At(e);return q_(r)},jW=$(B_,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:c.object({})}),K_=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},G_=async(t,e)=>{let{mapView:r}=At(e);return await K_(r)},LW=$(G_,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:c.object({})}),Td=750;function qs(t){return"point"in t&&t.point!==void 0}function ko(t){return"layerId"in t&&t.layerId!==void 0}var Gs=async(t,e)=>{if(qs(t)){let{point:r}=t;return{geometry:new kd({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(ko(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Td+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Td)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:Ed.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},W_=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},V_=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(m=>m.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let m=await Gs(o,e);if("error"in m)return m.error;i=m.geometry}if(a.featureEffect=null,a.featureEffect=new Pg({filter:new Cd({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await W_(e,t.layerId,u,i,o?.distance,o?.units),d=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${l.error}`},H_=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],It=c.enum(H_),J_=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=At(s);return await V_(t,a,n,o,e,r)},Z_=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Q_=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Y_=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer on which to set a feature effect."),where:c.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:c.array(c.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:c.union([Z_,Q_]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:c.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:c.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:c.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),DW=$(J_,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Y_}),X_=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Od=t=>{if(!t)return!1;let e=t.toLowerCase();return X_.has(e)},gi=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},ew=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,tw=t=>{if(typeof t=="string"&&t)return t;let e=gi(t);return e?e.toISOString().slice(0,10):null};var rw=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Od(n))return t;if(n==="date-only"){let s=tw(t);return s?Og(s,Ds("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Mg(t,Ds("long-time"));let s=gi(t);return s?Ad(s,{...Ds("long-time"),timeZone:"UTC"}):t}let o=gi(t);return o?Ad(o,{...Ds("short-date-short-time"),timeZone:ew(r)}):t},Md=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},nw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,ow=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},sw=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},aw=(t,e,r)=>{let n=ow(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=nw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Rd=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,$d=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?sw(r,s):s?.type==="date-time"?!n||Od(n)?aw(r,s,o):r:rw(r,n,o)},iw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Md(e,r,t)??r;return $d(t,e,s,o?.type,n)},lw=(t,e)=>Rd(t,e),Nd=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let d=i[l.name];if(l.name===n){u[l.name]=d;return}let m=Md(l.name,d,t)??d,f=Rd(t,l.name);u[f]=$d(t,l.name,m,l.type,r)}),u});return{objectIds:o,attributes:s}},uw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},cw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(d=>d.id===t),s=uw(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=iw(o,e,i,n.timeZone),l=lw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function dw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=At(n),s=await cw(t,e,r,o);return JSON.stringify(s,null,2)}var pw=c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:c.string().describe("The name of the field/attribute from which to get a field value."),query:c.object({where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),mw=$(dw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:pw}),Ti=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function Bs(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var fw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(h=>h.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),d=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(a){let h=await Gs(a,o);if("error"in h)throw new Error(h.error);if(!h.geometry)throw ko(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(ko(a)){let x=o.map?.allLayers.find(S=>S.id===a.layerId);m={geometryLayerName:x?.title??x?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else qs(a)&&(m={point:a.point,distance:a.distance,units:a.units,applied:!0});f=new Cd({geometry:h.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let I=Ti(u,[r],!1),w=null,b=null,y=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let h={layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Bs(i.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await Rg(h);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await $g({layer:i,useFeaturesInView:I,view:I?o:void 0,field:r,sqlWhere:Bs(i.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((E,F)=>F.count-E.count).slice(0,y)),b&&l.domain?.type==="coded-value"&&(b=b.map(E=>({...E,value:S?S.getName(E.value)??E.value:E.value})))}catch(h){console.error("Statistics error:",h)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:m}}};async function hw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Dn(o,"layersAndFieldsRegistry"),{mapView:a}=At(o),i=await fw({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var gw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),yw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),_w=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:c.union([gw,yw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:c.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:c.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),ww=$(hw,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
150
150
 
151
151
  USE THIS TOOL FOR:
152
152
  - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
@@ -158,7 +158,7 @@ DO NOT USE FOR:
158
158
  - "Show / list / find features" \u2014 use queryFeatures instead
159
159
  - Simple counts of features matching a condition \u2014 use queryFeatures instead
160
160
 
161
- Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:yw}),ww=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),bw=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let f=await Gs(n,r);if("error"in f)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=f.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new $g({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Ng({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=Bs(s.definitionExpression,t.where||"1=1"),b.outFields=m.length?m:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),n?.distance&&(b.distance=n.distance),n?.units&&(b.units=n.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...ww(e.orderByFields)])],h=Ti(a,y,o??!1);try{f=h?await a.queryFeatures(b):await s.queryFeatures(b)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(b)}}let I=f.features.map(b=>b.attributes[d]),{attributes:w}=Nd(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:I,objectIdField:d,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},xw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=At(o),a=await bw(t,e,s,r,n);return JSON.stringify(a,null,2)},Aw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Iw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),vw=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([Aw,Iw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:c.object({topCount:c.number().describe("Number of top features to return per group."),orderByFields:c.array(c.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:c.array(c.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),Tw=$(xw,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:vw}),hi=25,Sw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),kw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let y=await Gs(r,e);if("error"in y){let h={error:y.error};if(ko(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else qs(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!y.geometry){let h={};if(ko(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else qs(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=y.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...Sw(t.orderByFields)])],l=Ti(s,u,n??!1),d=o.objectIdField,m=o.createQuery();m.where=Bs(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],m.orderByFields=t.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,I;try{f=l?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=hi&&(I=l?await s.queryFeatures(m):await o.queryFeatures(m))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await o.queryFeatureCount(m),f>0&&f<=hi&&(I=await o.queryFeatures(m))}let{objectIds:w,attributes:b}=I?Nd(o,I,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...w&&{objectIds:w,objectIdField:d},...b&&{attributes:b},...f>hi&&{note:`${f} features found.`}}}};async function Cw({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=At(n),s=await kw(t,o,e,r);return JSON.stringify(s,null,2)}var Ew=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Pw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Ow=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([Ew,Pw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),Mw=$(Cw,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
161
+ Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:_w}),bw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),xw=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let f=await Gs(n,r);if("error"in f)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=f.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(l){let b=new Ng({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new zg({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=Bs(s.definitionExpression,t.where||"1=1"),b.outFields=m.length?m:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,u&&(b.geometry=u,b.spatialRelationship="intersects"),n?.distance&&(b.distance=n.distance),n?.units&&(b.units=n.units),b.outSpatialReference=r.spatialReference;let y=[...new Set([...t.outFields,...bw(e.orderByFields)])],h=Ti(a,y,o??!1);try{f=h?await a.queryFeatures(b):await s.queryFeatures(b)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(b)}}let I=f.features.map(b=>b.attributes[d]),{attributes:w}=Nd(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:I,objectIdField:d,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},Aw=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=At(o),a=await xw(t,e,s,r,n);return JSON.stringify(a,null,2)},Iw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),vw=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Tw=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([Iw,vw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:c.object({topCount:c.number().describe("Number of top features to return per group."),orderByFields:c.array(c.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:c.array(c.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),Sw=$(Aw,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:Tw}),hi=25,kw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Cw=async(t,e,r,n)=>{let o=e.map?.allLayers.find(y=>y.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let y=await Gs(r,e);if("error"in y){let h={error:y.error};if(ko(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else qs(r)&&(h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:h}}if(!y.geometry){let h={};if(ko(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);h.error=`No features found matching: ${r.where}`,h.geometryLayerName=x?.title??x?.id,h.geometryLayerId=r.layerId,h.geometryWhere=r.where}else qs(r)&&(h.error="Failed to create point geometry",h.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:h}}i=y.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...kw(t.orderByFields)])],l=Ti(s,u,n??!1),d=o.objectIdField,m=o.createQuery();m.where=Bs(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],m.orderByFields=t.orderByFields,i&&(m.geometry=i,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,I;try{f=l?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=hi&&(I=l?await s.queryFeatures(m):await o.queryFeatures(m))}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await o.queryFeatureCount(m),f>0&&f<=hi&&(I=await o.queryFeatures(m))}let{objectIds:w,attributes:b}=I?Nd(o,I,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...w&&{objectIds:w,objectIdField:d},...b&&{attributes:b},...f>hi&&{note:`${f} features found.`}}}};async function Ew({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=At(n),s=await Cw(t,o,e,r);return JSON.stringify(s,null,2)}var Pw=c.object({layerId:c.string().describe("The layerId of the layer containing the geometry by which to filter."),where:c.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:c.number().optional().describe("The buffer distance around the geometry."),units:It.optional().describe("The units for the distance buffer.")}),Ow=c.object({point:c.object({x:c.number().describe("X coordinate (longitude) from navigation result"),y:c.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:c.object({wkid:c.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:c.number().optional().describe("Optional buffer distance around the point."),units:It.optional().describe("The units for the distance buffer.")}),Mw=c.object({targetLayer:c.object({layerId:c.string().describe("The layerId of the layer containing the field from which to get a value."),where:c.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:c.array(c.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:c.array(c.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:c.union([Pw,Ow]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:c.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),Rw=$(Ew,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
162
162
 
163
163
  USE THIS TOOL FOR:
164
164
  - "Show / display / list features where..." \u2014 finding and listing features
@@ -167,26 +167,26 @@ USE THIS TOOL FOR:
167
167
  - Spatial queries \u2014 finding features near/within/intersecting other features
168
168
  - Any question where the user wants to SEE or COUNT matching features
169
169
 
170
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Ow}),zd=[pw,_w,Tw,Mw];var L2=new Qe(zd,{handleToolErrors:!1});var Rw=O.Root({...lr(),helpInternalState:O({reducer:So,default:()=>({toolCallMessage:void 0})})}),$w=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
170
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Mw}),zd=[mw,ww,Sw,Rw];var FW=new Qe(zd,{handleToolErrors:!1});var $w=O.Root({...lr(),helpInternalState:O({reducer:So,default:()=>({toolCallMessage:void 0})})}),Nw=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
171
171
  `);return`**${r.layerItem.title}** has ${n.length} field(s):
172
172
 
173
- ${o}`},Nw=async({layerTitle:t},e)=>{let r=Dn(e,"layersAndFieldsRegistry");return $w(r,t)},zw=$(Nw,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:c.object({layerTitle:c.string().describe("The title or partial title of the layer to list fields for.")})}),jw=O.Root({...lr(),intent:O({reducer:(t,e)=>e}),arcgisKnowledgeMessages:O({reducer:Hn,default:()=>[]}),arcgisKnowledgeToolResult:O({reducer:(t,e)=>e,default:()=>null})});function jd(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function Fn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function Ws(t){!t||Fn(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Eo(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&jd(r),{view:r}}async function Un(t){let e=t?.configurable?.context;if(Lw(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Id(n)}}else{jd(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Id(n)}}}}function Lw(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var yi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Ks.fromDataModel(e)}},Ks=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let n of e.entityTypes)r.entityTypes.push(Co.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(_i.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Dw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
174
- Relationship Types: ${n}.`}},Co=class t{constructor(){this.name="",this.properties=[]}static fromEntityType(e){let r=new t;r.name=e.name,r.alias=e.alias?e.alias:void 0,r.role=Fw(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:Uw(n.role),geometryDef:n.fieldType==="esriFieldTypeGeometry"?{geometryType:n.geometryType??"esriGeometryAny",hasM:n.hasM?n.hasM:void 0,hasZ:n.hasZ?n.hasZ:void 0}:void 0};r.properties.push(o)}return r}},_i=class extends Co{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Co.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},Dw=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Fw=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function Uw(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function Vs(t){return t?.signal}async function qw(t,e){let r=await Ye("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
173
+ ${o}`},zw=async({layerTitle:t},e)=>{let r=Dn(e,"layersAndFieldsRegistry");return Nw(r,t)},jw=$(zw,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:c.object({layerTitle:c.string().describe("The title or partial title of the layer to list fields for.")})}),Lw=O.Root({...lr(),intent:O({reducer:(t,e)=>e}),arcgisKnowledgeMessages:O({reducer:Hn,default:()=>[]}),arcgisKnowledgeToolResult:O({reducer:(t,e)=>e,default:()=>null})});function jd(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function Fn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function Ws(t){!t||Fn(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Eo(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&jd(r),{view:r}}async function Un(t){let e=t?.configurable?.context;if(Dw(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Id(n)}}else{jd(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Id(n)}}}}function Dw(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var yi=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Ks.fromDataModel(e)}},Ks=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let n of e.entityTypes)r.entityTypes.push(Co.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(_i.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:Fw(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
174
+ Relationship Types: ${n}.`}},Co=class t{constructor(){this.name="",this.properties=[]}static fromEntityType(e){let r=new t;r.name=e.name,r.alias=e.alias?e.alias:void 0,r.role=Uw(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:qw(n.role),geometryDef:n.fieldType==="esriFieldTypeGeometry"?{geometryType:n.geometryType??"esriGeometryAny",hasM:n.hasM?n.hasM:void 0,hasZ:n.hasZ?n.hasZ:void 0}:void 0};r.properties.push(o)}return r}},_i=class extends Co{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Co.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},Fw=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},Uw=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function qw(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function Vs(t){return t?.signal}async function Bw(t,e){let r=await Ye("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
175
175
 
176
176
  Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
177
177
 
178
178
  Attempt Number: ${e.attemptCount}
179
179
  Execution Error: ${e.executionError}
180
180
  Failed Query:
181
- ${e.failedGraphQuery}`:`${t} ${r}`}async function Bw(t,e,r,n){let{graphQuery:o,explanation:s}=await Si(t,e,r,n);return{graphQuery:o,explanation:s}}async function Si(t,e,r,n,o){let s={message:await qw(t,o),context:new yi(e)},a=Vs(n);await H({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await bd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:wd.findCredential(ur.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),d=i.data.sequenceNumber,m="",f="",I=1;for(;!u;){await new Promise(b=>setTimeout(b,1e3)),await H({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,I)}`},n),I=I%3+1;let w=await bd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:wd.findCredential(ur.getDefault().url)?.token??""},signal:a});if(w.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${w.httpStatus}`,{cause:w.data});if(w.data.context?.kind){if(w.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${w.data.message}`,{cause:w.data});m=w.data.context.graphQuery,f=w.data.message||"",u=!0}else if(!w.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=w.data.sequenceNumber}return{graphQuery:m,explanation:f}}function Kw(t,e){jn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function jn(t,e){if(!(!t||typeof t!="object")){if(Ww(t))for(let r of t.path)jn(r,e);else if(Gw(t))e(t);else if(Array.isArray(t))for(let r of t)jn(r,e);else if(Vw(t))for(let r of Object.values(t.properties??{}))jn(r,e)}}function Gw(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Ww(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Vw(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Hw(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function Jw(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let d=o.namedTypeDefinitions.get(l.name);if(!d){a=!1,n.push(l.name);continue}if(!d.useAllData){a=!1,n.push(l.name);for(let[m]of d.members||[])u.push(m)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var Ln=3;function Ld(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function qn(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var Zw=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,d=o?.signal,m=()=>{l.abort(d?.reason)};d&&(d.aborted?l.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let f=await jg(t,e,o);i=f.resultHeader;let I=f.resultRowsStream.getReader(),w=0,b=Date.now(),y=!1;for(;;){let{done:h,value:x}=await I.read();if(h)break;if(!y&&a&&Date.now()-b>a)return l.abort(),{type:"timeout"};for(let S of x){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,S)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:qn(f),error:f}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function Dd({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let d;for(let m=1;m<=Ln;m++){let f;try{f=await Si(t,r.dataModel,n,l,d)}catch(y){return{type:"generation-error",errorMessage:qn(y),error:y}}await H({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let I=await Qw(f.graphQuery,e),w=await Zw({kg:r,queryParams:new Pd({openCypherQuery:f.graphQuery,bindParameters:I}),targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),b=w.type==="aborted"?"Query execution was aborted.":w.type==="timeout"?"Query execution timed out.":w.type==="error"?`Query failed with error: ${w.errorMessage}`:"";if(w.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:w.rowLimitReached,resultHeader:w.resultHeader,processedResult:w.processedResult};if(w.type==="aborted")return{type:"aborted",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation};if(m>=Ln)return w.type==="timeout"?{type:"timeout",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:b,error:w.error,graphQuery:f.graphQuery,explanation:f.explanation};d={failedGraphQuery:f.graphQuery,executionError:b,attemptCount:m},await H({text:`Attempt ${m} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Ln} attempts.`)}var Qw=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await Fg(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},Yw=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let d=u-a.length;if(d<=0)break;let m=(await Lg(t,new Dg({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:I,value:w}=await m.read();if(I){f=!0;break}for(let b of w)for(let y of b)a.push(y)}}}catch(l){let d=qn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},Fd="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Ud({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(Fd),!Fn(e)&&e.map){let d=await Ye("arcgis_knowledge_current_lc_context"),m=Hw(e.map,r);return o.push(d),{enhancedPrompt:o.join(`
181
+ ${e.failedGraphQuery}`:`${t} ${r}`}async function Kw(t,e,r,n){let{graphQuery:o,explanation:s}=await Si(t,e,r,n);return{graphQuery:o,explanation:s}}async function Si(t,e,r,n,o){let s={message:await Bw(t,o),context:new yi(e)},a=Vs(n);await H({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await bd(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:wd.findCredential(ur.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),d=i.data.sequenceNumber,m="",f="",I=1;for(;!u;){await new Promise(b=>setTimeout(b,1e3)),await H({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,I)}`},n),I=I%3+1;let w=await bd(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json",token:wd.findCredential(ur.getDefault().url)?.token??""},signal:a});if(w.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${w.httpStatus}`,{cause:w.data});if(w.data.context?.kind){if(w.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${w.data.message}`,{cause:w.data});m=w.data.context.graphQuery,f=w.data.message||"",u=!0}else if(!w.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=w.data.sequenceNumber}return{graphQuery:m,explanation:f}}function Gw(t,e){jn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function jn(t,e){if(!(!t||typeof t!="object")){if(Vw(t))for(let r of t.path)jn(r,e);else if(Ww(t))e(t);else if(Array.isArray(t))for(let r of t)jn(r,e);else if(Hw(t))for(let r of Object.values(t.properties??{}))jn(r,e)}}function Ww(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Vw(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Hw(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Jw(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function Zw(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let d=o.namedTypeDefinitions.get(l.name);if(!d){a=!1,n.push(l.name);continue}if(!d.useAllData){a=!1,n.push(l.name);for(let[m]of d.members||[])u.push(m)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var Ln=3;function Ld(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function qn(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var Qw=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,d=o?.signal,m=()=>{l.abort(d?.reason)};d&&(d.aborted?l.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let f=await Lg(t,e,o);i=f.resultHeader;let I=f.resultRowsStream.getReader(),w=0,b=Date.now(),y=!1;for(;;){let{done:h,value:x}=await I.read();if(h)break;if(!y&&a&&Date.now()-b>a)return l.abort(),{type:"timeout"};for(let S of x){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,S)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:qn(f),error:f}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function Dd({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let d;for(let m=1;m<=Ln;m++){let f;try{f=await Si(t,r.dataModel,n,l,d)}catch(y){return{type:"generation-error",errorMessage:qn(y),error:y}}await H({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let I=await Yw(f.graphQuery,e),w=await Qw({kg:r,queryParams:new Pd({openCypherQuery:f.graphQuery,bindParameters:I}),targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),b=w.type==="aborted"?"Query execution was aborted.":w.type==="timeout"?"Query execution timed out.":w.type==="error"?`Query failed with error: ${w.errorMessage}`:"";if(w.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:w.rowLimitReached,resultHeader:w.resultHeader,processedResult:w.processedResult};if(w.type==="aborted")return{type:"aborted",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation};if(m>=Ln)return w.type==="timeout"?{type:"timeout",errorMessage:b,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:b,error:w.error,graphQuery:f.graphQuery,explanation:f.explanation};d={failedGraphQuery:f.graphQuery,executionError:b,attemptCount:m},await H({text:`Attempt ${m} failed with error: ${b}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Ln} attempts.`)}var Yw=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await Ug(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},Xw=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let d=u-a.length;if(d<=0)break;let m=(await Dg(t,new Fg({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:I,value:w}=await m.read();if(I){f=!0;break}for(let b of w)for(let y of b)a.push(y)}}}catch(l){let d=qn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:l}:{type:"error",errorMessage:d,error:l}}return{type:"success",results:a}},Fd="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Ud({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(Fd),!Fn(e)&&e.map){let d=await Ye("arcgis_knowledge_current_lc_context"),m=Jw(e.map,r);return o.push(d),{enhancedPrompt:o.join(`
182
182
 
183
- `),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=Jw(s,r);if(a)return{enhancedPrompt:o.join(`
183
+ `),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=Zw(s,r);if(a)return{enhancedPrompt:o.join(`
184
184
 
185
185
  `),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await Ye("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return o.push(l),{enhancedPrompt:o.join(`
186
186
 
187
- `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function Xw(t,e,r,n,o,s){let{view:a}=o,i=await Dd({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,I)=>{for(let w of I)Kw(w,f);return f},requestOptions:{signal:Vs(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let f=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:u,explanation:l,processedResult:d}=i,m=Array.from(d.values());return await H({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Fn(a)&&a?.map?(await a.map.addRecords(m),await Ws(a),{generatedQuery:u,explanation:l,addedIdTypePairs:m}):(await a?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:u,explanation:l,addedIdTypePairs:m})}var Fs="addRecords",eb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),tb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=Eo(e),{view:o}=n,s=ur.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await Ud({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:Fs,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:d,addedIdTypePairs:m}=await Xw(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Fs,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
187
+ `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function eb(t,e,r,n,o,s){let{view:a}=o,i=await Dd({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,I)=>{for(let w of I)Gw(w,f);return f},requestOptions:{signal:Vs(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let f=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:u,explanation:l,processedResult:d}=i,m=Array.from(d.values());return await H({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Fn(a)&&a?.map?(await a.map.addRecords(m),await Ws(a),{generatedQuery:u,explanation:l,addedIdTypePairs:m}):(await a?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:u,explanation:l,addedIdTypePairs:m})}var Fs="addRecords",tb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),rb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=Eo(e),{view:o}=n,s=ur.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await Ud({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:Fs,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:d,addedIdTypePairs:m}=await eb(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Fs,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
188
188
 
189
- Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:m}}}catch(l){let d=qn(l);return{toolName:Fs,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},rb=$(tb,{name:Fs,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
189
+ Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,addedIdTypePairs:m}}}catch(l){let d=qn(l);return{toolName:Fs,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:l}}},nb=$(rb,{name:Fs,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
190
190
 
191
191
  example prompts:
192
192
  - "add all suppliers and the parts they produce to the link chart"
@@ -196,15 +196,15 @@ Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:d,ad
196
196
  - "expand company x through all the buildings it owns"
197
197
  - "connect company x and company y"
198
198
  - "connect all buildings on the link chart"
199
- `,schema:eb});async function nb(t,e){return await e.map?.applyLayout(t),await Ws(e),{appliedLayout:t}}var wi="applyLayout",ob=c.object({layout:c.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),sb=async({layout:t},e)=>{let{view:r}=Eo(e);if(Fn(r))return{toolName:wi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await nb(t,r);return{toolName:wi,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},ab=$(sb,{name:wi,description:"Apply a diagram layout to the link chart",schema:ob});async function ib(t,e){return e.map?.changeNonspatialDataDisplay(t),await Ws(e),{appliedNonspatialDataDisplayMode:t}}var bi="changeNonspatialVisibility",lb=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),ub=async({setting:t},e)=>{let{view:r}=Eo(e);if(Fn(r))return{toolName:bi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await ib(t,r);return{toolName:bi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},cb=$(ub,{name:bi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:lb});async function db(t,e,r,n,o){let s,a="";for(let i=1;i<=Ln;i++){let{graphQuery:u,explanation:l}=await Si(t,e.dataModel,r,o,s);try{await H({text:`Attempting to create link chart from derived query: ${u}`},o);let d=await zg.fromCypherQuery(e,new Pd({openCypherQuery:u}));await H({text:"Link chart created successfully, loading..."},o),await d.load();let m=n.map;return n.map=d,await n.when(),await Sd.whenOnce(()=>!n.updating),d.entityCount===0&&d.relationshipCount===0?(n.map===d&&(n.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
199
+ `,schema:tb});async function ob(t,e){return await e.map?.applyLayout(t),await Ws(e),{appliedLayout:t}}var wi="applyLayout",sb=c.object({layout:c.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),ab=async({layout:t},e)=>{let{view:r}=Eo(e);if(Fn(r))return{toolName:wi,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await ob(t,r);return{toolName:wi,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},ib=$(ab,{name:wi,description:"Apply a diagram layout to the link chart",schema:sb});async function lb(t,e){return e.map?.changeNonspatialDataDisplay(t),await Ws(e),{appliedNonspatialDataDisplayMode:t}}var bi="changeNonspatialVisibility",ub=c.object({setting:c.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),cb=async({setting:t},e)=>{let{view:r}=Eo(e);if(Fn(r))return{toolName:bi,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await lb(t,r);return{toolName:bi,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},db=$(cb,{name:bi,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:ub});async function pb(t,e,r,n,o){let s,a="";for(let i=1;i<=Ln;i++){let{graphQuery:u,explanation:l}=await Si(t,e.dataModel,r,o,s);try{await H({text:`Attempting to create link chart from derived query: ${u}`},o);let d=await jg.fromCypherQuery(e,new Pd({openCypherQuery:u}));await H({text:"Link chart created successfully, loading..."},o),await d.load();let m=n.map;return n.map=d,await n.when(),await Sd.whenOnce(()=>!n.updating),d.entityCount===0&&d.relationshipCount===0?(n.map===d&&(n.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
200
200
  ${u}
201
201
 
202
- Explanation: ${l}`}):(await Ws(n),{type:"success",graphQuery:u,explanation:l})}catch(d){let m=qn(d);if(i>=Ln){a=m;break}s={failedGraphQuery:u,executionError:m,attemptCount:i},await H({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Ln} attempts. Last error: ${a}`}}var Us="createLinkChart",pb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),mb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),{view:n}=Eo(e);if(Fn(n))return{toolName:Us,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=ur.getDefault().helperServices,s=await db(`${t}
202
+ Explanation: ${l}`}):(await Ws(n),{type:"success",graphQuery:u,explanation:l})}catch(d){let m=qn(d);if(i>=Ln){a=m;break}s={failedGraphQuery:u,executionError:m,attemptCount:i},await H({text:`Attempt ${i} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Ln} attempts. Last error: ${a}`}}var Us="createLinkChart",mb=c.object({prompt:c.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),fb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),{view:n}=Eo(e);if(Fn(n))return{toolName:Us,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=ur.getDefault().helperServices,s=await pb(`${t}
203
203
 
204
204
  ${Fd}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:Us,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:Us,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
205
205
  ${a}
206
206
 
207
- Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},fb=$(mb,{name:Us,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:pb}),xi="queryGraphData",hb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),gb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=ur.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Eo(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await Ud({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await Dd({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,y)=>(b.push(y),b),requestOptions:{signal:Vs(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let b=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:xi,status:"error",errorMessage:`Failed to query the knowledge graph. ${b}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:d,resultHeader:m}=i,f=m.headerKeys;for(let b of d)for(let y of b)jn(y,h=>Ld(h));let I=50,w=d.slice(0,I).map(b=>JSON.stringify(b));return{toolName:xi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
207
+ Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},hb=$(fb,{name:Us,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:mb}),xi="queryGraphData",gb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),yb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=ur.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=Eo(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await Ud({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await Dd({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,y)=>(b.push(y),b),requestOptions:{signal:Vs(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let b=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:xi,status:"error",errorMessage:`Failed to query the knowledge graph. ${b}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:d,resultHeader:m}=i,f=m.headerKeys;for(let b of d)for(let y of b)jn(y,h=>Ld(h));let I=50,w=d.slice(0,I).map(b=>JSON.stringify(b));return{toolName:xi,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
208
208
 
209
209
  \`\`\`cypher
210
210
  ${u}
@@ -221,16 +221,16 @@ ${w.length>I?`Showing top ${I} results:
221
221
 
222
222
  `}${w.join(`
223
223
  `)}
224
- `,details:{generatedQuery:u,explanation:l,resultHeader:m,queryResults:d}}},yb=$(gb,{name:xi,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:hb}),Ai="generateCypher",_b=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),wb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=ur.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await Bw(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Ai,status:"success",summary:`Generated Graph Query:
224
+ `,details:{generatedQuery:u,explanation:l,resultHeader:m,queryResults:d}}},_b=$(yb,{name:xi,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:gb}),Ai="generateCypher",wb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),bb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e),n=ur.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await Kw(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:Ai,status:"success",summary:`Generated Graph Query:
225
225
  ${o}
226
226
 
227
- Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=qn(o);return{toolName:Ai,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},bb=$(wb,{name:Ai,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:_b}),xb=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let d=r.get(u)??new Set;l.propertyNames.forEach(m=>d.add(m)),r.set(u,d)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
227
+ Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=qn(o);return{toolName:Ai,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},xb=$(bb,{name:Ai,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:wb}),Ab=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let d=r.get(u)??new Set;l.propertyNames.forEach(m=>d.add(m)),r.set(u,d)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
228
228
  ${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
229
229
  `)}`,a=`Relationship Types:
230
230
  ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
231
231
  `)}`;return`${s}
232
232
 
233
- ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:xb(e)},s=c.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=c.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=c.array(c.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=c.object({query:c.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await To({promptText:n,inputVariables:o,schema:u,config:r})}var Ii="searchGraphData",Ib=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),vb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e);await H({text:"Generating search query for the user inquiry"},e);let n=await Ab(t,r,e);await H({text:"Executing graph search with generated search query"},e);let o=await Yw({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:Vs(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Ii,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)jn(i,u=>Ld(u));let s=10,a=o.results.slice(0,s);return{toolName:Ii,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
233
+ ${a}`};async function Ib(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:Ab(e)},s=c.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=c.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=c.array(c.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=c.object({query:c.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await To({promptText:n,inputVariables:o,schema:u,config:r})}var Ii="searchGraphData",vb=c.object({prompt:c.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),Tb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Un(e);await H({text:"Generating search query for the user inquiry"},e);let n=await Ib(t,r,e);await H({text:"Executing graph search with generated search query"},e);let o=await Xw({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:Vs(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Ii,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)jn(i,u=>Ld(u));let s=10,a=o.results.slice(0,s);return{toolName:Ii,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
234
234
  Query: ${n.query}
235
235
  Type Category Filter: ${n.typeCategoryFilter}
236
236
  Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
@@ -241,7 +241,7 @@ ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generati
241
241
  ${o.results.length>s?`Showing top ${s} results:
242
242
 
243
243
  `:""}${a.map(i=>JSON.stringify(i)).join(`
244
- `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},Tb=$(vb,{name:Ii,description:`
244
+ `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},Sb=$(Tb,{name:Ii,description:`
245
245
  Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
246
246
  Example prompts:
247
247
  - "Find 'Bradley'"
@@ -250,7 +250,7 @@ ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generati
250
250
  - "Find all references to 'delayed parts shipment'"
251
251
  - "Find all reports authored by someone with the title of 'Researcher'"
252
252
  - "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
253
- - "Search for all john smiths and show their global ids`,schema:Ib});var tW=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
253
+ - "Search for all john smiths and show their global ids`,schema:vb});var n2=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
254
254
  This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
255
255
 
256
256
  Supported actions:
@@ -269,11 +269,11 @@ ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generati
269
269
  _Example: “Center the map on San Francisco at scale 50000”_
270
270
  _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
271
271
  _Example: “Go to the Downtown bookmark”_
272
- _Example: “Where is Mount Rainier?”_`;var OW=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
272
+ _Example: “Where is Mount Rainier?”_`;var R2=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
273
273
  _Example: “Color points by sales amount”_
274
274
  _Example: “Show population density with a color gradient”_
275
275
  _Example: “Create a relationship map between height and depth”_
276
- _Example: “Vary circle sizes according to population”_`;var tV=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).
276
+ _Example: “Vary circle sizes according to population”_`;var nV=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).
277
277
  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.
278
278
  _Example: “Only show stations where Brand is Shell”_
279
279
  _Example: “Make Shell stations stand out on the map”_
@@ -283,7 +283,7 @@ ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generati
283
283
  _Example: “What’s the average population?”_
284
284
  _Example: “Which values are in the status field?”_
285
285
 
286
- This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var _V=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
286
+ This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var bV=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
287
287
 
288
288
  _Example: “Tell me about this map”_
289
289
  _Example: “List all layers in this map”_
@@ -296,7 +296,7 @@ ${a}`};async function Ab(t,e,r){let n=await Ye("arcgis_knowledge_lucene_generati
296
296
 
297
297
  IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
298
298
  _Example: "Create a chart"_
299
- _Example: "Create a table"_`;var zV=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
299
+ _Example: "Create a table"_`;var LV=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
300
300
  This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
301
301
  For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
302
302
  expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
@@ -334,7 +334,7 @@ _example: "Discover and add all the relationships originating at 'Entity E' to t
334
334
  _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
335
335
  _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
336
336
  _example: "Find John Smith and all people he has made phone calls to in the last year"_
337
- _example: "What is the average age of all people who work for Esri?"_`;var Xe=To;var ce=H;var Oo=()=>Ls(),Js=async(t,e)=>await me(t,e),Zs=async({modelTier:t="default",temperature:e=0,config:r}={})=>await mi({modelTier:t,temperature:e,config:r});var Yd=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function cr(t){if(!Yd(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Eb=`
337
+ _example: "What is the average age of all people who work for Esri?"_`;var Xe=To;var ce=H;var Oo=()=>Ls(),Js=async(t,e)=>await me(t,e),Zs=async({modelTier:t="default",temperature:e=0,config:r}={})=>await mi({modelTier:t,temperature:e,config:r});var Yd=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function cr(t){if(!Yd(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Pb=`
338
338
  Write a concise, friendly success message for adding members to a group.
339
339
 
340
340
  Rules:
@@ -349,12 +349,12 @@ Added members:
349
349
 
350
350
  Not added members:
351
351
  {notAddedMembers}
352
- `,Pb=t=>t.map(e=>`"${e}"`).join(", "),Ob=c.object({successMessage:c.string().default("")}),Kd="portal-group-creation",Gd="approveAddMembers",Mb=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(m=>m.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
352
+ `,Ob=t=>t.map(e=>`"${e}"`).join(", "),Mb=c.object({successMessage:c.string().default("")}),Kd="portal-group-creation",Gd="approveAddMembers",Rb=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(m=>m.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
353
353
 
354
354
  ${n.map(m=>`- **@${m}**`).join(`
355
355
  `)}
356
356
 
357
- Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Kd||s.id!==Gd){let m={agentId:Kd,id:Gd,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new Ro(m)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ce({text:`Adding members ${Pb(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;cr(a);let{result:i,error:u}=await cl(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:d}=i;try{let m=(await Xe({promptText:Eb,schema:Ob,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(m)return{status:"success",outputMessage:m}}catch(m){console.error("Error generating add-members success message:",m)}return{}},Rb=`
357
+ Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==Kd||s.id!==Gd){let m={agentId:Kd,id:Gd,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new Ro(m)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await ce({text:`Adding members ${Ob(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;cr(a);let{result:i,error:u}=await cl(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:d}=i;try{let m=(await Xe({promptText:Pb,schema:Mb,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(d.map(f=>({username:f.username,reason:f.error.message})))}})).successMessage;if(m)return{status:"success",outputMessage:m}}catch(m){console.error("Error generating add-members success message:",m)}return{}},$b=`
358
358
  Write a concise, friendly success message after creating a portal group.
359
359
 
360
360
  Rules:
@@ -365,7 +365,7 @@ Rules:
365
365
 
366
366
  Group title:
367
367
  {groupTitle}
368
- `,$b=`
368
+ `,Nb=`
369
369
  Write a concise, friendly failure message after an attempt to create a portal group.
370
370
 
371
371
  Rules:
@@ -380,7 +380,7 @@ Group title:
380
380
 
381
381
  Failure reason:
382
382
  {failureReason}
383
- `,Wd="portal-group-creation",Vd="approveCreateGroup",Nb=c.object({successMessage:c.string().default("")}),zb=c.object({failureMessage:c.string().default("")}),jb=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==Wd||o.id!==Vd){let l={agentId:Wd,id:Vd,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new Ro(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ce({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;cr(s);let{result:a,error:i}=await ul(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let d=(await Xe({promptText:$b,schema:zb,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(d)return{status:"success",outputMessage:d}}catch(d){console.error("Error generating create-group failure message:",d)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Xe({promptText:Rb,schema:Nb,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},dr=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Lb=`
383
+ `,Wd="portal-group-creation",Vd="approveCreateGroup",zb=c.object({successMessage:c.string().default("")}),jb=c.object({failureMessage:c.string().default("")}),Lb=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==Wd||o.id!==Vd){let l={agentId:Wd,id:Vd,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new Ro(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await ce({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;cr(s);let{result:a,error:i}=await ul(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let d=(await Xe({promptText:Nb,schema:jb,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(d)return{status:"success",outputMessage:d}}catch(d){console.error("Error generating create-group failure message:",d)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await Xe({promptText:$b,schema:zb,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},dr=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},Db=`
384
384
  You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
385
385
 
386
386
  Rules:
@@ -406,17 +406,17 @@ Examples:
406
406
 
407
407
  User message:
408
408
  {userMessage}
409
- `,Db=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),Fb=async(t,e)=>{await ce({text:"Thinking about groups...",agentName:"group-creation"},e);let r=dr(t.agentExecutionContext.messages).trim(),n=await Xe({promptText:Lb,schema:Db,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},Ub=c.enum(["portal-content","portal-content-favorites","portal-content-group","portal-content-living-atlas","portal-content-organization","portal-gallery","portal-groups","portal-groups-featured","portal-groups-my","portal-groups-organization","portal-map-viewer","portal-notebooks","portal-scene-viewer","portal-settings-security"]),qb=c.object({destinationType:Ub}),Bb=c.union([qb,c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1)})]),Xd="portal-navigation",Oi=async(t,e)=>{let r=e?.configurable?.context;!Yd(r)||!r.navigationTargetMap?.[t.destinationType]||await Js({type:Xd,data:{...t}},e)},Kb=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ce({text:"Preparing navigation...",agentName:"group-creation"},e),await Oi({destinationType:"portal-group",groupId:r},e),{}):{}},Hd=(t,e)=>e??t,ep=O.Root({...Oo(),intentParams:O({reducer:Hd,default:()=>({intent:"clarify"})}),createdGroupId:O({reducer:Hd,default:()=>""})}),Gb=()=>new pe(ep).addNode("detectGroupCreationIntent",Fb).addNode("createPortalGroup",jb).addNode("addMembersToPortalGroup",Mb).addNode("suggestCreatedGroupNavigation",Kb).addEdge(de,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return B}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",B),Wb=String.raw`- **portal-group-creation** - Portal group creation assistant:
409
+ `,Fb=c.object({intent:c.enum(["clarify","create","addMembers"]).default("clarify"),title:c.string().default(""),memberIdentifiers:c.array(c.string()).default([]),clarifyMessage:c.string().default("")}),Ub=async(t,e)=>{await ce({text:"Thinking about groups...",agentName:"group-creation"},e);let r=dr(t.agentExecutionContext.messages).trim(),n=await Xe({promptText:Db,schema:Fb,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},qb=c.enum(["portal-content","portal-content-favorites","portal-content-group","portal-content-living-atlas","portal-content-organization","portal-gallery","portal-groups","portal-groups-featured","portal-groups-my","portal-groups-organization","portal-map-viewer","portal-notebooks","portal-scene-viewer","portal-settings-security"]),Bb=c.object({destinationType:qb}),Kb=c.union([Bb,c.object({destinationType:c.literal("portal-item"),itemId:c.string().trim().min(1)}),c.object({destinationType:c.literal("portal-group"),groupId:c.string().trim().min(1)})]),Xd="portal-navigation",Oi=async(t,e)=>{let r=e?.configurable?.context;!Yd(r)||!r.navigationTargetMap?.[t.destinationType]||await Js({type:Xd,data:{...t}},e)},Gb=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await ce({text:"Preparing navigation...",agentName:"group-creation"},e),await Oi({destinationType:"portal-group",groupId:r},e),{}):{}},Hd=(t,e)=>e??t,ep=O.Root({...Oo(),intentParams:O({reducer:Hd,default:()=>({intent:"clarify"})}),createdGroupId:O({reducer:Hd,default:()=>""})}),Wb=()=>new pe(ep).addNode("detectGroupCreationIntent",Ub).addNode("createPortalGroup",Lb).addNode("addMembersToPortalGroup",Rb).addNode("suggestCreatedGroupNavigation",Gb).addEdge(de,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return B}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",B),Vb=String.raw`- **portal-group-creation** - Portal group creation assistant:
410
410
  - creates a new ArcGIS Portal group for the signed-in user
411
411
  - adds users to the newly created group using @mention usernames
412
- `,Vb={id:"portal-group-creation",name:"Portal Group Creation",description:Wb,createGraph:Gb,workspace:ep},tp="portalDocAssistantMemory",Hb=()=>({conversationId:""}),Jb=t=>{let e=t?.[tp]?.value;if(!e||typeof e!="object")return Hb();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Zb=t=>({[tp]:{value:t}}),Qb={rag:{top_k:20,certainty_threshold:.7,radius_of_surrounding_chunks:2,top_k_surrounding_chunks:120,extract_key_terms:!0},pipeline:{conversation_history:{allow:!0,number_of_interactions_to_include:4},conversation_title:{allow:!1},follow_up:{allow:!1},retrieved_chunks_in_response:{allow:!1}}};function Yb(t){return{kind:"DocAIAssistantRequest",filters:{...Qb,persona:{persona:t}}}}async function Xb({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=Yb(r),i=await ex({portal:t,skillId:s,message:e,options:{context:a,previousConversationId:n,signal:o}});return{reply:tx(i,s),conversationId:i[0]?.conversationId??""}}async function ex({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Cb.findCredential(t.url)?.token??""},a=await Bd(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:d}=i,m=async(f,I)=>{if(!I)return;await Ui(500);let w=await Bd(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:d,ackSequenceNumber:f}),headers:s,signal:n.signal});if(w.httpStatus!==200)throw new Error(`Doc assistant poll failed (${w.httpStatus})`,{cause:w.data});let b=w.data;u.push(b),await m(b.sequenceNumber,b.hasMore)};return i.hasMore&&await m(i.sequenceNumber,i.hasMore),u}function tx(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return Gn(e)}}var rx=async(t,e)=>{await ce({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=dr(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;cr(n);let o=Jb(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await Xb({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:Zb({conversationId:a||o.conversationId})}},rp=$(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;cr(n);try{return(await ll(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:c.object({groupTitle:c.string().describe("The portal group title to resolve to a group id.")})}),np=$(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;cr(n);let{result:o,error:s}=await dl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:c.object({itemTitle:c.string().describe("The portal item title to resolve to an item id.")})});function Mo(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let n=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return n?.[1]?n[1].trim():null}var op={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"],scope:"root"},"portal-content-favorites":{description:"The My favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"],scope:"collection"},"portal-content-group":{description:"The My groups view under Content in the portal.",hints:["Content my groups","My groups content","Group content"],scope:"collection"},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content Living Atlas"],scope:"collection"},"portal-content-organization":{description:"The My organization view under Content in the portal.",hints:["My organization content","Organization content","Content organization"],scope:"collection"},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"],scope:"collection"},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"],scope:"entity"},"portal-groups":{description:"The groups listing page of the portal.",hints:["My groups","Groups"],scope:"collection"},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"],scope:"collection"},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"],scope:"collection"},"portal-groups-organization":{description:"The My organization's groups view under Groups in the portal.",hints:["Organization's groups","My organization's groups","Groups organization"],scope:"collection"},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"],scope:"entity"},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"],scope:"entity"},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"],scope:"collection"},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"],scope:"entity"},"portal-settings-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],scope:"entity"}},nx=qi(op),ox=Object.entries(op).map(([t,{description:e,hints:r,scope:n}])=>` - ${t}: ${e} (scope: ${n}; hints: ${r.join(", ")})`).join(`
413
- `),sx=`
412
+ `,Hb={id:"portal-group-creation",name:"Portal Group Creation",description:Vb,createGraph:Wb,workspace:ep},tp="portalDocAssistantMemory",Jb=()=>({conversationId:""}),Zb=t=>{let e=t?.[tp]?.value;if(!e||typeof e!="object")return Jb();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},Qb=t=>({[tp]:{value:t}}),Yb={pipeline:{follow_up:{allow:!1}}};function Xb(t){return{kind:"DocAIAssistantRequest",filters:{...Yb,persona:{persona:t}}}}async function ex({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=Xb(r),i=await tx({portal:t,skillId:s,message:e,options:{context:a,previousConversationId:n,signal:o}});return{reply:rx(i,s),conversationId:i[0]?.conversationId??""}}async function tx({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Eb.findCredential(t.url)?.token??""},a=await Bd(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:d}=i,m=async(f,I)=>{if(!I)return;await Ui(500);let w=await Bd(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:d,ackSequenceNumber:f}),headers:s,signal:n.signal});if(w.httpStatus!==200)throw new Error(`Doc assistant poll failed (${w.httpStatus})`,{cause:w.data});let b=w.data;u.push(b),await m(b.sequenceNumber,b.hasMore)};return i.hasMore&&await m(i.sequenceNumber,i.hasMore),u}function rx(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return Gn(e)}}var nx=async(t,e)=>{await ce({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=dr(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;cr(n);let o=Zb(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await ex({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"doc-online"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:Qb({conversationId:a||o.conversationId})}},rp=$(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;cr(n);try{return(await ll(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:c.object({groupTitle:c.string().describe("The portal group title to resolve to a group id.")})}),np=$(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;cr(n);let{result:o,error:s}=await dl(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:c.object({itemTitle:c.string().describe("The portal item title to resolve to an item id.")})});function Mo(t,e="#"){let r=t.match(new RegExp(`\\${e}"([^"]+)"`,"u"));if(r?.[1])return r[1].trim();let n=t.match(new RegExp(`\\${e}([^\\s"']+)`,"u"));return n?.[1]?n[1].trim():null}var op={"portal-content":{description:"The main content page of the portal.",hints:["My content","Content"],scope:"root"},"portal-content-favorites":{description:"The My favorites view under Content in the portal.",hints:["My favorites","Favorites","Content favorites"],scope:"collection"},"portal-content-group":{description:"The My groups view under Content in the portal.",hints:["Content my groups","My groups content","Group content"],scope:"collection"},"portal-content-living-atlas":{description:"The Living Atlas view under Content in the portal.",hints:["Living Atlas","Content Living Atlas"],scope:"collection"},"portal-content-organization":{description:"The My organization view under Content in the portal.",hints:["My organization content","Organization content","Content organization"],scope:"collection"},"portal-gallery":{description:"The gallery page of the portal.",hints:["Gallery","Featured content","Maps and apps"],scope:"collection"},"portal-group":{description:"A specific group page in the portal.",hints:["Group","group page"],scope:"entity"},"portal-groups":{description:"The groups listing page of the portal.",hints:["My groups","Groups"],scope:"collection"},"portal-groups-featured":{description:"The Featured groups view under Groups in the portal.",hints:["Featured groups","Groups featured"],scope:"collection"},"portal-groups-my":{description:"The My groups view under Groups in the portal.",hints:["My groups","Groups my"],scope:"collection"},"portal-groups-organization":{description:"The My organization's groups view under Groups in the portal.",hints:["Organization's groups","My organization's groups","Groups organization"],scope:"collection"},"portal-item":{description:"A specific item page in the portal.",hints:["Item","item page"],scope:"entity"},"portal-map-viewer":{description:"The Map Viewer app of the portal.",hints:["Map Viewer","Map","Open map"],scope:"entity"},"portal-notebooks":{description:"The Notebooks home page of the portal.",hints:["Notebooks","Notebook home","My notebooks"],scope:"collection"},"portal-scene-viewer":{description:"The Scene Viewer app of the portal.",hints:["Scene Viewer","Scene","3D scene"],scope:"entity"},"portal-settings-security":{description:"The Organization > Settings > Security page of the portal.",hints:["Organization settings","Security","Organization > Settings > Security"],scope:"entity"}},ox=qi(op),sx=Object.entries(op).map(([t,{description:e,hints:r,scope:n}])=>` - ${t}: ${e} (scope: ${n}; hints: ${r.join(", ")})`).join(`
413
+ `),ax=`
414
414
  You decide whether the assistant response should include a navigation action to ArcGIS Portal.
415
415
 
416
416
  Given the user question and assistant response:
417
417
  - Decide if a navigation action would help the user complete the task.
418
418
  - If yes, choose one destination type:
419
- ${ox}
419
+ ${sx}
420
420
 
421
421
  Rules:
422
422
  - Only suggest navigation when you are highly confident the destination will help complete the user's task.
@@ -439,17 +439,17 @@ User question:
439
439
 
440
440
  Assistant response:
441
441
  {response}
442
- `,Jd=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...nx]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),ax=async(t,e)=>{await ce({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=dr(t.agentExecutionContext.messages).trim(),o=await fr.fromTemplate(sx).format({question:n,response:r}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Jd),a=Jd.parse(await s.invoke(o));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Mo(n,"#");u&&(a.itemId=await np.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Mo(n,"$")??Mo(n,"#");u&&(a.groupId=await rp.invoke({groupTitle:u},e)??"")}let i=ix(a);return i?(await Oi(i,e),{}):{}};function ix({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":case"portal-gallery":case"portal-groups":case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":case"portal-settings-security":return{destinationType:t};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return Gn(t)}}var sp=O.Root({...Oo()}),lx=()=>new pe(sp).addNode("answerDocQuestion",rx).addNode("extractNavigationIntent",ax).addEdge(de,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",B),ux=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
442
+ `,Jd=c.object({shouldSuggestNavigation:c.boolean().default(!1),destinationType:c.enum(["none",...ox]).default("none"),itemId:c.string().default(""),groupId:c.string().default(""),confidence:c.number().min(0).max(1).default(0)}),ix=async(t,e)=>{await ce({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=dr(t.agentExecutionContext.messages).trim(),o=await fr.fromTemplate(ax).format({question:n,response:r}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Jd),a=Jd.parse(await s.invoke(o));if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};if(a.destinationType==="portal-item"&&!a.itemId){let u=Mo(n,"#");u&&(a.itemId=await np.invoke({itemTitle:u},e)??"")}if(a.destinationType==="portal-group"&&!a.groupId){let u=Mo(n,"$")??Mo(n,"#");u&&(a.groupId=await rp.invoke({groupTitle:u},e)??"")}let i=lx(a);return i?(await Oi(i,e),{}):{}};function lx({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":case"portal-gallery":case"portal-groups":case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":case"portal-settings-security":return{destinationType:t};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return Gn(t)}}var sp=O.Root({...Oo()}),ux=()=>new pe(sp).addNode("answerDocQuestion",nx).addNode("extractNavigationIntent",ix).addEdge(de,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",B),cx=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
443
443
  - answers general ArcGIS, Portal, Enterprise, and JavaScript SDK questions
444
444
  - acts as a fallback when specialized agents are not applicable
445
- `,cx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:ux,createGraph:lx,workspace:sp},dx=()=>({latestGroupId:null,memory:{}}),Qs=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:dx()},ap=`
445
+ `,dx={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:cx,createGraph:ux,workspace:sp},px=()=>({latestGroupId:null,memory:{}}),Qs=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:px()},ap=`
446
446
  Shared markdown formatting rules:
447
447
  - Use clear markdown headings (##) to separate sections.
448
448
  - Use concise bullet points for lists of facts, counts, or signals.
449
449
  - Emphasize key metrics with bold labels (for example: **Recent items:** 4).
450
450
  - Keep wording direct and analytical; avoid filler language but make sure the language is friendly.
451
451
  - Do not include raw internal IDs unless explicitly requested.
452
- `,px=`
452
+ `,mx=`
453
453
  You answer follow-up questions about ArcGIS group analytics.
454
454
 
455
455
  ${ap}
@@ -474,7 +474,7 @@ Group full context:
474
474
 
475
475
  Question:
476
476
  {question}
477
- `,mx=async(t,e)=>{await ce({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=Qs(t),n=t.groupSummaryGroupId??r.latestGroupId,o=n?r.memory[n]:void 0,s=t.groupSummaryQuestion||dr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Xe({promptText:px,schema:fx,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I do not have group analytics context yet. Ask me to analyze a group first with analyze group <group id>."}},fx=c.object({answer:c.string(),isRelevant:c.boolean()}),hx=`
477
+ `,fx=async(t,e)=>{await ce({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=Qs(t),n=t.groupSummaryGroupId??r.latestGroupId,o=n?r.memory[n]:void 0,s=t.groupSummaryQuestion||dr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Xe({promptText:mx,schema:hx,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I do not have group analytics context yet. Ask me to analyze a group first with analyze group <group id>."}},hx=c.object({answer:c.string(),isRelevant:c.boolean()}),gx=`
478
478
  Classify the user's request for ArcGIS Portal group analytics.
479
479
 
480
480
  Rules:
@@ -503,7 +503,7 @@ hasAnalyticsContext:
503
503
 
504
504
  User message:
505
505
  {userMessage}
506
- `,gx=async(t,e)=>{await ce({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=dr(t.agentExecutionContext.messages),n=!!Qs(t).latestGroupId,o=await fr.fromTemplate(hx).format({userMessage:r,hasAnalyticsContext:String(n)}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Zd),a=Zd.parse(await s.invoke(o)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let I=Mo(r,"$");I&&(i=await rp.invoke({groupTitle:I},e)??"")}let{intent:u,question:l}=a,d=u==="summarize"&&!i,m=u==="followUp"&&!(l??"").trim(),f=u==="clarify"||d||m;return{groupSummaryIntent:f?"clarify":u,groupSummaryGroupId:i||null,groupSummaryQuestion:l||"",status:"success",outputMessage:f?"Please clarify with a group id or title":""}},Zd=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),yx=async(t,e)=>{let r=Qs(t),n=t.groupSummaryGroupId??r.latestGroupId;return await ce({text:"Preparing navigation...",agentName:"group-analytics"},e),await Oi(n?{destinationType:"portal-group",groupId:n}:{destinationType:"portal-groups"},e),{status:"success"}};function ip({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var _x=720*60*60*1e3;function wx(t){let e=ml(t);return{id:t.id??"",title:t.title??"",description:t.description??"",snippet:t.snippet??"",access:t.access??null,owner:t.owner??"",tags:t.tags??[],created:t.created?.getTime(),modified:t.modified?.getTime(),isInvitationOnly:t.isInvitationOnly,sourceSignals:{capabilities:fl(t),membershipAccess:hl(t),isOpenData:gl(t),isDistributedCollaborationGroup:yl(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function bx(t){let e={owner:t.owner??"",admins:[],users:[]};try{return await t.fetchMembers()}catch(r){return console.warn("Unable to fetch group members for analytics context",r),e}}function xx(t){return t.map(e=>({id:e.id??"",title:e.title??"Untitled",type:e.type??"Unknown",owner:e.owner??"",created:e.created?.getTime(),modified:e.modified?.getTime()}))}function Ax(t,e){return t.filter(r=>r.modified?ip({timestamp:r.modified,now:e,windowMs:_x}):!1)}function Ix(t){let e=new Map;for(let r of t)e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].sort((r,n)=>n[1]-r[1]||r[0].localeCompare(n[0])).slice(0,6).map(([r,n])=>({type:r,count:n}))}async function vx(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=xx(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:Ax(r,n),topItemTypes:Ix(r)}}async function Tx(t,e){if(!e)return{error:{code:"missingGroupId",message:"Group id is required."}};try{let r=(await t.queryGroups({query:`id:${e}`,num:1})).results[0];if(!r)return{error:{code:"groupNotFound",message:`No group found for id: ${e}`}};let n=wx(r),o=await bx(r),s=await vx(r);return{result:{group:n,members:o,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var Sx=`
506
+ `,yx=async(t,e)=>{await ce({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=dr(t.agentExecutionContext.messages),n=!!Qs(t).latestGroupId,o=await fr.fromTemplate(gx).format({userMessage:r,hasAnalyticsContext:String(n)}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Zd),a=Zd.parse(await s.invoke(o)),i=a.groupId;if((a.intent==="summarize"||a.intent==="navigation")&&!i){let I=Mo(r,"$");I&&(i=await rp.invoke({groupTitle:I},e)??"")}let{intent:u,question:l}=a,d=u==="summarize"&&!i,m=u==="followUp"&&!(l??"").trim(),f=u==="clarify"||d||m;return{groupSummaryIntent:f?"clarify":u,groupSummaryGroupId:i||null,groupSummaryQuestion:l||"",status:"success",outputMessage:f?"Please clarify with a group id or title":""}},Zd=c.object({intent:c.enum(["summarize","followUp","navigation","clarify"]),groupId:c.string().default(""),question:c.string().default("")}),_x=async(t,e)=>{let r=Qs(t),n=t.groupSummaryGroupId??r.latestGroupId;return await ce({text:"Preparing navigation...",agentName:"group-analytics"},e),await Oi(n?{destinationType:"portal-group",groupId:n}:{destinationType:"portal-groups"},e),{status:"success"}};function ip({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var wx=720*60*60*1e3;function bx(t){let e=ml(t);return{id:t.id??"",title:t.title??"",description:t.description??"",snippet:t.snippet??"",access:t.access??null,owner:t.owner??"",tags:t.tags??[],created:t.created?.getTime(),modified:t.modified?.getTime(),isInvitationOnly:t.isInvitationOnly,sourceSignals:{capabilities:fl(t),membershipAccess:hl(t),isOpenData:gl(t),isDistributedCollaborationGroup:yl(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function xx(t){let e={owner:t.owner??"",admins:[],users:[]};try{return await t.fetchMembers()}catch(r){return console.warn("Unable to fetch group members for analytics context",r),e}}function Ax(t){return t.map(e=>({id:e.id??"",title:e.title??"Untitled",type:e.type??"Unknown",owner:e.owner??"",created:e.created?.getTime(),modified:e.modified?.getTime()}))}function Ix(t,e){return t.filter(r=>r.modified?ip({timestamp:r.modified,now:e,windowMs:wx}):!1)}function vx(t){let e=new Map;for(let r of t)e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].sort((r,n)=>n[1]-r[1]||r[0].localeCompare(n[0])).slice(0,6).map(([r,n])=>({type:r,count:n}))}async function Tx(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=Ax(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:Ix(r,n),topItemTypes:vx(r)}}async function Sx(t,e){if(!e)return{error:{code:"missingGroupId",message:"Group id is required."}};try{let r=(await t.queryGroups({query:`id:${e}`,num:1})).results[0];if(!r)return{error:{code:"groupNotFound",message:`No group found for id: ${e}`}};let n=bx(r),o=await xx(r),s=await Tx(r);return{result:{group:n,members:o,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var kx=`
507
507
  You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
508
508
 
509
509
  ${ap}
@@ -542,11 +542,11 @@ Group context:
542
542
 
543
543
  Deterministic signals:
544
544
  {deterministicSignals}
545
- `,kx=2160*60*60*1e3,Cx=async(t,e)=>{let r=t.groupSummaryGroupId;if(!r)return{status:"success",outputMessage:'Please clarify with analyze group <group id>, analyze group $<title>, or analyze group $"<title with spaces>".'};await ce({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let n=e?.configurable?.context;cr(n);let{result:o,error:s}=await Tx(n.portal,r);if(s||!o)return await ce({text:"Failed to fetch group context",agentName:"group-analytics"},e),{status:"success",outputMessage:"Unable to retrieve group context for analytics."};let{group:a,items:i}=o,u=Date.now(),l=a.modified,d=l?ip({timestamp:l,now:u,windowMs:kx}):!1,m=i.recentlyModifiedItems.length,f=m>0,I=d||f,w=await Xe({promptText:Sx,schema:Ex,modelTier:"default",inputVariables:{context:JSON.stringify(o),deterministicSignals:JSON.stringify({isGroupActive:I,isGroupRecentlyModified:d,hasRecentlyAddedOrUpdatedContent:f,recentItemCount:m})}}),{followUpQuestions:b,summary:y}=w,h=Qs(t),x={latestGroupId:r,memory:{...h.memory,[r]:{summary:y,followUpQuestions:b,fullContext:o}}};return b.length&&await Js({type:"suggested-prompts",data:{prompts:b}},e),{status:"success",outputMessage:y,sharedStatePatch:{portalGroupSummaryMemory:{value:x}}}},Ex=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Ci=(t,e)=>e??t,lp=O.Root({...Oo(),groupSummaryIntent:O({reducer:Ci,default:()=>"clarify"}),groupSummaryGroupId:O({reducer:Ci,default:()=>null}),groupSummaryQuestion:O({reducer:Ci,default:()=>""})}),Px=()=>new pe(lp).addNode("detectGroupSummaryIntent",gx).addNode("summarizePortalGroup",Cx).addNode("answerGroupSummaryFollowUp",mx).addNode("suggestGroupSummaryNavigation",yx).addEdge(de,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":B).addEdge("summarizePortalGroup",B).addEdge("answerGroupSummaryFollowUp",B).addEdge("suggestGroupSummaryNavigation",B),Ox=String.raw`- **portal-group-analytics** - Portal group analytics assistant:
545
+ `,Cx=2160*60*60*1e3,Ex=async(t,e)=>{let r=t.groupSummaryGroupId;if(!r)return{status:"success",outputMessage:'Please clarify with analyze group <group id>, analyze group $<title>, or analyze group $"<title with spaces>".'};await ce({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let n=e?.configurable?.context;cr(n);let{result:o,error:s}=await Sx(n.portal,r);if(s||!o)return await ce({text:"Failed to fetch group context",agentName:"group-analytics"},e),{status:"success",outputMessage:"Unable to retrieve group context for analytics."};let{group:a,items:i}=o,u=Date.now(),l=a.modified,d=l?ip({timestamp:l,now:u,windowMs:Cx}):!1,m=i.recentlyModifiedItems.length,f=m>0,I=d||f,w=await Xe({promptText:kx,schema:Px,modelTier:"default",inputVariables:{context:JSON.stringify(o),deterministicSignals:JSON.stringify({isGroupActive:I,isGroupRecentlyModified:d,hasRecentlyAddedOrUpdatedContent:f,recentItemCount:m})}}),{followUpQuestions:b,summary:y}=w,h=Qs(t),x={latestGroupId:r,memory:{...h.memory,[r]:{summary:y,followUpQuestions:b,fullContext:o}}};return b.length&&await Js({type:"suggested-prompts",data:{prompts:b}},e),{status:"success",outputMessage:y,sharedStatePatch:{portalGroupSummaryMemory:{value:x}}}},Px=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Ci=(t,e)=>e??t,lp=O.Root({...Oo(),groupSummaryIntent:O({reducer:Ci,default:()=>"clarify"}),groupSummaryGroupId:O({reducer:Ci,default:()=>null}),groupSummaryQuestion:O({reducer:Ci,default:()=>""})}),Ox=()=>new pe(lp).addNode("detectGroupSummaryIntent",yx).addNode("summarizePortalGroup",Ex).addNode("answerGroupSummaryFollowUp",fx).addNode("suggestGroupSummaryNavigation",_x).addEdge(de,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":B).addEdge("summarizePortalGroup",B).addEdge("answerGroupSummaryFollowUp",B).addEdge("suggestGroupSummaryNavigation",B),Mx=String.raw`- **portal-group-analytics** - Portal group analytics assistant:
546
546
  - summarizes ArcGIS portal groups from group context and sourceJSON details
547
547
  - answers follow-up questions grounded in the summarized group
548
548
  - suggests navigation to groups when relevant
549
- `,Mx={id:"portal-group-analytics",name:"Portal Group Analytics",description:Ox,createGraph:Px,workspace:lp},Rx=()=>({latestItemId:null,memory:{}}),Mi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:Rx()},Qd=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),$x=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),Nx=c.object({answer:c.string(),isRelevant:c.boolean()}),zx=`
549
+ `,Rx={id:"portal-group-analytics",name:"Portal Group Analytics",description:Mx,createGraph:Ox,workspace:lp},$x=()=>({latestItemId:null,memory:{}}),Mi=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:$x()},Qd=c.object({intent:c.enum(["summarize","followUp","clarify"]),itemId:c.string().default(""),question:c.string().default("")}),Nx=c.object({summary:c.string(),followUpQuestions:c.array(c.string()).default([])}),zx=c.object({answer:c.string(),isRelevant:c.boolean()}),jx=`
550
550
  You answer follow-up questions about an ArcGIS item.
551
551
 
552
552
  Ground your answer in the provided item context.
@@ -566,7 +566,7 @@ Item full context
566
566
 
567
567
  Question:
568
568
  {question}
569
- `,jx=async(t,e)=>{await ce({text:"Answering follow-up...",agentName:"analytics"},e);let r=Mi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||dr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Xe({promptText:zx,schema:Nx,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Lx=`
569
+ `,Lx=async(t,e)=>{await ce({text:"Answering follow-up...",agentName:"analytics"},e);let r=Mi(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||dr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await Xe({promptText:jx,schema:zx,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},Dx=`
570
570
  Classify the user analytics request.
571
571
 
572
572
  Rules:
@@ -596,7 +596,7 @@ hasSummaryContext:
596
596
 
597
597
  User message:
598
598
  {userMessage}
599
- `,Dx=async(t,e)=>{await ce({text:"Analyzing intent...",agentName:"analytics"},e);let r=dr(t.agentExecutionContext.messages),n=!!Mi(t).latestItemId,o=await fr.fromTemplate(Lx).format({userMessage:r,hasSummaryContext:String(n)}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Qd),a=Qd.parse(await s.invoke(o)),i=a.itemId;if(a.intent==="summarize"&&!i){let m=Mo(r,"#");m&&(i=await np.invoke({itemTitle:m},e)??"")}let{intent:u,question:l}=a,d=u==="clarify"||u==="summarize"&&!i||u==="followUp"&&!l;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:d?"clarify":u,analyticsItemId:i||null,analyticsQuestion:l||"",status:"success",outputMessage:d?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Fx=`
599
+ `,Fx=async(t,e)=>{await ce({text:"Analyzing intent...",agentName:"analytics"},e);let r=dr(t.agentExecutionContext.messages),n=!!Mi(t).latestItemId,o=await fr.fromTemplate(Dx).format({userMessage:r,hasSummaryContext:String(n)}),s=(await Zs({modelTier:"fast"})).withStructuredOutput(Qd),a=Qd.parse(await s.invoke(o)),i=a.itemId;if(a.intent==="summarize"&&!i){let m=Mo(r,"#");m&&(i=await np.invoke({itemTitle:m},e)??"")}let{intent:u,question:l}=a,d=u==="clarify"||u==="summarize"&&!i||u==="followUp"&&!l;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:d?"clarify":u,analyticsItemId:i||null,analyticsQuestion:l||"",status:"success",outputMessage:d?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},Ux=`
600
600
  You are a item summary tool for ArcGIS. Your job is to summarize an item's info based on the provided context.
601
601
  Summary rules:
602
602
  - The summary should be concise markdown, make sure to format the output nicely so it's easy to read.
@@ -611,9 +611,9 @@ Do not include internal identifiers.
611
611
  If the user asks for a detailed summary, you may expand the response up to 300 words.
612
612
  Item context:
613
613
  {context}
614
- `,Ux=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await ce({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;cr(n);let{portal:o,user:s}=n,{result:a,error:i}=await pl(s,o,r);if(i||!a)return await ce({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await Xe({promptText:Fx,schema:$x,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:m}=l,f=Mi(t),I={latestItemId:r,memory:{...f.memory,[r]:{summary:m,followUpQuestions:d,fullContext:u}}};return d.length&&await Js({type:"suggested-prompts",data:{prompts:d}},e),{status:"success",outputMessage:m,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:I}}}},Ei=(t,e)=>e??t,up=O.Root({...Oo(),analyticsIntent:O({reducer:Ei,default:()=>"clarify"}),analyticsItemId:O({reducer:Ei,default:()=>null}),analyticsQuestion:O({reducer:Ei,default:()=>""})}),qx=()=>new pe(up).addNode("detectAnalyticsIntent",Dx).addNode("summarizePortalItem",Ux).addNode("answerAnalyticsFollowUp",jx).addEdge(de,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":B).addEdge("summarizePortalItem",B).addEdge("answerAnalyticsFollowUp",B),Bx=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
614
+ `,qx=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await ce({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;cr(n);let{portal:o,user:s}=n,{result:a,error:i}=await pl(s,o,r);if(i||!a)return await ce({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await Xe({promptText:Ux,schema:Nx,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:d,summary:m}=l,f=Mi(t),I={latestItemId:r,memory:{...f.memory,[r]:{summary:m,followUpQuestions:d,fullContext:u}}};return d.length&&await Js({type:"suggested-prompts",data:{prompts:d}},e),{status:"success",outputMessage:m,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:I}}}},Ei=(t,e)=>e??t,up=O.Root({...Oo(),analyticsIntent:O({reducer:Ei,default:()=>"clarify"}),analyticsItemId:O({reducer:Ei,default:()=>null}),analyticsQuestion:O({reducer:Ei,default:()=>""})}),Bx=()=>new pe(up).addNode("detectAnalyticsIntent",Fx).addNode("summarizePortalItem",qx).addNode("answerAnalyticsFollowUp",Lx).addEdge(de,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":B).addEdge("summarizePortalItem",B).addEdge("answerAnalyticsFollowUp",B),Kx=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
615
615
  - answers questions about one specific ArcGIS portal item when item context is present
616
616
  - summarizes item details, metadata, and context grounded in that item
617
617
  - suggests follow-up prompts grounded in the same item
618
618
  - use for item-specific requests, not for gallery browsing, featured content, or opening Map Viewer
619
- `,Kx={id:"portal-item-analytics",name:"Portal Item Analytics",description:Bx,createGraph:qx,workspace:up},Gx=Ni`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`;function Wx(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":case"portal-gallery":case"portal-groups":case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":case"portal-settings-security":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId);default:return Gn(r)}}function Vx(t){let e=Bb.safeParse(t);return e.success?e.data:void 0}var Pi=class extends Di{constructor(){super(...arguments),this.t9n=Bi({blocking:!0}),this.assistantEl=Bn(),this.formEl=Bn(),this.voiceInputEl=Bn(),this.inputEl=Bn(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=ji()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,defaultClosed:5}}static{this.styles=Gx}getNavigationAction(e){if(e?.type!==Xd)return;let r=Vx(e.data);if(!r)return;let n=Wx(r,this.navigationTargetMap);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),zi(pr`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?pr`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-content-favorites":return r.openContentFavorites;case"portal-content-group":return r.openContentGroup;case"portal-content-living-atlas":return r.openContentLivingAtlas;case"portal-content-organization":return r.openContentOrganization;case"portal-gallery":return r.openGallery;case"portal-groups":return r.openGroups;case"portal-groups-featured":return r.openGroupsFeatured;case"portal-groups-my":return r.openGroupsMy;case"portal-groups-organization":return r.openGroupsOrganization;case"portal-map-viewer":return r.openMapViewer;case"portal-notebooks":return r.openNotebooks;case"portal-scene-viewer":return r.openSceneViewer;case"portal-settings-security":return r.openOrganizationSettingsSecurity;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return Gn(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return pr`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:l})=>{this.interrupt=l}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:l})=>{this.inputText=l.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${Kn(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${l=>{l.preventDefault();let d=r.trim();d&&(this.assistantEl.value?.submitMessage(d),this.inputText="")}} ${Kn(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:l})=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:l})=>{this.inputText=l??""}} ${Kn(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${l=>{l.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${l=>{this.inputText=l.detail.text}} ${Kn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&pr`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let l=this.voiceInputEl.value;i?await l?.stopListening():await l?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${Kx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Vb} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${cx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Mx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>${this.interrupt&&pr`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:l})=>{this.assistantEl.value?.submitInterrupt(l)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};Fi("arcgis-portal-ai-assistant",Pi);return Pi},"identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","request",a,b,c)
619
+ `,Gx={id:"portal-item-analytics",name:"Portal Item Analytics",description:Kx,createGraph:Bx,workspace:up},Wx=Ni`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`;function Vx(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":case"portal-content-favorites":case"portal-content-group":case"portal-content-living-atlas":case"portal-content-organization":case"portal-gallery":case"portal-groups":case"portal-groups-featured":case"portal-groups-my":case"portal-groups-organization":case"portal-map-viewer":case"portal-notebooks":case"portal-scene-viewer":case"portal-settings-security":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId);default:return Gn(r)}}function Hx(t){let e=Kb.safeParse(t);return e.success?e.data:void 0}var Pi=class extends Di{constructor(){super(...arguments),this.t9n=Bi({blocking:!0}),this.assistantEl=Bn(),this.formEl=Bn(),this.voiceInputEl=Bn(),this.inputEl=Bn(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=ji()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,defaultClosed:5}}static{this.styles=Wx}getNavigationAction(e){if(e?.type!==Xd)return;let r=Hx(e.data);if(!r)return;let n=Vx(r,this.navigationTargetMap);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),zi(pr`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?pr`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-content-favorites":return r.openContentFavorites;case"portal-content-group":return r.openContentGroup;case"portal-content-living-atlas":return r.openContentLivingAtlas;case"portal-content-organization":return r.openContentOrganization;case"portal-gallery":return r.openGallery;case"portal-groups":return r.openGroups;case"portal-groups-featured":return r.openGroupsFeatured;case"portal-groups-my":return r.openGroupsMy;case"portal-groups-organization":return r.openGroupsOrganization;case"portal-map-viewer":return r.openMapViewer;case"portal-notebooks":return r.openNotebooks;case"portal-scene-viewer":return r.openSceneViewer;case"portal-settings-security":return r.openOrganizationSettingsSecurity;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return Gn(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return pr`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:l})=>{this.interrupt=l}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:l})=>{this.inputText=l.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${Kn(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${l=>{l.preventDefault();let d=r.trim();d&&(this.assistantEl.value?.submitMessage(d),this.inputText="")}} ${Kn(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:l})=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:l})=>{this.inputText=l??""}} ${Kn(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${l=>{l.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${l=>{this.inputText=l.detail.text}} ${Kn(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&pr`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let l=this.voiceInputEl.value;i?await l?.stopListening():await l?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${Gx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Hb} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${dx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${Rx} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>${this.interrupt&&pr`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:l})=>{this.assistantEl.value?.submitInterrupt(l)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};Fi("arcgis-portal-ai-assistant",Pi);return Pi},"identity/IdentityManager","portal/Portal","portal/Portal","request","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","request",a,b,c)