@esri/solutions-components 5.1.0-next.165 → 5.1.0-next.166

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 (85) hide show
  1. package/dist/cdn/{YW2WMW6B.js → 25QYS4LE.js} +1 -1
  2. package/dist/cdn/{CV4B2O7J.js → 2BI4S6V2.js} +1 -1
  3. package/dist/cdn/{UDPMO6YN.js → 2BRPSISV.js} +1 -1
  4. package/dist/cdn/{S37TPZAO.js → 2LCG2XWX.js} +1 -1
  5. package/dist/cdn/{ATEW4U4A.js → 2VG5GRFH.js} +1 -1
  6. package/dist/cdn/{26LDC3OX.js → 2YC25V3L.js} +1 -1
  7. package/dist/cdn/{OUMIC7G7.js → 3FKVBTJC.js} +1 -1
  8. package/dist/cdn/{3J5ZSELO.js → 46I7FRQJ.js} +1 -1
  9. package/dist/cdn/{HRQVJBRJ.js → 66N4ZZKC.js} +1 -1
  10. package/dist/cdn/{EUI6UDCN.js → 6WPQPRJ5.js} +8 -2
  11. package/dist/cdn/{GVMTSUDH.js → 7P57UVVG.js} +1 -1
  12. package/dist/cdn/{5W7G3TSG.js → 7X2SPNNK.js} +21 -19
  13. package/dist/cdn/{2D6HFQD5.js → AFLXI5U2.js} +1 -1
  14. package/dist/cdn/{4HRGPGDM.js → BT3FYIEX.js} +1 -1
  15. package/dist/cdn/{A2A3RFJ6.js → C47WRU5U.js} +1 -1
  16. package/dist/cdn/{HAMYUUYZ.js → CDT6E3VG.js} +1 -1
  17. package/dist/cdn/CKWEF3KW.js +2 -0
  18. package/dist/cdn/{MFFM74RG.js → CVHZAZLS.js} +1 -1
  19. package/dist/cdn/{I4PBOBUM.js → DKZ4FZKK.js} +1 -1
  20. package/dist/cdn/{C4F2OOUL.js → G2H3X6NS.js} +1 -1
  21. package/dist/cdn/{3UCDO65S.js → GDUCH242.js} +1 -1
  22. package/dist/cdn/{JFPR5QIQ.js → GI33DSVT.js} +1 -1
  23. package/dist/cdn/{354D2K6F.js → GJWHFH2F.js} +1 -1
  24. package/dist/cdn/{OZ4IYASP.js → HOCCKT72.js} +1 -1
  25. package/dist/cdn/{HDMAFAEM.js → IVKRYKER.js} +1 -1
  26. package/dist/cdn/{6PZSOVYB.js → JGL4WYTO.js} +1 -1
  27. package/dist/cdn/{7VY3RI7C.js → JS2MTHHP.js} +1 -1
  28. package/dist/cdn/{SHEDDVHQ.js → K4LZRLGL.js} +1 -1
  29. package/dist/cdn/{FMPY32BG.js → K5ZYDQR7.js} +1 -1
  30. package/dist/cdn/{QH6PUU3Q.js → KD4IHPH6.js} +1 -6
  31. package/dist/cdn/{ITCC5G26.js → KWAQEZ3T.js} +2 -2
  32. package/dist/cdn/{QYCERRRZ.js → LXNQ32NZ.js} +1 -1
  33. package/dist/cdn/{SNZRQPXI.js → MFVXFKKM.js} +1 -1
  34. package/dist/cdn/{25HVM373.js → MVDJOENC.js} +1 -1
  35. package/dist/cdn/P5RZHVDH.js +2 -0
  36. package/dist/cdn/{22BT2PBE.js → PVPKXQBE.js} +12 -10
  37. package/dist/cdn/{OBCXHY24.js → QVUBUYP6.js} +1 -1
  38. package/dist/cdn/{AAUM57XI.js → RHAHQ4DB.js} +1 -1
  39. package/dist/cdn/{AYHTQTVS.js → RSCCUNJ4.js} +1 -1
  40. package/dist/cdn/{W5TNQMAJ.js → RYJ556XB.js} +1 -1
  41. package/dist/cdn/{Y3GFBLXF.js → S5RB3GMN.js} +1 -1
  42. package/dist/cdn/SHQFXQEI.js +2 -0
  43. package/dist/cdn/{MOSQBUUZ.js → SJ2IGQMX.js} +1 -1
  44. package/dist/cdn/T26SIBKB.js +3 -0
  45. package/dist/cdn/{3SMHMC4L.js → TCRMAQDF.js} +1 -1
  46. package/dist/cdn/{JFMNVOWH.js → TFO2AK45.js} +1 -1
  47. package/dist/cdn/U76GHEKJ.js +71 -0
  48. package/dist/cdn/{6WVYNWVR.js → UEYON3AE.js} +1 -1
  49. package/dist/cdn/UIZL3C3H.js +2 -0
  50. package/dist/cdn/{ENXQ33P7.js → UTUOUV3E.js} +1 -1
  51. package/dist/cdn/{VN3AKGAY.js → VTFLDHVU.js} +1 -1
  52. package/dist/cdn/{WXDMML76.js → XLGAHCS7.js} +1 -1
  53. package/dist/cdn/{VBJJQPZT.js → XXCHYJ3I.js} +1 -1
  54. package/dist/cdn/{CU2JLCTZ.js → Y32IJPXS.js} +1 -1
  55. package/dist/cdn/{67CEWYTY.js → YPBSKBT2.js} +1 -1
  56. package/dist/cdn/YVWFYZTI.js +4 -0
  57. package/dist/cdn/{YLIWN2J2.js → YWX2U5OD.js} +1 -1
  58. package/dist/cdn/{ON4EBR25.js → Z7VXHUQA.js} +1 -1
  59. package/dist/cdn/{P666D4WT.js → ZOFZVFBV.js} +1 -1
  60. package/dist/cdn/ZSTC2DJY.js +2 -0
  61. package/dist/cdn/{DVPYGOBV.js → ZZOMKTFL.js} +1 -1
  62. package/dist/cdn/index.js +1 -1
  63. package/dist/chunks/assessBuildRequest.js +1 -6
  64. package/dist/chunks/assessUpdateRequest.js +21 -19
  65. package/dist/chunks/converter.js +75 -44
  66. package/dist/chunks/interfaces.js +26 -26
  67. package/dist/chunks/solution-builder-assistant.js +12 -14
  68. package/dist/chunks/transformQuery.js +1 -1
  69. package/dist/chunks/updateDesign.js +1 -1
  70. package/dist/components/arcgis-solutions-assistant/customElement.js +244 -224
  71. package/dist/components/solutions-deploy-app/customElement.js +1 -1
  72. package/dist/components/solutions-searchsort-toolbar/customElement.js +1 -1
  73. package/dist/docs/api.json +1 -1
  74. package/dist/docs/docs.json +1 -1
  75. package/dist/docs/web-types.json +1 -1
  76. package/dist/solutions-components_commit.txt +8 -5
  77. package/package.json +1 -1
  78. package/dist/cdn/62GTPPV5.js +0 -2
  79. package/dist/cdn/OAUHQK3Y.js +0 -54
  80. package/dist/cdn/PGTLLFW6.js +0 -3
  81. package/dist/cdn/SIODWUWX.js +0 -2
  82. package/dist/cdn/SYISCXZY.js +0 -4
  83. package/dist/cdn/U27263JW.js +0 -2
  84. package/dist/cdn/U2FC3BET.js +0 -2
  85. package/dist/cdn/YEDC2OLI.js +0 -2
@@ -1,5 +1,5 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{d as _r,e as to,f as Li,g as Di,h as Fi}from"./NQH7ZZWD.js";import{a as Ni}from"./S37TPZAO.js";import{a as ic,b as ac,c as lc,f as rs,g as ns,j as cc}from"./LVYAW6XF.js";import b from"./U27263JW.js";import a from"./WDASGI72.js";import{b as jl,c as zl}from"./2B4SGB3I.js";import{b as Ii}from"./RLSY4VUQ.js";import"./RDRCAA3H.js";import{a as Fl}from"./DIBK4RSG.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as Gl,Aa as Qo,Ab as ts,Ba as Yo,Bb as fe,Ca as Xo,Da as yr,Ea as w,Fa as N,Ga as Ri,Ha as $i,J as Kl,K as Ae,L as Wl,M as qo,N as Si,O as Ei,P as Bo,Q as Yn,R as q,Ra as S,S as Ci,T as j,U as Be,V as it,W as Ko,X as Hl,Y as Vl,Z as ki,_ as Wo,a as me,aa as Jl,b as K,ba as Xn,ca as Ho,da as Zl,ea as Ql,fa as Yl,g as Bl,ga as Vo,ha as Xl,ia as Pt,j as qe,ja as Oi,k as Ot,ka as Go,kb as sc,la as $,ma as x,na as Mt,oa as at,pa as ec,qa as Jo,ra as tc,s as Uo,sa as rc,ta as Zo,ua as Pi,va as gr,wa as Mi,wb as eo,xa as nc,y as Qn,ya as oc,zb as es}from"./RDJIKSXN.js";import"./TEHBW75B.js";import"./IHG7KTNC.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./N22MFQSQ.js";import"./N7BXCDA3.js";import"./ZX3UHK6P.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./LP2JYX4X.js";import"./GF4QELNV.js";import{l as Ul,v as Ti}from"./AYSQIO6L.js";import"./YQHYMLC7.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as Dl}from"./HIPZRG2Q.js";import{F as $l,G as Nl,H as Ll,L as vi,h as Cl,i as st,k as kl,l as Ai,q as xi,t as Ol,w as Pl,x as Ml,y as Rl}from"./T3EPRHTT.js";import{c as El}from"./EXBEKVP5.js";export default $arcgis.t(([gl,uW,pW,Hd,Ig,Tg,Dg,_W,bW,CG,rA,dp,pr,Ja,_p,,pp,Ug,{addressToLocations:qg},Bg,Kg,wp,{createRenderer:Wg},{getSchemesByTag:Hg,getSchemes:Vg},{getBackgroundColorTheme:mp},{createAgeRenderer:Gg,createContinuousRenderer:Jg},{getSchemesByTag:sl},{createContinuousRenderer:Zg},{createRenderer:Qg},{getSchemesByTag:Yg},{createRenderer:Xg},{getSchemesByTag:ey},{createRenderer:ty},{getSchemesByTag:ry},{createRenderer:ny},{getSchemesByTag:oy},{createAgeRenderer:sy,createContinuousRenderer:iy},{createRenderer:ay},{getSchemesByTag:ly},cy,bp,Ap,{formatDateOnly:uy,convertDateFormatToIntlOptions:Gs,formatTimeOnly:dy,formatDate:fp},py,my,fy,hy,gy,xp,,{fetchKnowledgeGraph:hp,executeQueryStreaming:yy,executeSearchStreaming:_y},wy,,,,,,,,,,,,,,,,,,,,,,,,,kV,PV,,,,,,,,,,,,,yA,Lp,_A,tJ,nJ,LA,DA,{r:ql},{r:Zn}])=>{var ro=class extends Rl{constructor(e){if(super(e),this.it=Ai,e.type!==Pl.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Ai||e==null)return this._t=void 0,this.it=e;if(e===kl)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;let r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};ro.directiveName="unsafeHTML",ro.resultType=1;var uc=Ml(ro);var d=w;async function os(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{d as _r,e as to,f as Li,g as Di,h as Fi}from"./NQH7ZZWD.js";import{a as Ni}from"./2LCG2XWX.js";import{a as ic,b as ac,c as lc,f as rs,g as ns,j as cc}from"./LVYAW6XF.js";import b from"./P5RZHVDH.js";import a from"./WDASGI72.js";import{b as jl,c as zl}from"./2B4SGB3I.js";import{b as Ii}from"./RLSY4VUQ.js";import"./RDRCAA3H.js";import{a as Fl}from"./DIBK4RSG.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as Gl,Aa as Qo,Ab as ts,Ba as Yo,Bb as fe,Ca as Xo,Da as yr,Ea as w,Fa as N,Ga as Ri,Ha as $i,J as Kl,K as Ae,L as Wl,M as qo,N as Si,O as Ei,P as Bo,Q as Yn,R as q,Ra as S,S as Ci,T as j,U as Be,V as it,W as Ko,X as Hl,Y as Vl,Z as ki,_ as Wo,a as me,aa as Jl,b as K,ba as Xn,ca as Ho,da as Zl,ea as Ql,fa as Yl,g as Bl,ga as Vo,ha as Xl,ia as Pt,j as qe,ja as Oi,k as Ot,ka as Go,kb as sc,la as $,ma as x,na as Mt,oa as at,pa as ec,qa as Jo,ra as tc,s as Uo,sa as rc,ta as Zo,ua as Pi,va as gr,wa as Mi,wb as eo,xa as nc,y as Qn,ya as oc,zb as es}from"./RDJIKSXN.js";import"./TEHBW75B.js";import"./IHG7KTNC.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./N22MFQSQ.js";import"./N7BXCDA3.js";import"./ZX3UHK6P.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./LP2JYX4X.js";import"./GF4QELNV.js";import{l as Ul,v as Ti}from"./AYSQIO6L.js";import"./YQHYMLC7.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as Dl}from"./HIPZRG2Q.js";import{F as $l,G as Nl,H as Ll,L as vi,h as Cl,i as st,k as kl,l as Ai,q as xi,t as Ol,w as Pl,x as Ml,y as Rl}from"./T3EPRHTT.js";import{c as El}from"./EXBEKVP5.js";export default $arcgis.t(([gl,uW,pW,Hd,Ig,Tg,Dg,_W,bW,CG,rA,dp,pr,Ja,_p,,pp,Ug,{addressToLocations:qg},Bg,Kg,wp,{createRenderer:Wg},{getSchemesByTag:Hg,getSchemes:Vg},{getBackgroundColorTheme:mp},{createAgeRenderer:Gg,createContinuousRenderer:Jg},{getSchemesByTag:sl},{createContinuousRenderer:Zg},{createRenderer:Qg},{getSchemesByTag:Yg},{createRenderer:Xg},{getSchemesByTag:ey},{createRenderer:ty},{getSchemesByTag:ry},{createRenderer:ny},{getSchemesByTag:oy},{createAgeRenderer:sy,createContinuousRenderer:iy},{createRenderer:ay},{getSchemesByTag:ly},cy,bp,Ap,{formatDateOnly:uy,convertDateFormatToIntlOptions:Gs,formatTimeOnly:dy,formatDate:fp},py,my,fy,hy,gy,xp,,{fetchKnowledgeGraph:hp,executeQueryStreaming:yy,executeSearchStreaming:_y},wy,,,,,,,,,,,,,,,,,,,,,,,,,kV,PV,,,,,,,,,,,,,yA,Lp,_A,tJ,nJ,LA,DA,{r:ql},{r:Zn}])=>{var ro=class extends Rl{constructor(e){if(super(e),this.it=Ai,e.type!==Pl.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Ai||e==null)return this._t=void 0,this.it=e;if(e===kl)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;let r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};ro.directiveName="unsafeHTML",ro.resultType=1;var uc=Ml(ro);var d=w;async function os(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
 
@@ -35,7 +35,7 @@ Messages to summarize:
35
35
  </messages>`;var Om=x.function().args(x.array(x.custom())).returns(x.union([x.number(),x.promise(x.number())])),Vi=x.object({fraction:x.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().positive("Tokens must be greater than 0").optional(),messages:x.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"}),xc=x.object({fraction:x.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:x.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:x.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"}),US=x.object({model:x.custom(),trigger:x.union([Vi,x.array(Vi)]).optional(),keep:xc.optional(),tokenCounter:Om.optional(),summaryPrompt:x.string().default(km),trimTokensToSummarize:x.number().optional(),summaryPrefix:x.string().optional(),maxTokensBeforeSummary:x.number().optional(),messagesToKeep:x.number().optional()});var YS=x.object({model:x.string().or(x.instanceof(tc)).optional(),systemPrompt:x.string().optional(),maxTools:x.number().optional(),alwaysInclude:x.array(x.string()).optional()});var sE=x.object({applyToInput:x.boolean().optional(),applyToOutput:x.boolean().optional(),applyToToolResults:x.boolean().optional()});var uE=x.object({rules:x.record(x.string(),x.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Pm=["continue","error","end"],Mm="continue";var Rm=x.enum(Pm).default(Mm);x.object({toolName:x.string().optional(),threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:Rm});var AE=x.object({threadToolCallCount:x.record(x.string(),x.number()).default({}),runToolCallCount:x.record(x.string(),x.number()).default({})});var $m=x.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Nm=x.object({content:x.string().describe("Content of the todo item"),status:$m}),kE=x.object({todos:x.array(Nm).default([])});var $E=x.object({threadLimit:x.number().optional(),runLimit:x.number().optional(),exitBehavior:x.enum(["error","end"]).optional()}),NE=x.object({threadModelCallCount:x.number().default(0),runModelCallCount:x.number().default(0)});var ss=x.object({maxRetries:x.number().min(0).default(2),retryOn:x.union([x.function().args(x.instanceof(Error)).returns(x.boolean()),x.array(x.custom())]).default(()=>()=>!0),backoffFactor:x.number().min(0).default(2),initialDelayMs:x.number().min(0).default(1e3),maxDelayMs:x.number().min(0).default(6e4),jitter:x.boolean().default(!0)});var JE=x.object({onFailure:x.union([x.literal("error"),x.literal("continue"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(ss);var nC=x.object({tools:x.array(x.union([x.custom(),x.custom(),x.string()])).optional(),onFailure:x.union([x.literal("error"),x.literal("continue"),x.literal("raise"),x.literal("return_message"),x.function().args(x.instanceof(Error)).returns(x.string())]).default("continue")}).merge(ss);var _C=x.object({enableCaching:x.boolean().optional(),ttl:x.enum(["5m","1h"]).optional(),minMessagesToCache:x.number().optional(),unsupportedModelBehavior:x.enum(["ignore","warn","raise"]).optional()});function no(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
- `,t}function k(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 Gi=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Gi=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 oo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var so=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 T=class extends Error{},W=class t extends T{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 lt({message:n,cause:so(r)});let s=r?.error;return e===400?new br(e,s,n,o):e===401?new Ar(e,s,n,o):e===403?new xr(e,s,n,o):e===404?new vr(e,s,n,o):e===409?new Ir(e,s,n,o):e===422?new Tr(e,s,n,o):e===429?new Sr(e,s,n,o):e>=500?new Er(e,s,n,o):new t(e,s,n,o)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},lt=class extends W{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Me=class extends lt{constructor({message:e}={}){super({message:e??"Request timed out."})}},br=class extends W{},Ar=class extends W{},xr=class extends W{},vr=class extends W{},Ir=class extends W{},Tr=class extends W{},Sr=class extends W{},Er=class extends W{},Cr=class extends T{constructor(){super("Could not parse response content as the length limit was reached")}},kr=class extends T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},$t=class extends W{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let i=r;s=i.error;let a=i.error_description;a&&typeof a=="string"?o=a:s&&(o=s)}super(e,r,o,n),this.error_code=s}},io=class extends T{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var qm=/^[a-z][a-z0-9+.-]*:/i,Sc=t=>qm.test(t),ue=t=>(ue=Array.isArray,ue(t)),Ji=ue;function is(t){return typeof t!="object"?{}:t??{}}function Zi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ec(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ao(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Cc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new T(`${t} must be an integer`);if(e<0)throw new T(`${t} must be a positive integer`);return e};var kc=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var ct="6.43.0";var Rc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Bm(){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 Km=()=>{let t=Bm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":Pc(Deno.build.os),"X-Stainless-Arch":Oc(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":ct,"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":ct,"X-Stainless-OS":Pc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Oc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Wm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"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":ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Wm(){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,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var Oc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Pc=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"),Mc,$c=()=>Mc??(Mc=Km());function as(){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 Qi(...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 ls(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Qi({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Yi(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 Xi(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 Lc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var ea="RFC3986",ta=t=>String(t),ra={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ta},Dc="RFC1738";var cs=(t,e)=>(cs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cs(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var na=1024,Fc=(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(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=na){let c=s.length>=na?s.slice(a,a+na):s,l=[];for(let u=0;u<c.length;++u){let m=c.charCodeAt(u);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===Dc&&(m===40||m===41)){l[l.length]=c.charAt(u);continue}if(m<128){l[l.length]=Ne[m];continue}if(m<2048){l[l.length]=Ne[192|m>>6]+Ne[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Ne[224|m>>12]+Ne[128|m>>6&63]+Ne[128|m&63];continue}u+=1,m=65536+((m&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&63]}i+=l.join("")}return i};function jc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function oa(t,e){if(ue(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Uc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},qc=function(t,e){Array.prototype.push.apply(t,ue(e)?e:[e])},zc,ee={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Fc,encodeValuesOnly:!1,format:ea,formatter:ta,indices:!1,serializeDate(t){return(zc??(zc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Vm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var sa={};function Bc(t,e,r,n,o,s,i,a,c,l,u,m,f,h,b,A,E,y){let v=t,C=y,L=0,B=!1;for(;(C=C.get(sa))!==void 0&&!B;){let Q=C.get(t);if(L+=1,typeof Q<"u"){if(Q===L)throw new RangeError("Cyclic object value");B=!0}typeof C.get(sa)>"u"&&(L=0)}if(typeof l=="function"?v=l(e,v):v instanceof Date?v=f?.(v):r==="comma"&&ue(v)&&(v=oa(v,function(Q){return Q instanceof Date?f?.(Q):Q})),v===null){if(s)return c&&!A?c(e,ee.encoder,E,"key",h):e;v=""}if(Vm(v)||jc(v)){if(c){let Q=A?e:c(e,ee.encoder,E,"key",h);return[b?.(Q)+"="+b?.(c(v,ee.encoder,E,"value",h))]}return[b?.(e)+"="+b?.(String(v))]}let P=[];if(typeof v>"u")return P;let z;if(r==="comma"&&ue(v))A&&c&&(v=oa(v,c)),z=[{value:v.length>0?v.join(",")||null:void 0}];else if(ue(l))z=l;else{let Q=Object.keys(v);z=u?Q.sort(u):Q}let U=a?String(e).replace(/\./g,"%2E"):String(e),ne=n&&ue(v)&&v.length===1?U+"[]":U;if(o&&ue(v)&&v.length===0)return ne+"[]";for(let Q=0;Q<z.length;++Q){let X=z[Q],Tl=typeof X=="object"&&typeof X.value<"u"?X.value:v[X];if(i&&Tl===null)continue;let bi=m&&a?X.replace(/\./g,"%2E"):X,rm=ue(v)?typeof r=="function"?r(ne,bi):ne:ne+(m?"."+bi:"["+bi+"]");y.set(t,L);let Sl=new WeakMap;Sl.set(sa,y),qc(P,Bc(Tl,rm,r,n,o,s,i,a,r==="comma"&&A&&ue(v)?null:c,l,u,m,f,h,b,A,E,Sl))}return P}function Gm(t=ee){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||ee.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=ea;if(typeof t.format<"u"){if(!cs(ra,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ra[r],o=ee.filter;(typeof t.filter=="function"||ue(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Uc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=ee.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:ee.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ee.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ee.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ee.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?ee.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ee.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ee.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ee.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ee.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ee.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ee.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ee.strictNullHandling}}function Kc(t,e={}){let r=t,n=Gm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ue(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=Uc[n.arrayFormat],c=a==="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 h=o[f];n.skipNulls&&r[h]===null||qc(i,Bc(r[h],h,a,c,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 u=i.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&"),u.length>0?m+u:""}function Wc(t){return Kc(t,{arrayFormat:"brackets"})}function Gc(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 Hc;function Or(t){let e;return(Hc??(e=new globalThis.TextEncoder,Hc=e.encode.bind(e)))(t)}var Vc;function ia(t){let e;return(Vc??(e=new globalThis.TextDecoder,Vc=e.decode.bind(e)))(t)}var ye,_e,Nt=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),k(this,ye,new Uint8Array,"f"),k(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Or(e):e;k(this,ye,Gc([_(this,ye,"f"),r]),"f");let n=[],o;for(;(o=Zm(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(o.carriage&&_(this,_e,"f")==null){k(this,_e,o.index,"f");continue}if(_(this,_e,"f")!=null&&(o.index!==_(this,_e,"f")+1||o.carriage)){n.push(ia(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),k(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),k(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?o.preceding-1:o.preceding,i=ia(_(this,ye,"f").subarray(0,s));n.push(i),k(this,ye,_(this,ye,"f").subarray(o.index),"f"),k(this,_e,null,"f")}return n}flush(){return _(this,ye,"f").length?this.decode(`
38
+ `,t}function k(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 Gi=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Gi=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 oo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var so=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 T=class extends Error{},W=class t extends T{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 lt({message:n,cause:so(r)});let s=r?.error;return e===400?new br(e,s,n,o):e===401?new Ar(e,s,n,o):e===403?new xr(e,s,n,o):e===404?new vr(e,s,n,o):e===409?new Ir(e,s,n,o):e===422?new Tr(e,s,n,o):e===429?new Sr(e,s,n,o):e>=500?new Er(e,s,n,o):new t(e,s,n,o)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},lt=class extends W{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Me=class extends lt{constructor({message:e}={}){super({message:e??"Request timed out."})}},br=class extends W{},Ar=class extends W{},xr=class extends W{},vr=class extends W{},Ir=class extends W{},Tr=class extends W{},Sr=class extends W{},Er=class extends W{},Cr=class extends T{constructor(){super("Could not parse response content as the length limit was reached")}},kr=class extends T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},$t=class extends W{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let i=r;s=i.error;let a=i.error_description;a&&typeof a=="string"?o=a:s&&(o=s)}super(e,r,o,n),this.error_code=s}},io=class extends T{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var qm=/^[a-z][a-z0-9+.-]*:/i,Sc=t=>qm.test(t),ue=t=>(ue=Array.isArray,ue(t)),Ji=ue;function is(t){return typeof t!="object"?{}:t??{}}function Zi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ec(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ao(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Cc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new T(`${t} must be an integer`);if(e<0)throw new T(`${t} must be a positive integer`);return e};var kc=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var ct="6.44.0";var Rc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Bm(){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 Km=()=>{let t=Bm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"X-Stainless-OS":Pc(Deno.build.os),"X-Stainless-Arch":Oc(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":ct,"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":ct,"X-Stainless-OS":Pc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Oc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Wm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ct,"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":ct,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Wm(){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,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var Oc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Pc=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"),Mc,$c=()=>Mc??(Mc=Km());function as(){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 Qi(...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 ls(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Qi({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Yi(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 Xi(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 Lc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var ea="RFC3986",ta=t=>String(t),ra={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ta},Dc="RFC1738";var cs=(t,e)=>(cs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cs(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var na=1024,Fc=(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(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=na){let c=s.length>=na?s.slice(a,a+na):s,l=[];for(let u=0;u<c.length;++u){let m=c.charCodeAt(u);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===Dc&&(m===40||m===41)){l[l.length]=c.charAt(u);continue}if(m<128){l[l.length]=Ne[m];continue}if(m<2048){l[l.length]=Ne[192|m>>6]+Ne[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Ne[224|m>>12]+Ne[128|m>>6&63]+Ne[128|m&63];continue}u+=1,m=65536+((m&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&63]}i+=l.join("")}return i};function jc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function oa(t,e){if(ue(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Uc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},qc=function(t,e){Array.prototype.push.apply(t,ue(e)?e:[e])},zc,ee={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Fc,encodeValuesOnly:!1,format:ea,formatter:ta,indices:!1,serializeDate(t){return(zc??(zc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Vm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var sa={};function Bc(t,e,r,n,o,s,i,a,c,l,u,m,f,h,b,A,E,y){let v=t,C=y,L=0,B=!1;for(;(C=C.get(sa))!==void 0&&!B;){let Q=C.get(t);if(L+=1,typeof Q<"u"){if(Q===L)throw new RangeError("Cyclic object value");B=!0}typeof C.get(sa)>"u"&&(L=0)}if(typeof l=="function"?v=l(e,v):v instanceof Date?v=f?.(v):r==="comma"&&ue(v)&&(v=oa(v,function(Q){return Q instanceof Date?f?.(Q):Q})),v===null){if(s)return c&&!A?c(e,ee.encoder,E,"key",h):e;v=""}if(Vm(v)||jc(v)){if(c){let Q=A?e:c(e,ee.encoder,E,"key",h);return[b?.(Q)+"="+b?.(c(v,ee.encoder,E,"value",h))]}return[b?.(e)+"="+b?.(String(v))]}let P=[];if(typeof v>"u")return P;let z;if(r==="comma"&&ue(v))A&&c&&(v=oa(v,c)),z=[{value:v.length>0?v.join(",")||null:void 0}];else if(ue(l))z=l;else{let Q=Object.keys(v);z=u?Q.sort(u):Q}let U=a?String(e).replace(/\./g,"%2E"):String(e),ne=n&&ue(v)&&v.length===1?U+"[]":U;if(o&&ue(v)&&v.length===0)return ne+"[]";for(let Q=0;Q<z.length;++Q){let X=z[Q],Tl=typeof X=="object"&&typeof X.value<"u"?X.value:v[X];if(i&&Tl===null)continue;let bi=m&&a?X.replace(/\./g,"%2E"):X,rm=ue(v)?typeof r=="function"?r(ne,bi):ne:ne+(m?"."+bi:"["+bi+"]");y.set(t,L);let Sl=new WeakMap;Sl.set(sa,y),qc(P,Bc(Tl,rm,r,n,o,s,i,a,r==="comma"&&A&&ue(v)?null:c,l,u,m,f,h,b,A,E,Sl))}return P}function Gm(t=ee){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||ee.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=ea;if(typeof t.format<"u"){if(!cs(ra,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ra[r],o=ee.filter;(typeof t.filter=="function"||ue(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Uc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=ee.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:ee.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ee.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ee.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ee.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?ee.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ee.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ee.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ee.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ee.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ee.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ee.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ee.strictNullHandling}}function Kc(t,e={}){let r=t,n=Gm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ue(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=Uc[n.arrayFormat],c=a==="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 h=o[f];n.skipNulls&&r[h]===null||qc(i,Bc(r[h],h,a,c,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 u=i.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&"),u.length>0?m+u:""}function Wc(t){return Kc(t,{arrayFormat:"brackets"})}function Gc(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 Hc;function Or(t){let e;return(Hc??(e=new globalThis.TextEncoder,Hc=e.encode.bind(e)))(t)}var Vc;function ia(t){let e;return(Vc??(e=new globalThis.TextDecoder,Vc=e.decode.bind(e)))(t)}var ye,_e,Nt=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),k(this,ye,new Uint8Array,"f"),k(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Or(e):e;k(this,ye,Gc([_(this,ye,"f"),r]),"f");let n=[],o;for(;(o=Zm(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(o.carriage&&_(this,_e,"f")==null){k(this,_e,o.index,"f");continue}if(_(this,_e,"f")!=null&&(o.index!==_(this,_e,"f")+1||o.carriage)){n.push(ia(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),k(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),k(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?o.preceding-1:o.preceding,i=ia(_(this,ye,"f").subarray(0,s));n.push(i),k(this,ye,_(this,ye,"f").subarray(o.index),"f"),k(this,_e,null,"f")}return n}flush(){return _(this,ye,"f").length?this.decode(`
39
39
  `):[]}};ye=new WeakMap,_e=new WeakMap;Nt.NEWLINE_CHARS=new Set([`
40
40
  `,"\r"]);Nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Zm(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Jc(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var ds={off:0,error:200,warn:300,info:400,debug:500},aa=(t,e,r)=>{if(t){if(Ec(ds,t))return t;Z(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(ds))}`)}};function lo(){}function us(t,e,r){return!e||ds[t]>ds[r]?lo:e[t].bind(e)}var Qm={error:lo,warn:lo,info:lo,debug:lo},Zc=new WeakMap;function Z(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Qm;let n=Zc.get(e);if(n&&n[0]===r)return n[1];let o={error:us("error",e,r),warn:us("warn",e,r),info:us("info",e,r),debug:us("debug",e,r)};return Zc.set(e,[r,o]),o}var We=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var co,Le=class t{constructor(e,r,n){this.iterator=e,co.set(this,void 0),this.controller=r,k(this,co,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,i=n?Z(n):console;async function*a(){if(s)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let l of Ym(e,r))if(!c){if(l.data.startsWith("[DONE]")){c=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let u;try{u=JSON.parse(l.data)}catch(m){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),m}if(u&&u.error)throw new W(void 0,u.error,void 0,e.headers);yield o?{event:l.event,data:u}:u}else{let u;try{u=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new W(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}c=!0}catch(l){if(oo(l))return;throw l}finally{c||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let a=new Nt,c=Yi(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*i(){if(o)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(oo(c))return;throw c}finally{a||r.abort()}}return new t(i,r,n)}[(co=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let i=n.next();e.push(i),r.push(i)}return s.shift()}});return[new t(()=>o(e),this.controller,_(this,co,"f")),new t(()=>o(r),this.controller,_(this,co,"f"))]}toReadableStream(){let e=this,r;return Qi({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let i=Or(JSON.stringify(o)+`
41
41
  `);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Ym(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new T("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new T("Attempted to iterate over a response with no body");let r=new la,n=new Nt,o=Yi(t.body);for await(let s of Xm(o))for(let i of n.decode(s)){let a=r.decode(i);a&&(yield a)}for(let s of n.flush()){let i=r.decode(s);i&&(yield i)}}async function*Xm(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Or(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Jc(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var la=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
@@ -74,7 +74,7 @@ Title: {title}
74
74
  Description: {description}`,sp=`Name: {name}
75
75
  Alias: {alias}
76
76
  Description: {description}`,ip=w.object({schemaVersion:w.literal(tp),modified:w.number().int().nonnegative(),embeddings:w.object({modelProvider:w.literal(rp),model:w.literal(np),dimensions:w.literal(zn),templates:w.object({layer:w.string().default(op),field:w.string().default(sp)})}),layers:w.array(w.object({id:w.string().min(1),name:w.string().min(1),title:w.string().catch(""),description:w.string().catch(""),vector:w.array(w.number()).length(zn,{message:`Layer vector must be exactly ${zn} dimensions`}),fields:w.array(w.object({name:w.string().min(1),alias:w.string().catch(""),description:w.string().catch(""),vector:w.array(w.number()).length(zn,{message:`Field vector must be exactly ${zn} dimensions`})}))})).default([])});var ap=(t,e)=>{let r=Yo.fromTemplate(t);return Xo.fromMessages([r,...e])},$g=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=ap(e,o??[]),a=await Ga({modelTier:r,temperature:n,config:s});return i.pipe(a)},Vs=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,config:i}=t,a=await(await $g({promptText:e,modelTier:r,temperature:n,messages:o,config:i})).invoke(s??{},i);if(typeof a=="string")return a;let c=a.content;return typeof c=="string"?c:JSON.stringify(c)},Mo=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i,config:a}=t,c=ap(e,o??[]),l=(await Ga({modelTier:r,temperature:n,config:a})).withStructuredOutput(i);return await c.pipe(l).invoke(s??{},a)};var Ng=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),oW=d.object({fields:d.array(Ng)});var sW=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var lp=async t=>{try{return await(await ep()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var up=t=>Array.isArray(t)&&t.every(Yn),Fg=t=>typeof t=="object"&&t!=null&&"messages"in t&&up(t.messages),jg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,ot=class extends sc{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,i)=>this.run(s,i)}),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},i=await n.invoke(o,s);return Yn(i)&&i.getType()==="tool"||Ot(i)?i:new q({status:"success",name:n.name,content:typeof i=="string"?i:JSON.stringify(i),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||Qn(o))throw o;return new q({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(jg(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(up(t))s=t;else if(Fg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),a;for(let c=s.length-1;c>=0;c-=1){let l=s[c];if(Be(l)){a=l;break}}if(a==null||!Be(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,e,t))??[])}if(!r.some(Ot))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Ot(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Bl(i))?o?o.goto.push(...s.goto):o=new qe({graph:qe.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var n2=S.Root({llmInputMessages:S({reducer:(t,e)=>eo([],e),default:()=>[]})});var Ro=(t,e)=>e??t,by=S.Root({...Va(),intent:S({reducer:Ro}),vectorSearchLayerResults:S({reducer:Ro,default:()=>[]}),vectorSearchFieldResults:S({reducer:Ro}),navigationInternalState:S({reducer:Ro,default:()=>({toolCallMessage:void 0})})});async function Ay(t,e){let r=pr.getDefault().helperServices,n=r.geocode.find(u=>u.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Ja.assetsPath?.endsWith("/")?Ja.assetsPath:`${Ja.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await qg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!i?.extent||!i.location)throw new Error(`Could not find location for: ${t}`);let a=new Bg({url:s,width:24,height:24}),c=new Ug({geometry:i.location,symbol:a});e.graphics.removeAll(),e.graphics.add(c),await e.goTo(i.extent);let l={address:i.address??"",location:i.location?i.location.toJSON():null,extent:i.extent?i.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var xy=["mapView"];function ze(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=xy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function vy({address:t},e){let{mapView:r}=ze(e);return await Ay(t,r)}var Iy=d.object({address:d.string().describe("The full address or place name to locate.")}),Ty=N(vy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Iy});async function Sy(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 Ey({bookmarkName:t},e){let{mapView:r}=ze(e);return await Promise.resolve(Sy(t,r))}var Cy=w.object({bookmarkName:w.string().describe("The name of the bookmark to navigate to.")}),ky=N(Ey,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Cy});async function Oy(t,e,r){let n=r.map?.allLayers.find(i=>i.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:i,count:a}=await n.queryExtent(s);if(a===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(i)await r.goTo(i);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let c={layerId:t,layerTitle:n.title??t,where:o,count:a};return{text:`Successfully zoomed to ${a} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:c}}}}catch(i){return console.error("Error in goToFeatures:",i),{text:`Error: ${i instanceof Error?i.message:"Unknown error"}`,where:o}}}async function Py({layerId:t,where:e},r){let{mapView:n}=ze(r);return await Oy(t,e,n)}var My=w.object({layerId:w.string().describe("The layerId of the layer to zoom to."),where:w.string().describe("The sql-92 where clause used to query features to zoom to")}),Ry=N(Py,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:My});async function $y(t){let e=new Kg({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}=ze(e);return await $y(r)}var Ly=w.object({}),Dy=N(Ny,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Ly});async function Fy(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 jy(t,e){let{mapView:r}=ze(e);return await Fy(r)}var zy=d.object({}),Uy=N(jy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:zy});async function qy(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 By({layerId:t},e){let{mapView:r}=ze(e);return await qy(t,r)}var Ky=w.object({layerId:w.string().describe("The id of the layer to navigate to")}),Wy=N(By,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Ky});async function Hy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Vy({scale:t},e){let{mapView:r}=ze(e);return await Hy(t,r)}var Gy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),Jy=N(Vy,{name:"goToScale",description:"Go to the specified view scale.",schema:Gy});async function Zy(t,e,r){let n={target:new wp({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 Qy({center:t,zoom:e,scale:r},n){let{mapView:o}=ze(n);return await Zy(t,o,{zoom:e,scale:r})}var Yy=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Xy=N(Qy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Yy});async function e_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function t_({zoom:t},e){let{mapView:r}=ze(e);return await e_(t,r)}var r_=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),n_=N(t_,{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:r_}),gp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./VDI7SDRK.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./275IZ5I6.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./MV7GEGP5.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./CRDFUDM4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./EL3OIP52.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./TLIIJ2QC.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./PLXHBQBF.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./YPDXQEUA.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./OAUHQK3Y.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./54TJQLYJ.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./EUI6UDCN.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./VDZT4UXB.js").then(t=>t.default)});async function St(t){let e=Object.entries(gp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
77
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(jg(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(up(t))s=t;else if(Fg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),a;for(let c=s.length-1;c>=0;c-=1){let l=s[c];if(Be(l)){a=l;break}}if(a==null||!Be(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,e,t))??[])}if(!r.some(Ot))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Ot(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Bl(i))?o?o.goto.push(...s.goto):o=new qe({graph:qe.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var n2=S.Root({llmInputMessages:S({reducer:(t,e)=>eo([],e),default:()=>[]})});var Ro=(t,e)=>e??t,by=S.Root({...Va(),intent:S({reducer:Ro}),vectorSearchLayerResults:S({reducer:Ro,default:()=>[]}),vectorSearchFieldResults:S({reducer:Ro}),navigationInternalState:S({reducer:Ro,default:()=>({toolCallMessage:void 0})})});async function Ay(t,e){let r=pr.getDefault().helperServices,n=r.geocode.find(u=>u.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Ja.assetsPath?.endsWith("/")?Ja.assetsPath:`${Ja.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await qg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!i?.extent||!i.location)throw new Error(`Could not find location for: ${t}`);let a=new Bg({url:s,width:24,height:24}),c=new Ug({geometry:i.location,symbol:a});e.graphics.removeAll(),e.graphics.add(c),await e.goTo(i.extent);let l={address:i.address??"",location:i.location?i.location.toJSON():null,extent:i.extent?i.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var xy=["mapView"];function ze(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=xy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function vy({address:t},e){let{mapView:r}=ze(e);return await Ay(t,r)}var Iy=d.object({address:d.string().describe("The full address or place name to locate.")}),Ty=N(vy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Iy});async function Sy(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 Ey({bookmarkName:t},e){let{mapView:r}=ze(e);return await Promise.resolve(Sy(t,r))}var Cy=w.object({bookmarkName:w.string().describe("The name of the bookmark to navigate to.")}),ky=N(Ey,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Cy});async function Oy(t,e,r){let n=r.map?.allLayers.find(i=>i.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:i,count:a}=await n.queryExtent(s);if(a===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(i)await r.goTo(i);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let c={layerId:t,layerTitle:n.title??t,where:o,count:a};return{text:`Successfully zoomed to ${a} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:c}}}}catch(i){return console.error("Error in goToFeatures:",i),{text:`Error: ${i instanceof Error?i.message:"Unknown error"}`,where:o}}}async function Py({layerId:t,where:e},r){let{mapView:n}=ze(r);return await Oy(t,e,n)}var My=w.object({layerId:w.string().describe("The layerId of the layer to zoom to."),where:w.string().describe("The sql-92 where clause used to query features to zoom to")}),Ry=N(Py,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:My});async function $y(t){let e=new Kg({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}=ze(e);return await $y(r)}var Ly=w.object({}),Dy=N(Ny,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Ly});async function Fy(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 jy(t,e){let{mapView:r}=ze(e);return await Fy(r)}var zy=d.object({}),Uy=N(jy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:zy});async function qy(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 By({layerId:t},e){let{mapView:r}=ze(e);return await qy(t,r)}var Ky=w.object({layerId:w.string().describe("The id of the layer to navigate to")}),Wy=N(By,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Ky});async function Hy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Vy({scale:t},e){let{mapView:r}=ze(e);return await Hy(t,r)}var Gy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),Jy=N(Vy,{name:"goToScale",description:"Go to the specified view scale.",schema:Gy});async function Zy(t,e,r){let n={target:new wp({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 Qy({center:t,zoom:e,scale:r},n){let{mapView:o}=ze(n);return await Zy(t,o,{zoom:e,scale:r})}var Yy=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Xy=N(Qy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Yy});async function e_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function t_({zoom:t},e){let{mapView:r}=ze(e);return await e_(t,r)}var r_=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),n_=N(t_,{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:r_}),gp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./VDI7SDRK.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./275IZ5I6.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./MV7GEGP5.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./CRDFUDM4.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./EL3OIP52.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./TLIIJ2QC.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./PLXHBQBF.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./YPDXQEUA.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./U76GHEKJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./54TJQLYJ.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./6WPQPRJ5.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./VDZT4UXB.js").then(t=>t.default)});async function St(t){let e=Object.entries(gp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
78
78
  Available prompts:
79
79
  ${Object.keys(gp).join(`
80
80
  `)}`);return await e[1]()}var Kn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function o_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=Hg({basemapTheme:await mp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=Vg({basemapTheme:await mp(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(a=>({field:a,label:r.fields.find(c=>c.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:i}}async function s_(t){return await Wg(t)}async function i_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"chart-size":"chart",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=await o_(c),u=await s_(l);return a.renderer=u.renderer,a.visible=!0,`Chart renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var a_=["mapView"];function Oe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=a_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function l_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await i_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var c_=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),u_=N(l_,{name:"chart",description:`Label: Charts
@@ -262,7 +262,9 @@ ${i}`};async function Qb(t,e){let r=await St("arcgis_knowledge_lucene_generation
262
262
  This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
263
263
  _Example: “How many features are there?”_
264
264
  _Example: “What’s the average population?”_
265
- _Example: “Which values are in the status field?”_`;var JV=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
265
+ _Example: “Which values are in the status field?”_
266
+
267
+ 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 JV=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
266
268
 
267
269
  _Example: “Tell me about this map”_
268
270
  _Example: “List all layers in this map”_
@@ -271,9 +273,9 @@ ${i}`};async function Qb(t,e){let r=await St("arcgis_knowledge_lucene_generation
271
273
  _Example: “What can you do?”_
272
274
  _Example: “What can I ask”_
273
275
 
274
- Even if the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent.
276
+ If the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent so it can politely refuse and redirect to map-related questions.
275
277
 
276
- 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 accordingly.
278
+ 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.
277
279
  _Example: "Create a chart"_
278
280
  _Example: "Create a table"_`;var mG=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).
279
281
  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.
@@ -322,11 +324,11 @@ ${r}`},TA=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedS
322
324
  Title: {title}
323
325
  Description: {description}`,RA=`Name: {name}
324
326
  Alias: {alias}
325
- Description: {description}`,sJ=w.object({schemaVersion:w.literal(kA),modified:w.number().int().nonnegative(),embeddings:w.object({modelProvider:w.literal(OA),model:w.literal(PA),dimensions:w.literal(zo),templates:w.object({layer:w.string().default(MA),field:w.string().default(RA)})}),layers:w.array(w.object({id:w.string().min(1),name:w.string().min(1),title:w.string().catch(""),description:w.string().catch(""),vector:w.array(w.number()).length(zo,{message:`Layer vector must be exactly ${zo} dimensions`}),fields:w.array(w.object({name:w.string().min(1),alias:w.string().catch(""),description:w.string().catch(""),vector:w.array(w.number()).length(zo,{message:`Field vector must be exactly ${zo} dimensions`})}))})).default([])});var $A=(t,e)=>{let r=Yo.fromTemplate(t);return Xo.fromMessages([r,...e])};var Fp=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i}=t,a=$A(e,o??[]),c=(await EA(r,n)).withStructuredOutput(i);return await a.pipe(c).invoke(s??{})};var NA=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),iJ=d.object({fields:d.array(NA)});var aJ=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var FA=Cl`:host{display:block;height:100%}.margin-lg{margin:var(--calcite-spacing-lg)}.display-flex-row{display:flex;flex-direction:row}.assistant-split-container{display:flex;width:100%;height:calc(100vh - 78px);overflow:hidden;border-radius:10px}.assistant-panel{display:flex;flex-direction:column;height:100%;border:1px solid var(--calcite-color-surface-3);background-color:var(--calcite-color-surface-2);overflow:hidden}.chat-panel{min-width:320px}.builder-panel{min-width:320px;max-width:100%;border-left:1px solid var(--calcite-color-surface-3)}.panel-actions{display:flex;gap:8px;padding:6px;align-items:center}.builder-header,.builder-footer{padding:10px;background:var(--calcite-color-surface-1);border-bottom:1px solid var(--calcite-color-surface-3)}.builder-content{flex:1;overflow:auto;padding:12px}.builder-content pre{white-space:pre-wrap;word-wrap:break-word;max-height:100%;overflow:auto}.builder-actions{display:flex;gap:6px;align-items:center}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-surface-4);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-surface-1);border-radius:10px;padding:10px}.chat-panel{--calcite-color-focus: var(--calcite-color-brand);--calcite-panel-border-color: var(--calcite-color-border-2);--calcite-internal-panel-header-vertical-padding: 0px;--calcite-panel-header-content-space: 0px;border:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);height:100%}.header-content{display:flex;align-items:center;gap:var(--calcite-spacing-sm);height:65px;box-sizing:border-box;padding-inline-start:var(--calcite-space-2xl)}.header-title{font-size:var(--calcite-font-size-md);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-text-1)}.beta-chip{--calcite-chip-corner-radius: var(--calcite-corner-radius-half)}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button,.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-surface-1, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-surface-3);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-surface-4);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-surface-4)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;align-items:center;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-surface-1)}#closeAssistantButton{--calcite-action-text-color: var(--calcite-color-text-1)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-surface-1)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;async function be(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
327
+ Description: {description}`,sJ=w.object({schemaVersion:w.literal(kA),modified:w.number().int().nonnegative(),embeddings:w.object({modelProvider:w.literal(OA),model:w.literal(PA),dimensions:w.literal(zo),templates:w.object({layer:w.string().default(MA),field:w.string().default(RA)})}),layers:w.array(w.object({id:w.string().min(1),name:w.string().min(1),title:w.string().catch(""),description:w.string().catch(""),vector:w.array(w.number()).length(zo,{message:`Layer vector must be exactly ${zo} dimensions`}),fields:w.array(w.object({name:w.string().min(1),alias:w.string().catch(""),description:w.string().catch(""),vector:w.array(w.number()).length(zo,{message:`Field vector must be exactly ${zo} dimensions`})}))})).default([])});var $A=(t,e)=>{let r=Yo.fromTemplate(t);return Xo.fromMessages([r,...e])};var Fp=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i}=t,a=$A(e,o??[]),c=(await EA(r,n)).withStructuredOutput(i);return await a.pipe(c).invoke(s??{})};var NA=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),iJ=d.object({fields:d.array(NA)});var aJ=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var FA=Cl`:host{display:block;height:100%}.margin-lg{margin:var(--calcite-spacing-lg)}.display-flex-row{display:flex;flex-direction:row}.assistant-split-container{display:flex;width:100%;height:calc(100vh - 78px);overflow:hidden;border-radius:10px}.assistant-panel{display:flex;flex-direction:column;height:100%;border:1px solid var(--calcite-color-surface-3);background-color:var(--calcite-color-surface-2);overflow:hidden}.chat-panel{min-width:320px}.builder-panel{min-width:320px;max-width:100%;border-left:1px solid var(--calcite-color-surface-3)}.panel-actions{display:flex;gap:8px;padding:6px;align-items:center}.builder-header,.builder-footer{padding:10px;background:var(--calcite-color-surface-1);border-bottom:1px solid var(--calcite-color-surface-3)}.builder-content{flex:1;overflow:auto;padding:12px}.builder-content pre{white-space:pre-wrap;word-wrap:break-word;max-height:100%;overflow:auto}.builder-actions{display:flex;gap:6px;align-items:center}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-surface-4);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-surface-1);border-radius:10px;padding:10px}.chat-panel{--calcite-color-focus: var(--calcite-color-brand);--calcite-panel-border-color: var(--calcite-color-border-2);--calcite-internal-panel-header-vertical-padding: 0px;--calcite-panel-header-content-space: 0px;border:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);height:100%}.header-content{display:flex;align-items:center;gap:var(--calcite-spacing-sm);height:65px;box-sizing:border-box;padding-inline-start:var(--calcite-space-2xl)}@media(resolution:1.25dppx),(resolution:1.75dppx){.chat-panel{margin-top:.5px}}.header-title{font-size:var(--calcite-font-size-md);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-text-1)}.beta-chip{--calcite-chip-corner-radius: var(--calcite-corner-radius-half)}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button,.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-surface-1, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-surface-3);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-surface-4);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-surface-4)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;align-items:center;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-surface-1)}#closeAssistantButton{--calcite-action-text-color: var(--calcite-color-text-1)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-surface-1)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;async function be(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
326
328
  Available prompts:
327
329
  ${Object.keys(t).join(`
328
- `)}`);return await r[1]()}function _i(t){return t?.configurable?.context?.translations}function Up(t){if(typeof window>"u"||t.length<=1)return;let e=t.map(n=>n.solution.id),r=t.map(n=>n.solution.title);window.dispatchEvent(new CustomEvent("searchTermSet",{detail:{scope:"all-solutions",searchTerm:""}})),window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant",{detail:{solutionIds:e,solutionTitles:r},bubbles:!0,composed:!0})),window.dispatchEvent(new CustomEvent("navTabSelected",{detail:{tabType:"all-solutions"}}))}function qp(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var jA=w.object({needsContext:w.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:w.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),jp=t=>t?.signal?.aborted??!1,Bp=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./AS6VINEU.js").then(t=>t.default),"./prompts/transformQuery.md":()=>import("./SNZRQPXI.js").then(t=>t.default)});function zA(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">&#91;$1&#93;</a></sup>')}function UA(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function qA(t,e){let r=[];return(e?.configurable?.context?.configContext.allCards??[]).forEach(n=>{let o=n.title;if(!o)return;let s=new RegExp(`(?<![\\p{L}\\p{N}])${o}(?![\\p{L}\\p{N}])`,"giu"),i=!1;t=t.replace(s,(a,c,l)=>{let u=l.slice(0,c);return/<img[^>]*alt\s*=\s*["'][^"']*$/i.test(u)?a:(i=!0,`<a href="" target="solutionId:${n.deployCommonId}">${o}</a>`)}),i&&r.push({solution:{title:n.title,id:n.deployCommonId,snippet:n.snippet,description:n.description},score:100})}),{source:t,allMatches:r}}function BA(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function Kp(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function _l(t,e,r){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",token:r},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status} calling ${e}`);return n.json()}var KA=t=>new Promise(e=>setTimeout(e,t));async function WA(t,e){let r=t.agentExecutionContext.userRequest,n=e?.configurable?.context?.lastTurnAgent,o=t.agentExecutionContext.messages??[];if(!n||o.length<=1||n==="explorer")return r;try{let s=await be(Bp,"transformQuery"),i=await kt({promptText:s,modelTier:"fast",temperature:0,schema:jA,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return console.debug(`Rephrased query from "${r}" to "${i.rewrittenQuery.trim()}"`),i.rewrittenQuery.trim()}catch{}return r}var HA=S.Root({...ii(),solutionResponse:S({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:S({reducer:(t,e)=>e??null,default:()=>null}),conversationId:S({reducer:(t,e)=>e??t,default:()=>null})}),VA=()=>new fe(HA).addNode("initializeAgent",JA).addNode("askSolutionsQuestions",GA).addEdge(me,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",K),Wp=async(t,e,r,n)=>{if(!t)return;let o=Kp(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:r,use_llm:!1}}}}};n&&(s.conversationId=n),_l(s,o,e??"")},GA=async(t,e)=>{if(jp(e))return{};let r=_i(e),n=t.documentSkillUrl,o=[],s=await WA(t,e);await Pe({text:r.agentProgress.explorerAgentSearching},e);let i=await _l({message:s,conversationId:e?.configurable?.context?.convoId??void 0,context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:e?.configurable?.context?.configContext.locale??"en",use_llm:!1}}}}},n,e?.configurable?.context?.token??"");i.conversationId&&e?.configurable?.context?.setConversationId&&e.configurable.context.setConversationId(i.conversationId);let a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},c="",l=async u=>{let m=u.context?.results?.[0]?.reply??"";if(m!==""){let h=zA(m),b=UA(h),A=qA(b,e);c=A.source,o=[...o,...A.allMatches.filter(E=>!o.some(y=>y.solution.id===E.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let h="";f===1?h=r.agentProgress.explorerAgentReading:f===2?h=r.agentProgress.explorerAgentReviewing:f===3&&(h=r.agentProgress.explorerAgentPreparing),await Pe({text:h},e)}};for(await l(i);a.hasMore;){if(jp(e))return{};await KA(500),i=await _l({conversationId:a.conversationId,ackSequenceNumber:a.ackSequenceNumber,inquiryId:a.inquiryId},n,e?.configurable?.context?.token??""),a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},await l(i)}return Kp(e?.configurable?.context.portal)&&Wp(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?qp(o[0].solution.id):Up(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},JA=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=BA(e.configurable.context.portal)),{documentSkillUrl:r}};await be(Bp,"solutions_explorer_description");var Hp=t=>{if(t&&Array.isArray(t.id)&&t.id.length>0)return t.id[t.id.length-1].replace("Message","").toLowerCase();if(t&&typeof t._getType=="function")try{return t._getType()}catch{return"human"}return"human"},ZA=t=>{let e=Hp(t);if(t&&t.kwargs)return{role:e,...t.kwargs};if(t&&typeof t=="object"){let r={role:e,content:typeof t.content=="string"?t.content:String(t.content||"")};return t.id&&(r.id=t.id),t.name&&(r.name=t.name),t.additional_kwargs&&(r.additional_kwargs=t.additional_kwargs),t.response_metadata&&(r.response_metadata=t.response_metadata),r}return{role:"human",content:String(t)}},QA=t=>Hp(t)==="human",YA=(t,e=3)=>t.filter(r=>QA(r)).slice(-e).map(ZA),XA=(t,e=" ")=>YA(t).map(r=>r.content).join(e).trim(),ex={understandingRequest:"Understanding your request...",selectTemplatePrompt:"This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.",searchingExistingSolutions:"Searching for existing solutions...",existingSolutionMatch:"I found one or more existing solutions that match your use case. These are ready-to-use solutions that may already meet your needs and can be deployed now. Do you want to continue building your own solution?",continueBuildingYes:"Yes, I want to build a new solution",continueBuildingNo:"No, I\u2019ll review existing solutions",continueBuildingDeclined:"Sounds good. We can focus on existing solutions. Let me know if I can help answer any questions or provide more details.",creatingDesign:"Generating solution design...",updatingDesign:"Updating solution design...",applyChangeFailed:"I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.",createDesignFailed:"I wasn't able to create a solution design from that request. Please try rephrasing and try again.",discardMessage:"Are you sure you want to discard your solution?",discardForNewSolution:"I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?"},tx={builderMessages:ex},yi=class t{constructor(e,r,n=!0){this.isValid=!0,this.issues=[],this.fieldNameRegistry=null,this.response=e,this.template=r,this.newDesign=n,this.validate()}static{this.INVALID_NAME_CHARS=/[><~`$^+=|]/gu}static{this.NAME_MAX_LENGTH=250}static{this.DESCRIPTION_MAX_LENGTH=2048}static{this.SERVICE_NAME_MAX_LENGTH=100}static{this.FIELD_NAME_MAX_LENGTH=31}validate(){this.compareModels(),this.validateResponse()}compareModels(){this._compareStrings(),this._compareItems(),this._compareFeatureLayers()}validateResponse(){this._validateSolutionProps(),this._validateItems(),this._validateFeatureLayer()}_compareStrings(){let e=new Set(this.response.solution.strings.map(n=>n.key)),r=new Map(this.template.solution.strings.map(n=>[n.key,n]));[...r.keys()].every(n=>e.has(n))||(this.newDesign?this._reconcileStringKeys():this._logIssue("String keys in llm response do not match the template."));for(let n of this.response.solution.strings){if(n.value)continue;let o=r.get(n.key)?.value;this.newDesign&&o?(n.value=o,this._logAutoFix(`String key '${n.key}' had no value. Auto-fixed by restoring the template value.`)):this._logIssue(`String key '${n.key}' has no value in the design. It must be populated.`)}}_reconcileStringKeys(){let e=new Set(this.response.solution.strings.map(r=>r.key));for(let r of this.template.solution.strings)e.has(r.key)||(this.response.solution.strings.push({...r}),this._logAutoFix(`String key '${r.key}' was missing from the design. Auto-fixed by re-adding it from the template.`))}_compareItems(){let e=new Set(this.template.items.map(n=>n.id)),r=new Set(this.response.items.map(n=>n.id));e.size===r.size&&[...e].every(n=>r.has(n))||(this.newDesign?this._reconcileItems():this._logIssue("Item IDs in design do not match the template."))}_reconcileItems(){let e=new Set(this.template.items.map(o=>o.id)),r=new Set(this.response.items.map(o=>o.id)),n=[...r].filter(o=>!e.has(o));n.length&&(this.response.items=this.response.items.filter(o=>e.has(o.id)),this._logAutoFix(`Removed items not present in the template: ${n.join(", ")}.`));for(let o of this.template.items)r.has(o.id)||(this.response.items.push({...o}),this._logAutoFix(`Item '${o.id}' was missing from the design. Auto-fixed by adding it from the template.`))}_compareFeatureLayers(){let e=this.template.featureLayer,r=this.response.featureLayer;if(e.itemId!==r.itemId){let n=r.itemId;r.itemId=e.itemId,this._logAutoFix(`Feature Layer itemId '${n}' did not match the template. Auto-fixed to '${e.itemId}'.`)}if(!e.addLayers){let n=new Set(e.layers.map(s=>s.id)),o=new Set(r.layers.map(s=>s.id));if(!(n.size===o.size&&[...n].every(s=>o.has(s))))this._logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`);else for(let s of e.layers){if(s.type){let a=r.layers.find(c=>c.id===s.id);if(a&&a.type!==s.type)if(this.newDesign){let c=a.type;a.type=s.type,this._logAutoFix(`Layer '${s.id}' type '${c}' is immutable. Auto-fixed back to template type '${s.type}'.`)}else this._logIssue(`Layer '${s.id}' type '${a.type}' does not match template type '${s.type}'. This layer type is immutable.`)}let i=r.layers.find(a=>a.id===s.id);i&&this._validateRequiredFields(i,s)}}}_validateRequiredFields(e,r){let n=new Map(e.requiredFields.map(o=>[o.name.toLowerCase(),o]));for(let o of r.requiredFields){let s=n.get(o.name.toLowerCase());if(!s){this.newDesign?(e.requiredFields.push({...o}),this._logAutoFix(`Layer '${e.name}' was missing required field '${o.name}'. Auto-fixed by re-adding it from the template.`)):this._logIssue(`Layer '${e.name}' is missing required field '${o.name}'.`);continue}this._enforceRequiredFieldImmutability(e,s,o)}}_enforceRequiredFieldImmutability(e,r,n){let o=[];if(r.type!==n.type&&o.push("type"),(r.length??null)!==(n.length??null)&&o.push("length"),this._choiceListsEqual(r.choiceList,n.choiceList)||o.push("choiceList"),!o.length)return;let s=o.length===1?"property":"properties";this.newDesign?(r.type=n.type,r.length=n.length,r.choiceList=Array.isArray(n.choiceList)?[...n.choiceList]:n.choiceList??null,this._logAutoFix(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). Auto-fixed by reverting to the template.`)):this._logIssue(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). These cannot be modified.`)}_choiceListsEqual(e,r){let n=Array.isArray(e)?e:null,o=Array.isArray(r)?r:null;if(n===null&&o===null)return!0;if(n===null||o===null)return!1;let s=new Set(n),i=new Set(o);return s.size===i.size&&[...s].every(a=>i.has(a))}_validateSolutionProps(){let e=this.response.solution.title??"",r=this.response.solution.description,n=/[/\\]/u.test(e),o=this.newDesign?e.replace(/[/\\]/gu,""):e;this.newDesign&&o!==e?(this.response.solution.title=o,this._logAutoFix("Solution title contained forward or back slashes. Auto-fixed by removing them.")):!this.newDesign&&n&&this._logIssue("Solution title contains forbidden forward or back slashes.");let s=rs(o);if(s.isValid||this._tryFixName(s.errorType,o,i=>{this.response.solution.title=i},"Solution title","Solution Title")||this._logIssue(`Solution title is invalid (${s.errorType}).`),r){let i=ns(r,t.DESCRIPTION_MAX_LENGTH,!0);i.isValid||this._tryFixDescription(r,a=>{this.response.solution.description=a},"Solution description")||this._logIssue(`Solution description is invalid (${i.errorType}).`)}}_validateItems(){let e=new Set(["Feature Layer (hosted)","Feature Layer (hosted, view)"]);for(let r of this.response.items){if(e.has(r.type)&&r.title.length>t.SERVICE_NAME_MAX_LENGTH)if(this.newDesign){let o=r.title;r.title=r.title.slice(0,t.SERVICE_NAME_MAX_LENGTH).trim(),this._logAutoFix(`Service name '${o}' exceeded ${t.SERVICE_NAME_MAX_LENGTH} characters. Auto-fixed to '${r.title}'.`)}else this._logIssue(`Service name '${r.title}' exceeds 100 characters.`);let n=rs(r.title??"");if(n.isValid||this._tryFixName(n.errorType,r.title??"",o=>{r.title=o},`Item '${r.id}' title`,"Item Title")||this._logIssue(`Item '${r.id}' title is invalid (${n.errorType}).`),r.description){let o=ns(r.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(r.description,s=>{r.description=s},`Item '${r.id}' description`)||this._logIssue(`Item '${r.id}' description is invalid (${o.errorType}).`)}}}_validateFeatureLayer(){this.response.featureLayer.layers.length||this._logIssue("Feature layer item must contain at least one layer.");let e=this.response.featureLayer.layers.map(r=>r.name.toLowerCase());e.length!==new Set(e).size&&(this.newDesign?this._dedupeLayerNames(this.response.featureLayer.layers):this._logIssue(`Layer names must be unique (case-insensitive). Layer names in design: ${e}.`));for(let r of this.response.featureLayer.layers)this._validateLayer(r,this.response.featureLayer.addLayers)}_dedupeLayerNames(e){let r=new Set;for(let n of e){let o=(n.name??"").toLowerCase();if(r.has(o)){let s=n.name;n.name=this._makeUniqueName(n.name??"Layer",r),this._logAutoFix(`Duplicate layer name '${s}'. Auto-fixed to '${n.name}'.`)}r.add(n.name.toLowerCase())}}_validateLayer(e,r){!r&&e.typeMutable===!0&&e.type==="Table"&&(this.newDesign?(e.type="Point",this._logAutoFix(`Layer '${e.name}' cannot be a Table. Auto-fixed to 'Point'.`)):this._logIssue(`Layer '${e.name}' cannot be a Table. It may be a Point, Line, or Polygon.`));let n=rs(e.name??"");if(n.isValid||this._tryFixName(n.errorType,e.name??"",o=>{e.name=o},`Layer '${e.name}' name`,"Layer Title")||this._logIssue(`Layer '${e.name}' name is invalid (${n.errorType}).`),e.description){let o=ns(e.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(e.description,s=>{e.description=s},`Layer '${e.name}' description`)||this._logIssue(`Layer '${e.name}' description is invalid (${o.errorType}).`)}this._validateLayerFields(e)}_validateLayerFields(e){let r=e.systemFields??[];this.fieldNameRegistry=new Set([...e.customFields,...e.requiredFields,...r].map(s=>s.name.toLowerCase()));for(let s of[...e.customFields,...e.requiredFields])this._validateField(s);this.fieldNameRegistry=null;let n=new Set(e.requiredFields.map(s=>s.name.toLowerCase())),o=new Set(n);for(let s of e.customFields){let i=s.name.toLowerCase();if(o.has(i)){let a=n.has(i)?"a required field name":"another field with the same name";if(this.newDesign){let c=s.name;s.name=this._makeUniqueName(s.name,o),this._logAutoFix(`Layer '${e.name}' field '${c}' collided with ${a}. Auto-fixed to '${s.name}'.`)}else this._logIssue(`Layer '${e.name}' field '${s.name}' collides with ${a}.`)}o.add(s.name.toLowerCase())}}_validateField(e){let r=/^\p{L}/u,n=/^.[\p{L}\p{M}\p{N}_]*$/u;e.alias||(this.newDesign?(e.alias=e.name,this._logAutoFix(`Field '${e.name}' had no display name (alias). Auto-fixed to '${e.alias}'.`)):this._logIssue(`Field '${e.name}' has no display name (alias).`));let o=r.test(e.name),s=n.test(e.name);if(!o||!s)if(this.newDesign){let i=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' had an invalid name. Auto-fixed to '${e.name}'.`)}else o||this._logIssue(`Field '${e.name}' does not start with a letter.`),s||this._logIssue(`Field '${e.name}' contains invalid characters (only letters from any writing system, numbers, and underscores are allowed; emojis and punctuation are not allowed).`);if(e.name.length>t.FIELD_NAME_MAX_LENGTH)if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters.`);if(ic.has(e.name.toLowerCase()))if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(i,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(ac.has(e.name.toLowerCase()))if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(i,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' is a reserved system field name. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a reserved system field name.`);if(Array.isArray(e.choiceList)&&e.type!=="string"&&(this.newDesign?e.choiceList.length?(e.type="string",this._logAutoFix(`Field '${e.name}' had a domain but was not of type 'string'. Auto-fixed by setting the type to 'string'.`)):(e.choiceList=null,this._logAutoFix(`Field '${e.name}' had an empty domain but is not of type 'string'. Auto-fixed by removing the domain.`)):this._logIssue(`Field '${e.name}' must be of type 'string' to have a domain.`)),e.type==="string"&&this._validateStringFieldLength(e),Array.isArray(e.choiceList)&&(this.newDesign?this._autoFixChoiceList(e):this._logChoiceListIssues(e)),Array.isArray(e.choiceList)&&e.length!=null){let i=Math.max(...e.choiceList.map(a=>a.length));i>e.length&&(this.newDesign?(this._logAutoFix(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${i} characters. Auto-fixing to ${i}.`),e.length=i):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${i} characters.`))}}_autoFixChoiceList(e){let r=e.choiceList,n=r.filter(s=>s?.trim());n.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had blank domain values. Auto-fixed by removing them.`),r=n,e.choiceList=r);let o=[...new Set(r)];o.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had duplicate domain values. Auto-fixed by removing duplicates.`),r=o,e.choiceList=r),r.length||(this._logAutoFix(`Field '${e.name}' had an empty domain. Auto-fixed by removing the domain.`),e.choiceList=null)}_logChoiceListIssues(e){if(Array.isArray(e.choiceList)){if(!e.choiceList.length){this._logIssue(`Field '${e.name}' has an empty domain. At least one value is required.`);return}e.choiceList.some(r=>!r?.trim())&&this._logIssue(`A blank domain value was added to Field '${e.name}'.`),e.choiceList.length!==new Set(e.choiceList).size&&this._logIssue(`Field '${e.name}' has duplicate domain values.`)}}_validateStringFieldLength(e){if(this.newDesign&&e.length===255&&(e.length=256),typeof e.length!="number"||Number.isNaN(e.length)){this._handleInvalidStringFieldLength(e,256);return}let r=e.length;if(!cc(r).isValid){let n=r>4e3?4e3:256;this._handleInvalidStringFieldLength(e,n)}}_handleInvalidStringFieldLength(e,r){this.newDesign?(this._logAutoFix(`Field '${e.name}' has an invalid length. Auto-fixing to ${r}.`),e.length=r):this._logIssue(`Field '${e.name}' length is invalid (must be a number between 1 and 4000).`)}_makeUniqueName(e,r){let n=e,o=1;for(;r.has(n.toLowerCase());)n=`${e}_${o}`,o+=1;return n}_getUniqueTruncatedFieldName(e,r){let n=t.FIELD_NAME_MAX_LENGTH,o=e.slice(0,n),s=o,i=1;for(;r.has(s.toLowerCase());){let a=`_${i}`,c=Math.max(1,n-a.length);s=`${o.slice(0,c)}${a}`,i+=1}return s}_sanitizeItemName(e,r=t.NAME_MAX_LENGTH){let n=(e??"").replace(new RegExp(lc.source,"gu"),"").replace(t.INVALID_NAME_CHARS,"").replace(/\s+/gu," ").trim();return n.length>r&&(n=n.slice(0,r).trim()),n}_sanitizeDescription(e,r=t.DESCRIPTION_MAX_LENGTH){let n=(e??"").replace(/[<>]/gu,"");return n.length>r&&(n=n.slice(0,r)),n}_sanitizeFieldName(e){let r=(e??"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"");return r.length===0?r="field":/^\p{L}/u.test(r)||(r=`f_${r}`),r}_tryFixName(e,r,n,o,s){if(!this.newDesign)return!1;if(e==="empty")return n(s),this._logAutoFix(`${o} was empty. Auto-fixed to '${s}'.`),!0;let i=this._sanitizeItemName(r)||s;return n(i),this._logAutoFix(`${o} was invalid (${e}). Auto-fixed to '${i}'.`),!0}_tryFixDescription(e,r,n){if(!this.newDesign)return!1;let o=this._sanitizeDescription(e);return r(o),this._logAutoFix(`${n} was invalid. Auto-fixed to a sanitized value.`),!0}_logAutoFix(e){console.debug(e)}_logIssue(e){console.debug(e),this.issues.push(e),this.isValid=!1}},rx=d.object({key:d.string().describe("Stable key identifier for the string."),value:d.string().describe("Display value for the string."),description:d.string().describe("Explanation of where/how the string is used.")}),nx=d.object({id:d.string().describe("ArcGIS item id (32 hex characters)."),title:d.string().describe("Item title."),description:d.string().describe("Item description."),type:d.enum(["Feature Layer (hosted)","Feature Layer (hosted, view)","Web Map","Instant App","Dashboard","Web Experience","Form","Table (hosted)","Table (hosted, view)","Hub Site Application","Hub Page","CSV","Data Pipeline","Desktop Application Template","Group","Notebook","QuickCapture Project"]).describe("ArcGIS item type.")}),zp=d.object({name:d.string().describe("Field name."),type:d.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:d.string().describe("Field alias for display."),description:d.string().describe("Field description."),choiceList:d.array(d.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:d.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),ox=d.object({id:d.number().int().describe("Layer/table id within the feature service."),type:d.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),typeMutable:d.boolean().describe("Indicates whether the layer type can be changed."),name:d.string().describe("Layer/table name."),description:d.string().describe("Layer/table description."),customFields:d.array(zp).describe("User/business fields specific to the solution."),requiredFields:d.array(zp).describe("Fields required for solution functionality (e.g., relationship keys).")}),sx=d.object({itemId:d.string().describe("ArcGIS item id for the feature layer."),addLayers:d.boolean().describe("Indicates whether new layers can be added during solution design."),layers:d.array(ox)}),bl=d.object({response:d.string().describe("Conversational response to the user's query."),solution:d.object({itemId:d.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),title:d.string().describe("Title of the solution."),description:d.string().describe("Description of the solution."),tags:d.array(d.string()).describe("Keywords/tags associated with the solution."),strings:d.array(rx).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:d.array(nx).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:sx.describe("Primary feature layer item and its schema/layers/tables details.")}),ix=d.object({op:d.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:d.string().describe("RFC 6901 JSON Pointer to the target location."),value:d.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null \u2014 not an empty string \u2014 for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),from:d.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null \u2014 not an empty string \u2014 for all other operations.")}),ax=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(ix).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),lx=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),cx=d.object({assistantResponse:d.string().describe("Natural-language response for the user."),isValidUpdate:d.boolean().describe("True only when the request is in scope for supported design updates.")}),ux=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),dx=d.object({templateId:d.string().min(1).describe("Template id from the available template list."),confidence:d.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:d.string().min(1).describe("Short action\u2011oriented description of the template in the user's use case/workflow, starting with a verb.")}),px=d.object({assistantResponse:d.string().nullable().describe("Natural-language response for the user."),isValidUseCase:d.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:d.array(dx).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),mx=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
329
- `):"No validation errors were provided.",fx=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await Fp({promptText:await be(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:lx,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:mx(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},Al=t=>t in _r,hx=5,gx=.8,yx=.5,_x="Web Mapping Application",wx="Embeddings",fi=null,yl=null,hi=null,gi=null,bx="Build",fr=Object.assign({"./prompts/assessBuildRequest.md":()=>import("./QH6PUU3Q.js").then(t=>t.default),"./prompts/assessUpdateRequest.md":()=>import("./5W7G3TSG.js").then(t=>t.default),"./prompts/description.md":()=>import("./E25ZWVBK.js").then(t=>t.default),"./prompts/designSolution.md":()=>import("./VXGLGWIF.js").then(t=>t.default),"./prompts/explainValidationFailure.md":()=>import("./I5E3PM26.js").then(t=>t.default),"./prompts/findExistingSolution.md":()=>import("./LPFG5XTA.js").then(t=>t.default),"./prompts/updateDesign.md":()=>import("./62GTPPV5.js").then(t=>t.default)}),Ax=tx.builderMessages,G=t=>t?.signal?.aborted??!1,re=(t,e,r)=>_i(e)?.builderMessages?.[t]??Ax[t],Vp=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},xx=async(t,e,r)=>{if(!t)return null;let n=`type:"${_x}" AND typekeywords:${wx} AND group:${t}`;return(await Ti({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function vx(t,e,r,n){try{let o=await xx(t,e,r);if(!o||G(n))return null;let s=new DA({id:o.id});return await s.load(),G(n)?null:await s.fetchData("json")}catch{return null}}var Ix=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${bx} AND group:${t}`;return(await Ti({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},Tx=async(t,e,r)=>{try{let n=await Ul(t,{params:e?{token:e}:void 0,portal:r}),o=n?.buildSolution;if(!o)return null;let s=n?.params,i=s&&typeof s=="object"&&!Array.isArray(s)?s:null;return{buildSolution:o,params:i}}catch{return null}},hr=(t,e={})=>{let r=t;return"itemId"in e&&(r={...r,solution:{...r.solution,itemId:e.itemId??null}}),e.sourceBuildSolution!=null&&(r={...r,sourceBuildSolution:e.sourceBuildSolution}),"params"in e&&(r={...r,params:e.params??null}),"templateId"in e&&(r={...r,templateId:e.templateId??null}),r},Gp=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Ni({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},xl=async t=>{if(yl){Object.entries(yl).forEach(([i,a])=>{_r[i]&&(_r[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=Zp(t),n=Qp(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await Ix(r,e,n),s={};G(t)||(await Promise.all(o.map(async i=>{let a=i.properties?.templateInfo;if(!a||typeof a!="object")return;let c=a.id;if(typeof c!="string"||s[c])return;let l=await Tx(i.id,e,n);if(!l||G(t))return;let{buildSolution:u,params:m}=l;if(typeof u=="object"&&u!==null&&"solution"in u){let h=u.solution;h.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,h.item=i}let f={...a,buildSolution:u};s[c]=hr(new Ni(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(u),params:m?structuredClone(m):null}),_r[c]={...a,initialTemplate:s[c]}})),yl=s)},Jp=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},Zp=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},Qp=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},Sx=async t=>{await Promise.all([Xp(t),xl(t)])},Yp=async t=>{let e=Jp(t);(!hi||e&&e!==gi)&&(gi=e??gi,hi=Sx(t).catch(r=>{throw hi=null,gi=null,r})),await hi};async function Xp(t){if(fi)return fi;let e=Zp(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=Qp(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new LA(n?{url:n}:void 0).load(),G(t))return null;let o=Jp(t)??void 0,s=await vx(e,o,r,t);return G(t)?null:s?(fi=s.items,fi):null}var Ex=()=>Object.entries(_r).map(([t,e])=>`ID: ${t}
330
+ `)}`);return await r[1]()}function _i(t){return t?.configurable?.context?.translations}function Up(t){if(typeof window>"u"||t.length<=1)return;let e=t.map(n=>n.solution.id),r=t.map(n=>n.solution.title);window.dispatchEvent(new CustomEvent("searchTermSet",{detail:{scope:"all-solutions",searchTerm:""}})),window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant",{detail:{solutionIds:e,solutionTitles:r},bubbles:!0,composed:!0})),window.dispatchEvent(new CustomEvent("navTabSelected",{detail:{tabType:"all-solutions"}}))}function qp(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var jA=w.object({needsContext:w.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:w.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),jp=t=>t?.signal?.aborted??!1,Bp=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./AS6VINEU.js").then(t=>t.default),"./prompts/transformQuery.md":()=>import("./MFVXFKKM.js").then(t=>t.default)});function zA(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">&#91;$1&#93;</a></sup>')}function UA(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function qA(t,e){let r=[];return(e?.configurable?.context?.configContext.allCards??[]).forEach(n=>{let o=n.title;if(!o)return;let s=new RegExp(`(?<![\\p{L}\\p{N}])${o}(?![\\p{L}\\p{N}])`,"giu"),i=!1;t=t.replace(s,(a,c,l)=>{let u=l.slice(0,c);return/<img[^>]*alt\s*=\s*["'][^"']*$/i.test(u)?a:(i=!0,`<a href="" target="solutionId:${n.deployCommonId}">${o}</a>`)}),i&&r.push({solution:{title:n.title,id:n.deployCommonId,snippet:n.snippet,description:n.description},score:100})}),{source:t,allMatches:r}}function BA(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function Kp(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function _l(t,e,r){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",token:r},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status} calling ${e}`);return n.json()}var KA=t=>new Promise(e=>setTimeout(e,t));async function WA(t,e){let r=t.agentExecutionContext.userRequest,n=e?.configurable?.context?.lastTurnAgent,o=t.agentExecutionContext.messages??[];if(!n||o.length<=1||n==="explorer")return r;try{let s=await be(Bp,"transformQuery"),i=await kt({promptText:s,modelTier:"advanced",temperature:0,schema:jA,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return console.debug(`Rephrased query from "${r}" to "${i.rewrittenQuery.trim()}"`),i.rewrittenQuery.trim()}catch{}return r}var HA=S.Root({...ii(),solutionResponse:S({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:S({reducer:(t,e)=>e??null,default:()=>null}),conversationId:S({reducer:(t,e)=>e??t,default:()=>null})}),VA=()=>new fe(HA).addNode("initializeAgent",JA).addNode("askSolutionsQuestions",GA).addEdge(me,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",K),Wp=async(t,e,r,n)=>{if(!t)return;let o=Kp(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:r,use_llm:!1}}}}};n&&(s.conversationId=n),_l(s,o,e??"")},GA=async(t,e)=>{if(jp(e))return{};let r=_i(e),n=t.documentSkillUrl,o=[],s=await WA(t,e);await Pe({text:r.agentProgress.explorerAgentSearching},e);let i=await _l({message:s,conversationId:e?.configurable?.context?.convoId??void 0,context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:e?.configurable?.context?.configContext.locale??"en",use_llm:!1}}}}},n,e?.configurable?.context?.token??"");i.conversationId&&e?.configurable?.context?.setConversationId&&e.configurable.context.setConversationId(i.conversationId);let a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},c="",l=async u=>{let m=u.context?.results?.[0]?.reply??"";if(m!==""){let h=zA(m),b=UA(h),A=qA(b,e);c=A.source,o=[...o,...A.allMatches.filter(E=>!o.some(y=>y.solution.id===E.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let h="";f===1?h=r.agentProgress.explorerAgentReading:f===2?h=r.agentProgress.explorerAgentReviewing:f===3&&(h=r.agentProgress.explorerAgentPreparing),await Pe({text:h},e)}};for(await l(i);a.hasMore;){if(jp(e))return{};await KA(500),i=await _l({conversationId:a.conversationId,ackSequenceNumber:a.ackSequenceNumber,inquiryId:a.inquiryId},n,e?.configurable?.context?.token??""),a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},await l(i)}return Kp(e?.configurable?.context.portal)&&Wp(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?qp(o[0].solution.id):Up(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},JA=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=BA(e.configurable.context.portal)),{documentSkillUrl:r}};await be(Bp,"solutions_explorer_description");var Hp=t=>{if(t&&Array.isArray(t.id)&&t.id.length>0)return t.id[t.id.length-1].replace("Message","").toLowerCase();if(t&&typeof t._getType=="function")try{return t._getType()}catch{return"human"}return"human"},ZA=t=>{let e=Hp(t);if(t&&t.kwargs)return{role:e,...t.kwargs};if(t&&typeof t=="object"){let r={role:e,content:typeof t.content=="string"?t.content:String(t.content||"")};return t.id&&(r.id=t.id),t.name&&(r.name=t.name),t.additional_kwargs&&(r.additional_kwargs=t.additional_kwargs),t.response_metadata&&(r.response_metadata=t.response_metadata),r}return{role:"human",content:String(t)}},QA=t=>Hp(t)==="human",YA=(t,e=3)=>t.filter(r=>QA(r)).slice(-e).map(ZA),XA=(t,e=" ")=>YA(t).map(r=>r.content).join(e).trim(),ex={understandingRequest:"Understanding your request...",selectTemplatePrompt:"This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.",searchingExistingSolutions:"Searching for existing solutions...",existingSolutionMatch:"I found one or more existing solutions that match your use case. These are ready-to-use solutions that may already meet your needs and can be deployed now. Do you want to continue building your own solution?",continueBuildingYes:"Yes, I want to build a new solution",continueBuildingNo:"No, I\u2019ll review existing solutions",continueBuildingDeclined:"Sounds good. We can focus on existing solutions. Let me know if I can help answer any questions or provide more details.",creatingDesign:"Generating solution design...",updatingDesign:"Updating solution design...",applyChangeFailed:"I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.",createDesignFailed:"I wasn't able to create a solution design from that request. Please try rephrasing and try again.",discardMessage:"Are you sure you want to discard your solution?",discardForNewSolution:"I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?"},tx={builderMessages:ex},yi=class t{constructor(e,r,n=!0){this.isValid=!0,this.issues=[],this.fieldNameRegistry=null,this.response=e,this.template=r,this.newDesign=n,this.validate()}static{this.INVALID_NAME_CHARS=/[><~`$^+=|]/gu}static{this.NAME_MAX_LENGTH=250}static{this.DESCRIPTION_MAX_LENGTH=2048}static{this.SERVICE_NAME_MAX_LENGTH=100}static{this.FIELD_NAME_MAX_LENGTH=31}validate(){this.compareModels(),this.validateResponse()}compareModels(){this._compareStrings(),this._compareItems(),this._compareFeatureLayers()}validateResponse(){this._validateSolutionProps(),this._validateItems(),this._validateFeatureLayer()}_compareStrings(){let e=new Set(this.response.solution.strings.map(n=>n.key)),r=new Map(this.template.solution.strings.map(n=>[n.key,n]));[...r.keys()].every(n=>e.has(n))||(this.newDesign?this._reconcileStringKeys():this._logIssue("String keys in llm response do not match the template."));for(let n of this.response.solution.strings){if(n.value)continue;let o=r.get(n.key)?.value;this.newDesign&&o?(n.value=o,this._logAutoFix(`String key '${n.key}' had no value. Auto-fixed by restoring the template value.`)):this._logIssue(`String key '${n.key}' has no value in the design. It must be populated.`)}}_reconcileStringKeys(){let e=new Set(this.response.solution.strings.map(r=>r.key));for(let r of this.template.solution.strings)e.has(r.key)||(this.response.solution.strings.push({...r}),this._logAutoFix(`String key '${r.key}' was missing from the design. Auto-fixed by re-adding it from the template.`))}_compareItems(){let e=new Set(this.template.items.map(n=>n.id)),r=new Set(this.response.items.map(n=>n.id));e.size===r.size&&[...e].every(n=>r.has(n))||(this.newDesign?this._reconcileItems():this._logIssue("Item IDs in design do not match the template."))}_reconcileItems(){let e=new Set(this.template.items.map(i=>i.id)),r=new Set(this.response.items.map(i=>i.id)),n=[...r].filter(i=>!e.has(i)),o=[...e].filter(i=>!r.has(i));if(e.size===r.size&&n.length===1&&o.length===1){let i=n[0],a=o[0],c=this.response.items.find(l=>l.id===i);if(c){c.id=a,this._logAutoFix(`Item id '${i}' did not match the template id '${a}'. Auto-fixed in place.`);return}}n.length&&(this.response.items=this.response.items.filter(i=>e.has(i.id)),this._logAutoFix(`Removed items not present in the template: ${n.join(", ")}.`));let s=this.template.items.filter(i=>!r.has(i.id));if(s.length){this.response.items=[...s.map(i=>({...i})),...this.response.items];for(let i of s)this._logAutoFix(`Item '${i.id}' was missing from the design. Auto-fixed by adding it from the template.`)}}_compareFeatureLayers(){let e=this.template.featureLayer,r=this.response.featureLayer;if(e.itemId!==r.itemId){let n=r.itemId;r.itemId=e.itemId,this._logAutoFix(`Feature Layer itemId '${n}' did not match the template. Auto-fixed to '${e.itemId}'.`)}if(!e.addLayers){let n=new Set(e.layers.map(s=>s.id)),o=new Set(r.layers.map(s=>s.id));if(!(n.size===o.size&&[...n].every(s=>o.has(s))))this._logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`);else for(let s of e.layers){if(s.type){let a=r.layers.find(c=>c.id===s.id);if(a&&a.type!==s.type)if(this.newDesign){let c=a.type;a.type=s.type,this._logAutoFix(`Layer '${s.id}' type '${c}' is immutable. Auto-fixed back to template type '${s.type}'.`)}else this._logIssue(`Layer '${s.id}' type '${a.type}' does not match template type '${s.type}'. This layer type is immutable.`)}let i=r.layers.find(a=>a.id===s.id);i&&this._validateRequiredFields(i,s)}}}_validateRequiredFields(e,r){let n=new Map(e.requiredFields.map(o=>[o.name.toLowerCase(),o]));for(let o of r.requiredFields){let s=n.get(o.name.toLowerCase());if(!s){this.newDesign?(e.requiredFields.push({...o}),this._logAutoFix(`Layer '${e.name}' was missing required field '${o.name}'. Auto-fixed by re-adding it from the template.`)):this._logIssue(`Layer '${e.name}' is missing required field '${o.name}'.`);continue}this._enforceRequiredFieldImmutability(e,s,o)}}_enforceRequiredFieldImmutability(e,r,n){let o=[];if(r.type!==n.type&&o.push("type"),(r.length??null)!==(n.length??null)&&o.push("length"),this._choiceListsEqual(r.choiceList,n.choiceList)||o.push("choiceList"),!o.length)return;let s=o.length===1?"property":"properties";this.newDesign?(r.type=n.type,r.length=n.length,r.choiceList=Array.isArray(n.choiceList)?[...n.choiceList]:n.choiceList??null,this._logAutoFix(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). Auto-fixed by reverting to the template.`)):this._logIssue(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). These cannot be modified.`)}_choiceListsEqual(e,r){let n=Array.isArray(e)?e:null,o=Array.isArray(r)?r:null;if(n===null&&o===null)return!0;if(n===null||o===null)return!1;let s=new Set(n),i=new Set(o);return s.size===i.size&&[...s].every(a=>i.has(a))}_validateSolutionProps(){let e=this.response.solution.title??"",r=this.response.solution.description,n=/[/\\]/u.test(e),o=this.newDesign?e.replace(/[/\\]/gu,""):e;this.newDesign&&o!==e?(this.response.solution.title=o,this._logAutoFix("Solution title contained forward or back slashes. Auto-fixed by removing them.")):!this.newDesign&&n&&this._logIssue("Solution title contains forbidden forward or back slashes.");let s=rs(o);if(s.isValid||this._tryFixName(s.errorType,o,i=>{this.response.solution.title=i},"Solution title","Solution Title")||this._logIssue(`Solution title is invalid (${s.errorType}).`),r){let i=ns(r,t.DESCRIPTION_MAX_LENGTH,!0);i.isValid||this._tryFixDescription(r,a=>{this.response.solution.description=a},"Solution description")||this._logIssue(`Solution description is invalid (${i.errorType}).`)}}_validateItems(){let e=new Set(["Feature Layer (hosted)","Feature Layer (hosted, view)"]);for(let r of this.response.items){if(e.has(r.type)&&r.title.length>t.SERVICE_NAME_MAX_LENGTH)if(this.newDesign){let o=r.title;r.title=r.title.slice(0,t.SERVICE_NAME_MAX_LENGTH).trim(),this._logAutoFix(`Service name '${o}' exceeded ${t.SERVICE_NAME_MAX_LENGTH} characters. Auto-fixed to '${r.title}'.`)}else this._logIssue(`Service name '${r.title}' exceeds 100 characters.`);let n=rs(r.title??"");if(n.isValid||this._tryFixName(n.errorType,r.title??"",o=>{r.title=o},`Item '${r.id}' title`,"Item Title")||this._logIssue(`Item '${r.id}' title is invalid (${n.errorType}).`),r.description){let o=ns(r.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(r.description,s=>{r.description=s},`Item '${r.id}' description`)||this._logIssue(`Item '${r.id}' description is invalid (${o.errorType}).`)}}}_validateFeatureLayer(){this.response.featureLayer.layers.length||this._logIssue("Feature layer item must contain at least one layer.");let e=this.response.featureLayer.layers.map(r=>r.name.toLowerCase());e.length!==new Set(e).size&&(this.newDesign?this._dedupeLayerNames(this.response.featureLayer.layers):this._logIssue(`Layer names must be unique (case-insensitive). Layer names in design: ${e}.`));for(let r of this.response.featureLayer.layers)this._validateLayer(r,this.response.featureLayer.addLayers)}_dedupeLayerNames(e){let r=new Set;for(let n of e){let o=(n.name??"").toLowerCase();if(r.has(o)){let s=n.name;n.name=this._makeUniqueName(n.name??"Layer",r),this._logAutoFix(`Duplicate layer name '${s}'. Auto-fixed to '${n.name}'.`)}r.add(n.name.toLowerCase())}}_validateLayer(e,r){!r&&e.typeMutable===!0&&e.type==="Table"&&(this.newDesign?(e.type="Point",this._logAutoFix(`Layer '${e.name}' cannot be a Table. Auto-fixed to 'Point'.`)):this._logIssue(`Layer '${e.name}' cannot be a Table. It may be a Point, Line, or Polygon.`));let n=rs(e.name??"");if(n.isValid||this._tryFixName(n.errorType,e.name??"",o=>{e.name=o},`Layer '${e.name}' name`,"Layer Title")||this._logIssue(`Layer '${e.name}' name is invalid (${n.errorType}).`),e.description){let o=ns(e.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(e.description,s=>{e.description=s},`Layer '${e.name}' description`)||this._logIssue(`Layer '${e.name}' description is invalid (${o.errorType}).`)}this._validateLayerFields(e)}_validateLayerFields(e){let r=e.systemFields??[];this.fieldNameRegistry=new Set([...e.customFields,...e.requiredFields,...r].map(s=>s.name.toLowerCase()));for(let s of[...e.customFields,...e.requiredFields])this._validateField(s);this.fieldNameRegistry=null;let n=new Set(e.requiredFields.map(s=>s.name.toLowerCase())),o=new Set(n);for(let s of e.customFields){let i=s.name.toLowerCase();if(o.has(i)){let a=n.has(i)?"a required field name":"another field with the same name";if(this.newDesign){let c=s.name;s.name=this._makeUniqueName(s.name,o),this._logAutoFix(`Layer '${e.name}' field '${c}' collided with ${a}. Auto-fixed to '${s.name}'.`)}else this._logIssue(`Layer '${e.name}' field '${s.name}' collides with ${a}.`)}o.add(s.name.toLowerCase())}}_validateField(e){let r=/^\p{L}/u,n=/^.[\p{L}\p{M}\p{N}_]*$/u;e.alias||(this.newDesign?(e.alias=e.name,this._logAutoFix(`Field '${e.name}' had no display name (alias). Auto-fixed to '${e.alias}'.`)):this._logIssue(`Field '${e.name}' has no display name (alias).`));let o=r.test(e.name),s=n.test(e.name);if(!o||!s)if(this.newDesign){let i=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' had an invalid name. Auto-fixed to '${e.name}'.`)}else o||this._logIssue(`Field '${e.name}' does not start with a letter.`),s||this._logIssue(`Field '${e.name}' contains invalid characters (only letters from any writing system, numbers, and underscores are allowed; emojis and punctuation are not allowed).`);if(e.name.length>t.FIELD_NAME_MAX_LENGTH)if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters.`);if(ic.has(e.name.toLowerCase()))if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(i,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(ac.has(e.name.toLowerCase()))if(this.newDesign){let i=e.name;e.name=this._getUniqueTruncatedFieldName(i,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${i}' is a reserved system field name. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a reserved system field name.`);if(Array.isArray(e.choiceList)&&e.type!=="string"&&(this.newDesign?e.choiceList.length?(e.type="string",this._logAutoFix(`Field '${e.name}' had a domain but was not of type 'string'. Auto-fixed by setting the type to 'string'.`)):(e.choiceList=null,this._logAutoFix(`Field '${e.name}' had an empty domain but is not of type 'string'. Auto-fixed by removing the domain.`)):this._logIssue(`Field '${e.name}' must be of type 'string' to have a domain.`)),e.type==="string"&&this._validateStringFieldLength(e),Array.isArray(e.choiceList)&&(this.newDesign?this._autoFixChoiceList(e):this._logChoiceListIssues(e)),Array.isArray(e.choiceList)&&e.length!=null){let i=Math.max(...e.choiceList.map(a=>a.length));i>e.length&&(this.newDesign?(this._logAutoFix(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${i} characters. Auto-fixing to ${i}.`),e.length=i):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${i} characters.`))}}_autoFixChoiceList(e){let r=e.choiceList,n=r.filter(s=>s?.trim());n.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had blank domain values. Auto-fixed by removing them.`),r=n,e.choiceList=r);let o=[...new Set(r)];o.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had duplicate domain values. Auto-fixed by removing duplicates.`),r=o,e.choiceList=r),r.length||(this._logAutoFix(`Field '${e.name}' had an empty domain. Auto-fixed by removing the domain.`),e.choiceList=null)}_logChoiceListIssues(e){if(Array.isArray(e.choiceList)){if(!e.choiceList.length){this._logIssue(`Field '${e.name}' has an empty domain. At least one value is required.`);return}e.choiceList.some(r=>!r?.trim())&&this._logIssue(`A blank domain value was added to Field '${e.name}'.`),e.choiceList.length!==new Set(e.choiceList).size&&this._logIssue(`Field '${e.name}' has duplicate domain values.`)}}_validateStringFieldLength(e){if(this.newDesign&&e.length===255&&(e.length=256),typeof e.length!="number"||Number.isNaN(e.length)){this._handleInvalidStringFieldLength(e,256);return}let r=e.length;if(!cc(r).isValid){let n=r>4e3?4e3:256;this._handleInvalidStringFieldLength(e,n)}}_handleInvalidStringFieldLength(e,r){this.newDesign?(this._logAutoFix(`Field '${e.name}' has an invalid length. Auto-fixing to ${r}.`),e.length=r):this._logIssue(`Field '${e.name}' length is invalid (must be a number between 1 and 4000).`)}_makeUniqueName(e,r){let n=e,o=1;for(;r.has(n.toLowerCase());)n=`${e}_${o}`,o+=1;return n}_getUniqueTruncatedFieldName(e,r){let n=t.FIELD_NAME_MAX_LENGTH,o=e.slice(0,n),s=o,i=1;for(;r.has(s.toLowerCase());){let a=`_${i}`,c=Math.max(1,n-a.length);s=`${o.slice(0,c)}${a}`,i+=1}return s}_sanitizeItemName(e,r=t.NAME_MAX_LENGTH){let n=(e??"").replace(new RegExp(lc.source,"gu"),"").replace(t.INVALID_NAME_CHARS,"").replace(/\s+/gu," ").trim();return n.length>r&&(n=n.slice(0,r).trim()),n}_sanitizeDescription(e,r=t.DESCRIPTION_MAX_LENGTH){let n=(e??"").replace(/[<>]/gu,"");return n.length>r&&(n=n.slice(0,r)),n}_sanitizeFieldName(e){let r=(e??"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"");return r.length===0?r="field":/^\p{L}/u.test(r)||(r=`f_${r}`),r}_tryFixName(e,r,n,o,s){if(!this.newDesign)return!1;if(e==="empty")return n(s),this._logAutoFix(`${o} was empty. Auto-fixed to '${s}'.`),!0;let i=this._sanitizeItemName(r)||s;return n(i),this._logAutoFix(`${o} was invalid (${e}). Auto-fixed to '${i}'.`),!0}_tryFixDescription(e,r,n){if(!this.newDesign)return!1;let o=this._sanitizeDescription(e);return r(o),this._logAutoFix(`${n} was invalid. Auto-fixed to a sanitized value.`),!0}_logAutoFix(e){console.debug(e)}_logIssue(e){console.debug(e),this.issues.push(e),this.isValid=!1}},rx=d.object({key:d.string().describe("Stable key identifier for the string."),value:d.string().describe("Display value for the string."),description:d.string().describe("Explanation of where/how the string is used.")}),nx=d.object({id:d.string().describe("ArcGIS item id (32 hex characters)."),title:d.string().describe("Item title."),description:d.string().describe("Item description."),type:d.enum(["Feature Layer (hosted)","Feature Layer (hosted, view)","Web Map","Instant App","Dashboard","Web Experience","Form","Table (hosted)","Table (hosted, view)","Hub Site Application","Hub Page","CSV","Data Pipeline","Desktop Application Template","Group","Notebook","QuickCapture Project"]).describe("ArcGIS item type.")}),zp=d.object({name:d.string().describe("Field name."),type:d.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:d.string().describe("Field alias for display."),description:d.string().describe("Field description."),choiceList:d.array(d.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:d.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),ox=d.object({id:d.number().int().describe("Layer/table id within the feature service."),type:d.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),typeMutable:d.boolean().describe("Indicates whether the layer type can be changed."),name:d.string().describe("Layer/table name."),description:d.string().describe("Layer/table description."),customFields:d.array(zp).describe("User/business fields specific to the solution."),requiredFields:d.array(zp).describe("Fields required for solution functionality (e.g., relationship keys).")}),sx=d.object({itemId:d.string().describe("ArcGIS item id for the feature layer."),addLayers:d.boolean().describe("Indicates whether new layers can be added during solution design."),layers:d.array(ox)}),bl=d.object({response:d.string().describe("Conversational response to the user's query."),solution:d.object({itemId:d.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),title:d.string().describe("Title of the solution."),description:d.string().describe("Description of the solution."),tags:d.array(d.string()).describe("Keywords/tags associated with the solution."),strings:d.array(rx).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:d.array(nx).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:sx.describe("Primary feature layer item and its schema/layers/tables details.")}),ix=d.object({op:d.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:d.string().describe("RFC 6901 JSON Pointer to the target location."),value:d.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null \u2014 not an empty string \u2014 for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),from:d.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null \u2014 not an empty string \u2014 for all other operations.")}),ax=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(ix).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),lx=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),cx=d.object({assistantResponse:d.string().describe("Natural-language response for the user."),isValidUpdate:d.boolean().describe("True only when the request is in scope for supported design updates.")}),ux=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),dx=d.object({templateId:d.string().min(1).describe("Template id from the available template list."),confidence:d.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:d.string().min(1).describe("Short action\u2011oriented description of the template in the user's use case/workflow, starting with a verb.")}),px=d.object({assistantResponse:d.string().nullable().describe("Natural-language response for the user."),isValidUseCase:d.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:d.array(dx).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),mx=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
331
+ `):"No validation errors were provided.",fx=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await Fp({promptText:await be(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:lx,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:mx(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},Al=t=>t in _r,hx=5,gx=.8,yx=.5,_x="Web Mapping Application",wx="Embeddings",fi=null,yl=null,hi=null,gi=null,bx="Build",fr=Object.assign({"./prompts/assessBuildRequest.md":()=>import("./KD4IHPH6.js").then(t=>t.default),"./prompts/assessUpdateRequest.md":()=>import("./7X2SPNNK.js").then(t=>t.default),"./prompts/description.md":()=>import("./E25ZWVBK.js").then(t=>t.default),"./prompts/designSolution.md":()=>import("./VXGLGWIF.js").then(t=>t.default),"./prompts/explainValidationFailure.md":()=>import("./I5E3PM26.js").then(t=>t.default),"./prompts/findExistingSolution.md":()=>import("./LPFG5XTA.js").then(t=>t.default),"./prompts/updateDesign.md":()=>import("./ZSTC2DJY.js").then(t=>t.default)}),Ax=tx.builderMessages,G=t=>t?.signal?.aborted??!1,re=(t,e,r)=>_i(e)?.builderMessages?.[t]??Ax[t],Vp=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},xx=async(t,e,r)=>{if(!t)return null;let n=`type:"${_x}" AND typekeywords:${wx} AND group:${t}`;return(await Ti({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function vx(t,e,r,n){try{let o=await xx(t,e,r);if(!o||G(n))return null;let s=new DA({id:o.id});return await s.load(),G(n)?null:await s.fetchData("json")}catch{return null}}var Ix=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${bx} AND group:${t}`;return(await Ti({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},Tx=async(t,e,r)=>{try{let n=await Ul(t,{params:e?{token:e}:void 0,portal:r}),o=n?.buildSolution;if(!o)return null;let s=n?.params,i=s&&typeof s=="object"&&!Array.isArray(s)?s:null;return{buildSolution:o,params:i}}catch{return null}},hr=(t,e={})=>{let r=t;return"itemId"in e&&(r={...r,solution:{...r.solution,itemId:e.itemId??null}}),e.sourceBuildSolution!=null&&(r={...r,sourceBuildSolution:e.sourceBuildSolution}),"params"in e&&(r={...r,params:e.params??null}),"templateId"in e&&(r={...r,templateId:e.templateId??null}),r},Gp=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Ni({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},xl=async t=>{if(yl){Object.entries(yl).forEach(([i,a])=>{_r[i]&&(_r[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=Zp(t),n=Qp(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await Ix(r,e,n),s={};G(t)||(await Promise.all(o.map(async i=>{let a=i.properties?.templateInfo;if(!a||typeof a!="object")return;let c=a.id;if(typeof c!="string"||s[c])return;let l=await Tx(i.id,e,n);if(!l||G(t))return;let{buildSolution:u,params:m}=l;if(typeof u=="object"&&u!==null&&"solution"in u){let h=u.solution;h.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,h.item=i}let f={...a,buildSolution:u};s[c]=hr(new Ni(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(u),params:m?structuredClone(m):null}),_r[c]={...a,initialTemplate:s[c]}})),yl=s)},Jp=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},Zp=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},Qp=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},Sx=async t=>{await Promise.all([Xp(t),xl(t)])},Yp=async t=>{let e=Jp(t);(!hi||e&&e!==gi)&&(gi=e??gi,hi=Sx(t).catch(r=>{throw hi=null,gi=null,r})),await hi};async function Xp(t){if(fi)return fi;let e=Zp(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=Qp(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new LA(n?{url:n}:void 0).load(),G(t))return null;let o=Jp(t)??void 0,s=await vx(e,o,r,t);return G(t)?null:s?(fi=s.items,fi):null}var Ex=()=>Object.entries(_r).map(([t,e])=>`ID: ${t}
330
332
  Label: ${e.label}
331
333
  Description: ${e.description}`).join(`
332
334
 
@@ -335,4 +337,4 @@ Snippet: ${u.snippet}
335
337
  Description: ${u.description}`).join(`
336
338
 
337
339
  `),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await kt({promptText:await be(fr,"findExistingSolution"),modelTier:"fast",temperature:0,schema:ux,messages:l,inputVariables:{query:r,candidates:c}})).matchedTitles.map(u=>a.find(({solution:m})=>m.title===u)).filter(u=>u!==void 0)}},Dx=(t,e)=>{if(G(e))return{};let{existingMatches:r}=t,{hitlResponse:n}=e.configurable,o=`confirmExistingSolution:${r[0].solution.id}`;if(n?.agentId!=="solutionBuilder"||n.id!==o){r.length===1?qp(r[0].solution.id):Up(r);let a=re("existingSolutionMatch",e),c=[re("continueBuildingYes",e),re("continueBuildingNo",e)],l={agentId:"solutionBuilder",id:o,kind:"singleSelection",message:a,metadata:c};throw new Uo(l)}let s=String(n.payload??"").trim(),i=re("continueBuildingNo",e);return{continueBuilding:s!==i}},Fx=(t,e)=>{let r=re("continueBuildingDeclined",e);return{outputMessage:r,summary:r,status:"success"}},em=async(t,e)=>{if(G(e))return{};if(await Yp(e),G(e))return{};let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await Pe({text:re("creatingDesign",e)},e);let o=to(t.selectedTemplate);if(o?.initialTemplate||(await xl(e),o=to(t.selectedTemplate)),G(e))return{};if(!o?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let s=hr(r??o.initialTemplate,{itemId:(r??o.initialTemplate)?.solution?.itemId??null,sourceBuildSolution:r?.sourceBuildSolution??o.initialTemplate.sourceBuildSolution,params:r?.params??o.initialTemplate.params??null}),i=t.agentExecutionContext.messages.slice(-11),a=await kt({promptText:await be(fr,"designSolution"),modelTier:"advanced",temperature:0,schema:bl,messages:i,inputVariables:{currentDesign:JSON.stringify(Li(s)),templateInstructions:o.instructions,query:n}});if(await Pe({text:" of design solution 1"},e),G(e))return{};let{response:c,featureLayer:l,...u}=a,m=Fi(l,s.featureLayer),f=hr({...u,featureLayer:m},{itemId:s?.solution?.itemId,sourceBuildSolution:s.sourceBuildSolution,templateId:t.selectedTemplate??null,params:s.params??null}),h=new yi(f,o.initialTemplate);if(!h.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:h.issues,llmResponse:a}),{outputMessage:re("createDesignFailed",e)};let b=f.sourceBuildSolution,A=Gp(f,b);if(!A.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:A.error,llmResponse:a,design:f});let E=re("createDesignFailed",e);return{outputMessage:E,summary:E,status:"success"}}return G(e)?{}:(Vp(f),{outputMessage:c,summary:c,status:"success",currentDesign:f})},jx=async(t,e)=>{if(G(e))return{};let{currentDesign:r}=t;if(!r)return em(t,e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);await Pe({text:re("updatingDesign",e)},e);let s;try{s=await kt({promptText:await be(fr,"updateDesign"),modelTier:"advanced",temperature:0,schema:ax,messages:o,inputVariables:{currentDesign:JSON.stringify(Di(r)),query:n}})}catch(P){console.warn("[SolutionBuilder] updateDesign structured prompt failed:",P);let z=re("applyChangeFailed",e);return{outputMessage:z,summary:z,status:"success"}}let{response:i,patches:a}=s;if(!a||a.length===0)return{outputMessage:i,summary:i,status:"success"};let c=P=>{try{return JSON.parse(P)}catch{let z=P.replace(/[\u0000-\u001F]/g,U=>{switch(U){case"\b":return"\\b";case"\f":return"\\f";case`
338
- `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+U.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(z)}catch{return P}}},l=[...a.map(P=>({op:P.op,path:P.path.replace(/\/+$/,""),...P.value!=null&&P.value!==""?{value:c(P.value)}:{},...P.from!=null&&P.from!==""?{from:P.from}:{}}))].sort((P,z)=>P.op!=="remove"||z.op!=="remove"?0:z.path.localeCompare(P.path,void 0,{numeric:!0})),u=structuredClone(Li(r));try{Jn(u,l,!0)}catch(P){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:P,llmResponse:s,patches:l,patchTarget:u});let z=re("applyChangeFailed",e);return{outputMessage:z,summary:z,status:"success"}}let m=hr({response:"",...u},{itemId:r.solution?.itemId??null}),f=bl.safeParse(m);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:m});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}let{response:h,featureLayer:b,...A}=f.data,E=Fi(b,r.featureLayer),y=hr({...A,featureLayer:E},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),v=to(t.selectedTemplate);if(v?.initialTemplate||(await xl(e),v=to(t.selectedTemplate)),G(e))return{};if(!v?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let C=new yi(y,v.initialTemplate,!1);if(!C.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:C.issues,llmResponse:s,patchedDesign:y});let P=await fx({query:n,validationIssues:C.issues,recentMessages:o,fallbackMessage:re("applyChangeFailed",e),promptModules:fr});return{outputMessage:P,summary:P,status:"success"}}let L=y.sourceBuildSolution,B=Gp(y,L);if(!B.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:B.error,llmResponse:s,design:y});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}return G(e)?{}:(Vp(y),{outputMessage:i,summary:i,status:"success",currentDesign:y})},zx=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",Ux=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",qx=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",Bx=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",Kx=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",Wx=()=>new fe(kx).addNode("syncCurrentDesignFromContext",Ox).addNode("assessBuildRequest",Px).addNode("assessUpdateRequest",Rx).addNode("invalidBuildExit",Mx).addNode("invalidUpdateExit",$x).addNode("selectTemplateHIL",Nx).addNode("findExistingSolutions",Lx).addNode("confirmContinueBuildingHIL",Dx).addNode("declineContinueBuildingExit",Fx).addNode("designSolution",em).addNode("updateDesign",jx).addEdge(me,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",zx,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",Ux,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",qx,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",K).addEdge("invalidUpdateExit",K).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Bx,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",Kx,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",K).addEdge("designSolution",K).addEdge("updateDesign",K);await be(fr,"description");var Hx=w.object({tool:w.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:w.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:w.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),wi=t=>t?.signal?.aborted??!1,vl=Object.assign({"./prompts/assistantResponse.md":()=>import("./632J5NXN.js").then(t=>t.default),"./prompts/classifyIntent.md":()=>import("./LWJF6EXD.js").then(t=>t.default),"./prompts/description.md":()=>import("./ENLFOYSI.js").then(t=>t.default)}),Vx=t=>{let e=t?.configurable?.context?.solutionDesignJson,r=t?.configurable?.context?.lastTurnAgent,n=r==="assistant"?"other":r,o=!1;if(typeof e=="string"&&e.trim())try{o=JSON.parse(e).solution!=null}catch{o=!1}return{activeSolutionDesign:o,lastTool:n}},Il=(t,e)=>{let r=t?.configurable?.context?.setLastTurnAgent;typeof r=="function"&&r(e);let n=new CustomEvent("assistantProcessing",{detail:{finished:!0,agent:e}});window.dispatchEvent(n)},tm=S.Root({...ii(),selectedTool:S({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:S({reducer:(t,e)=>e??null,default:()=>null})}),Gx=async(t,e)=>{if(wi(e))return{};let r=_i(e);await Pe({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=Vx(e),a=await be(vl,"classifyIntent"),c=await kt({promptText:a,modelTier:"advanced",temperature:0,schema:Hx,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},Jx=async(t,e)=>{if(wi(e))return{};let r=await VA().compile().invoke(t,e);return Il(e,"explorer"),r},Zx=async(t,e)=>{if(wi(e))return{};let r=await Wx().compile().invoke(t,e);return Il(e,"builder"),r},Qx=async(t,e)=>{if(wi(e))return{};let r=_i(e),n=t.agentExecutionContext.userRequest,o=t.intentRationale??"No rationale available.";await Pe({text:r?.executingSolutionsAssistantAgent},e);let s=await be(vl,"assistantResponse"),i=t.agentExecutionContext.messages.slice(-11),a=await Pp({promptText:s,modelTier:"advanced",temperature:0,messages:i,inputVariables:{query:n,rationale:o}});return Il(e,"assistant"),{outputMessage:a,summary:a,status:"success"}},Yx=t=>t.selectedTool??"other",Xx=()=>new fe(tm).addNode("classifyIntent",Gx).addNode("routeToExplorer",Jx).addNode("routeToBuilder",Zx).addNode("assistantResponse",Qx).addEdge(me,"classifyIntent").addConditionalEdges("classifyIntent",Yx,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",K).addEdge("routeToBuilder",K).addEdge("assistantResponse",K),ev=await be(vl,"description"),tv={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:ev,createGraph:Xx,workspace:tm},rv="https://links.esri.com/solutions/agol-organizational-account",nv="https://links.esri.com/solutions/configure-assistants",wl=class extends Ll{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._lastTurnAgent=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=Fl({name:"arcgis-solutions-assistant",blocking:!0}),this._builderWidth=48,this._solutionDesignJson='{ "solution": null }',this._isAssistantBusy=!1,this._isBuilderBusy=!1,this._preChatCheck=!1,this._showNewChatConfirm=!1,this._assistantRef=$l(),this._configContextConsumer=Ii({context:jl,subscribe:!0,callback:e=>{e?.portalURL&&(gl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Ii({context:zl,subscribe:!0,callback:e=>{e?.design&&(this._solutionDesignJson=JSON.stringify(e.design,null,2))}}),this._handleResize=()=>{this._isMobile=window.innerWidth<=800},this._chatStartTime=null,this._handleAssistantProcessingFinished=e=>{let r=e;if(r.detail?.finished&&this._chatStartTime!==null){let n=ql(this._chatStartTime);this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"Chat",dimensions:[r.detail.agent],metrics:[n]}),this._chatStartTime=null,this.assistantProcessing.emit(!1)}},this.closeAssistant=xi(),this.assistantProcessing=xi(),this._handleAssistantLinkClick=e=>{let r=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(r?.href)if(e.preventDefault(),r.target.indexOf("solutionId:")>-1){let n=r.target.split("solutionId:")[1];this._emitItemIdFromAI(n)}else window.open(r.href,"_blank","noopener,noreferrer")},this._onSolutionDesignUpdate=e=>{let r=e.detail;this._solutionDesignJson=r?JSON.stringify(r,null,2):'{ "solution": null }'},this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open},this.listenOn(window,"arcgisFeedback",e=>{let r=e.detail,{agentPicked:n,taskAssigned:o,userMessage:s}=this._parseAgentPickedAndTask(r);this._sendFeedback(r.content,s??o??"",r.feedback?.positive?"Good":r.feedback?.positive=="Bad"?"Bad":"N/A",n??"")}),this.listenOn(window,"clearAssistantConversation",()=>{this._clearConversation()})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_lastTurnAgent:16,_orgSettings:16,_suggestedPrompts:16,_hasInteracted:16,_isMobile:16,_translations:16,_builderWidth:16,_solutionDesignJson:16,_isAssistantBusy:16,_isBuilderBusy:16,_preChatCheck:16,_showNewChatConfirm:16}}static{this.styles=FA}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}connectedCallback(){super.connectedCallback(),window.addEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.addEventListener("click",this._handleAssistantLinkClick),window.addEventListener("resize",this._handleResize),window.addEventListener("assistantProcessing",this._handleAssistantProcessingFinished),this._builderDesignContextConsumer}disconnectedCallback(){window.removeEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.removeEventListener("click",this._handleAssistantLinkClick),window.removeEventListener("resize",this._handleResize),window.removeEventListener("assistantProcessing",this._handleAssistantProcessingFinished),super.disconnectedCallback()}loaded(){this._checkURLOpenParameter()}load(){gl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(gl.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(e){this._loadUserFirstName()}willUpdate(e){e.has("open")&&this.open&&window.dispatchEvent(new CustomEvent("openAssistant")),this._configContextConsumer.value?.authentication&&this._configContextConsumer.value?.userSession?.token&&(this._preChatCheck||(Wp(this._configContextConsumer.value?.authentication.Portal,this._configContextConsumer.value?.userSession?.token,this._configContextConsumer.value?.locale??"en"),this._preChatCheck=!0)),this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return st`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??vi} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return st`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${uc(this._translations.noPermissionMessage.replace("{{orgUrl}}",rv).replace("{{configAI}}",nv))}</div></calcite-notice>`}render(){let e=this._suggestedPrompts.length>0?this._suggestedPrompts:this._hasInteracted?[]:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length>0?e=this._suggestedPrompts:this._hasInteracted||(e=[...Object.values(this._translations.defaultFollowUpQuestions)]),st`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?st`${!this._isMobile&&st`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.builder} text-enabled .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${()=>{this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"Toggle Builder Panel",dimensions:[this.builderVisible?"Close":"Open"]}),window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"))}} scale=m slot=header-actions-end></calcite-action>`||""}${!this._isMobile&&st`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.solutionBuilder}</span></calcite-tooltip>`||""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage??vi} .suggestedPrompts=${e} @arcgisSubmit=${r=>{console.log("arcgis submit: ",r.detail),this._suggestedPrompts=[],e=[],this._hasInteracted=!0,this._chatStartTime=Date.now(),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail}} ${Nl(this._assistantRef)}><calcite-button appearance=transparent id=newChatButton icon-start=speech-bubble-plus kind=neutral .label=${this._translations.tooltips.newChat} @click=${()=>{this.hasActiveBuilderDesign?this._showNewChatConfirm=!0:(this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"New Chat",dimensions:["No Active Design"]}),this._clearConversation())}} round scale=m slot=entry-actions-start>${this._translations.tooltips.newChat}</calcite-button><arcgis-assistant-agent .agent=${tv} .context=${{token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,translations:this._translations,solutionDesignJson:this._solutionDesignJson,lastTurnAgent:this._lastTurnAgent,setConversationId:r=>{this._conversationId=r},setLastTurnAgent:r=>{this._lastTurnAgent=r},clearSuggestedPrompts:()=>{this._suggestedPrompts=[]}}}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=solid kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>`:this._renderNoPermission():this._renderNoSign()}${this._showNewChatConfirm&&st`<calcite-dialog close-disabled escape-disabled .heading=${this._translations.newConversationConfirmTitle} modal open outside-close-disabled>${this._translations.builderMessages.discardMessage}<calcite-button appearance=outline @click=${()=>{this._showNewChatConfirm=!1}} slot=footer-end>${this._translations.cancel}</calcite-button><calcite-button appearance=solid kind=danger @click=${()=>{this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"New Chat",dimensions:["With Design Discard"]}),this._showNewChatConfirm=!1,window.dispatchEvent(new CustomEvent("requestBuilderDiscard"))}} slot=footer-end>${this._translations.discard}</calcite-button></calcite-dialog>`||""}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${()=>{this.closeAssistant.emit(!0)}} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`}_clearConversation(){this._conversationId=void 0,this._lastTurnAgent=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._assistantRef.value?.clearChatHistory()}_sendFeedback(e,r,n,o){let s=`https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(r)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({agent:o}))}&field:version=${encodeURIComponent("v2")}`;window.open(s,"_blank")}async _loadUserFirstName(){try{let e=await this._configContextConsumer.value?.userSession?.getUser();if(e?.fullName){let r=e.fullName.split(" ")[0];this.userFirstName=r}}catch{}}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],o=[...r].sort((u,m)=>m.id-u.id).find(u=>u.role==="user"&&u.id<=e.id)?.content||null,s=n.find(u=>typeof u=="string"&&u.includes("Agent picked:"))??null;if(!s)return{agentPicked:null,taskAssigned:null,userMessage:o};let i=/Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i,a=s.match(i);if(!a)return{agentPicked:null,taskAssigned:null,userMessage:o};let c=a[1].trim(),l=a[2].trim();return{agentPicked:c,taskAssigned:l,userMessage:o}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};Dl("arcgis-solutions-assistant",wl);return wl},"config","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","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","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,b)
340
+ `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+U.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(z)}catch{return P}}},l=[...a.map(P=>({op:P.op,path:P.path.replace(/\/+$/,""),...P.value!=null&&P.value!==""?{value:c(P.value)}:{},...P.from!=null&&P.from!==""?{from:P.from}:{}}))].sort((P,z)=>P.op!=="remove"||z.op!=="remove"?0:z.path.localeCompare(P.path,void 0,{numeric:!0})),u=structuredClone(Li(r));try{Jn(u,l,!0)}catch(P){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:P,llmResponse:s,patches:l,patchTarget:u});let z=re("applyChangeFailed",e);return{outputMessage:z,summary:z,status:"success"}}let m=hr({response:"",...u},{itemId:r.solution?.itemId??null}),f=bl.safeParse(m);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:m});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}let{response:h,featureLayer:b,...A}=f.data,E=Fi(b,r.featureLayer),y=hr({...A,featureLayer:E},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),v=to(t.selectedTemplate);if(v?.initialTemplate||(await xl(e),v=to(t.selectedTemplate)),G(e))return{};if(!v?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let C=new yi(y,v.initialTemplate,!1);if(!C.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:C.issues,llmResponse:s,patchedDesign:y});let P=await fx({query:n,validationIssues:C.issues,recentMessages:o,fallbackMessage:re("applyChangeFailed",e),promptModules:fr});return{outputMessage:P,summary:P,status:"success"}}let L=y.sourceBuildSolution,B=Gp(y,L);if(!B.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:B.error,llmResponse:s,design:y});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}return G(e)?{}:(Vp(y),{outputMessage:i,summary:i,status:"success",currentDesign:y})},zx=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",Ux=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",qx=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",Bx=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",Kx=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",Wx=()=>new fe(kx).addNode("syncCurrentDesignFromContext",Ox).addNode("assessBuildRequest",Px).addNode("assessUpdateRequest",Rx).addNode("invalidBuildExit",Mx).addNode("invalidUpdateExit",$x).addNode("selectTemplateHIL",Nx).addNode("findExistingSolutions",Lx).addNode("confirmContinueBuildingHIL",Dx).addNode("declineContinueBuildingExit",Fx).addNode("designSolution",em).addNode("updateDesign",jx).addEdge(me,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",zx,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",Ux,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",qx,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",K).addEdge("invalidUpdateExit",K).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Bx,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",Kx,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",K).addEdge("designSolution",K).addEdge("updateDesign",K);await be(fr,"description");var Hx=w.object({tool:w.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:w.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:w.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),wi=t=>t?.signal?.aborted??!1,vl=Object.assign({"./prompts/assistantResponse.md":()=>import("./632J5NXN.js").then(t=>t.default),"./prompts/classifyIntent.md":()=>import("./LWJF6EXD.js").then(t=>t.default),"./prompts/description.md":()=>import("./ENLFOYSI.js").then(t=>t.default)}),Vx=t=>{let e=t?.configurable?.context?.solutionDesignJson,r=t?.configurable?.context?.lastTurnAgent,n=r==="assistant"?"other":r,o=!1;if(typeof e=="string"&&e.trim())try{o=JSON.parse(e).solution!=null}catch{o=!1}return{activeSolutionDesign:o,lastTool:n}},Il=(t,e)=>{let r=t?.configurable?.context?.setLastTurnAgent;typeof r=="function"&&r(e);let n=new CustomEvent("assistantProcessing",{detail:{finished:!0,agent:e}});window.dispatchEvent(n)},tm=S.Root({...ii(),selectedTool:S({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:S({reducer:(t,e)=>e??null,default:()=>null})}),Gx=async(t,e)=>{if(wi(e))return{};let r=_i(e);await Pe({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=Vx(e),a=await be(vl,"classifyIntent"),c=await kt({promptText:a,modelTier:"advanced",temperature:0,schema:Hx,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},Jx=async(t,e)=>{if(wi(e))return{};let r=await VA().compile().invoke(t,e);return Il(e,"explorer"),r},Zx=async(t,e)=>{if(wi(e))return{};let r=await Wx().compile().invoke(t,e);return Il(e,"builder"),r},Qx=async(t,e)=>{if(wi(e))return{};let r=_i(e),n=t.agentExecutionContext.userRequest,o=t.intentRationale??"No rationale available.";await Pe({text:r?.executingSolutionsAssistantAgent},e);let s=await be(vl,"assistantResponse"),i=t.agentExecutionContext.messages.slice(-11),a=await Pp({promptText:s,modelTier:"advanced",temperature:0,messages:i,inputVariables:{query:n,rationale:o}});return Il(e,"assistant"),{outputMessage:a,summary:a,status:"success"}},Yx=t=>t.selectedTool??"other",Xx=()=>new fe(tm).addNode("classifyIntent",Gx).addNode("routeToExplorer",Jx).addNode("routeToBuilder",Zx).addNode("assistantResponse",Qx).addEdge(me,"classifyIntent").addConditionalEdges("classifyIntent",Yx,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",K).addEdge("routeToBuilder",K).addEdge("assistantResponse",K),ev=await be(vl,"description"),tv={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:ev,createGraph:Xx,workspace:tm},rv="https://links.esri.com/solutions/agol-organizational-account",nv="https://links.esri.com/solutions/configure-assistants",wl=class extends Ll{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._lastTurnAgent=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=Fl({name:"arcgis-solutions-assistant",blocking:!0}),this._builderWidth=48,this._solutionDesignJson='{ "solution": null }',this._isAssistantBusy=!1,this._isBuilderBusy=!1,this._preChatCheck=!1,this._showNewChatConfirm=!1,this._assistantRef=$l(),this._configContextConsumer=Ii({context:jl,subscribe:!0,callback:e=>{e?.portalURL&&(gl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Ii({context:zl,subscribe:!0,callback:e=>{e?.design&&(this._solutionDesignJson=JSON.stringify(e.design,null,2))}}),this._handleResize=()=>{this._isMobile=window.innerWidth<=800},this._chatStartTime=null,this._handleAssistantProcessingFinished=e=>{let r=e;if(r.detail?.finished&&this._chatStartTime!==null){let n=ql(this._chatStartTime);this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"Chat",dimensions:[r.detail.agent],metrics:[n]}),this._chatStartTime=null}},this.closeAssistant=xi(),this.assistantProcessing=xi(),this._handleAssistantLinkClick=e=>{let r=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(r?.href)if(e.preventDefault(),r.target.indexOf("solutionId:")>-1){let n=r.target.split("solutionId:")[1];this._emitItemIdFromAI(n)}else window.open(r.href,"_blank","noopener,noreferrer")},this._onSolutionDesignUpdate=e=>{let r=e.detail;this._solutionDesignJson=r?JSON.stringify(r,null,2):'{ "solution": null }'},this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open},this.listenOn(window,"arcgisFeedback",e=>{let r=e.detail,{agentPicked:n,taskAssigned:o,userMessage:s}=this._parseAgentPickedAndTask(r);this._sendFeedback(r.content,s??o??"",r.feedback?.positive?"Good":r.feedback?.positive=="Bad"?"Bad":"N/A",n??"")}),this.listenOn(window,"clearAssistantConversation",()=>{this._clearConversation()})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_lastTurnAgent:16,_orgSettings:16,_suggestedPrompts:16,_hasInteracted:16,_isMobile:16,_translations:16,_builderWidth:16,_solutionDesignJson:16,_isAssistantBusy:16,_isBuilderBusy:16,_preChatCheck:16,_showNewChatConfirm:16}}static{this.styles=FA}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}connectedCallback(){super.connectedCallback(),window.addEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.addEventListener("click",this._handleAssistantLinkClick),window.addEventListener("resize",this._handleResize),window.addEventListener("assistantProcessing",this._handleAssistantProcessingFinished),this._builderDesignContextConsumer}disconnectedCallback(){window.removeEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.removeEventListener("click",this._handleAssistantLinkClick),window.removeEventListener("resize",this._handleResize),window.removeEventListener("assistantProcessing",this._handleAssistantProcessingFinished),super.disconnectedCallback()}loaded(){this._checkURLOpenParameter()}load(){gl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(gl.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(e){this._loadUserFirstName()}willUpdate(e){e.has("open")&&this.open&&window.dispatchEvent(new CustomEvent("openAssistant")),this._configContextConsumer.value?.authentication&&this._configContextConsumer.value?.userSession?.token&&(this._preChatCheck||(Wp(this._configContextConsumer.value?.authentication.Portal,this._configContextConsumer.value?.userSession?.token,this._configContextConsumer.value?.locale??"en"),this._preChatCheck=!0)),this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return st`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??vi} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return st`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${uc(this._translations.noPermissionMessage.replace("{{orgUrl}}",rv).replace("{{configAI}}",nv))}</div></calcite-notice>`}render(){let e=this._suggestedPrompts.length>0?this._suggestedPrompts:this._hasInteracted?[]:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length>0?e=this._suggestedPrompts:this._hasInteracted||(e=[...Object.values(this._translations.defaultFollowUpQuestions)]),st`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?st`${!this._isMobile&&st`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.builder} text-enabled .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${()=>{this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"Toggle Builder Panel",dimensions:[this.builderVisible?"Close":"Open"]}),window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"))}} scale=m slot=header-actions-end></calcite-action>`||""}${!this._isMobile&&st`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.solutionBuilder}</span></calcite-tooltip>`||""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage??vi} .suggestedPrompts=${e} @arcgisSubmit=${r=>{console.log("arcgis submit: ",r.detail),this._suggestedPrompts=[],e=[],this._hasInteracted=!0,this._chatStartTime=Date.now(),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail}} @arcgisResponse=${()=>{this.assistantProcessing.emit(!1)}} ${Nl(this._assistantRef)}><calcite-button appearance=transparent id=newChatButton icon-start=speech-bubble-plus kind=neutral .label=${this._translations.tooltips.newChat} @click=${()=>{this.hasActiveBuilderDesign?this._showNewChatConfirm=!0:(this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"New Chat",dimensions:["No Active Design"]}),this._clearConversation())}} round scale=m slot=entry-actions-start>${this._translations.tooltips.newChat}</calcite-button><arcgis-assistant-agent .agent=${tv} .context=${{token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,translations:this._translations,solutionDesignJson:this._solutionDesignJson,lastTurnAgent:this._lastTurnAgent,setConversationId:r=>{this._conversationId=r},setLastTurnAgent:r=>{this._lastTurnAgent=r},clearSuggestedPrompts:()=>{this._suggestedPrompts=[]}}}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=solid kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>`:this._renderNoPermission():this._renderNoSign()}${this._showNewChatConfirm&&st`<calcite-dialog close-disabled escape-disabled .heading=${this._translations.newConversationConfirmTitle} modal open outside-close-disabled>${this._translations.builderMessages.discardMessage}<calcite-button appearance=outline @click=${()=>{this._showNewChatConfirm=!1}} slot=footer-end>${this._translations.cancel}</calcite-button><calcite-button appearance=solid kind=danger @click=${()=>{this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"New Chat",dimensions:["With Design Discard"]}),this._showNewChatConfirm=!1,window.dispatchEvent(new CustomEvent("requestBuilderDiscard"))}} slot=footer-end>${this._translations.discard}</calcite-button></calcite-dialog>`||""}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${()=>{this.closeAssistant.emit(!0)}} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`}_clearConversation(){this._conversationId=void 0,this._lastTurnAgent=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._assistantRef.value?.clearChatHistory()}_sendFeedback(e,r,n,o){let s=`https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(r)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({agent:o}))}&field:version=${encodeURIComponent("v2")}`;window.open(s,"_blank")}async _loadUserFirstName(){try{let e=await this._configContextConsumer.value?.userSession?.getUser();if(e?.fullName){let r=e.fullName.split(" ")[0];this.userFirstName=r}}catch{}}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],o=[...r].sort((u,m)=>m.id-u.id).find(u=>u.role==="user"&&u.id<=e.id)?.content||null,s=n.find(u=>typeof u=="string"&&u.includes("Agent picked:"))??null;if(!s)return{agentPicked:null,taskAssigned:null,userMessage:o};let i=/Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i,a=s.match(i);if(!a)return{agentPicked:null,taskAssigned:null,userMessage:o};let c=a[1].trim(),l=a[2].trim();return{agentPicked:c,taskAssigned:l,userMessage:o}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};Dl("arcgis-solutions-assistant",wl);return wl},"config","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","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","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,b)