@esri/solutions-components 5.1.13 → 5.1.15

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 (145) hide show
  1. package/dist/cdn/{BP5ZQTYK.js → 2A7FDE6T.js} +1 -1
  2. package/dist/cdn/{4QXIKPGO.js → 2CIYQPV2.js} +1 -1
  3. package/dist/cdn/{ODJ7OCZ6.js → 2WXIVPKA.js} +1 -1
  4. package/dist/cdn/{WPDKKXGG.js → 3CQUAISD.js} +1 -1
  5. package/dist/cdn/{XIUOFNHN.js → 3JF7PWPA.js} +1 -1
  6. package/dist/cdn/{WQUCBG6T.js → 4ESJPQUS.js} +1 -1
  7. package/dist/cdn/{URV3LNEF.js → 4QGYS5DL.js} +1 -1
  8. package/dist/cdn/{J2HB6QQJ.js → 5AGI2QC2.js} +1 -1
  9. package/dist/cdn/{BPZVE5D3.js → 5DMFGBJJ.js} +1 -1
  10. package/dist/cdn/{FTK634CB.js → 5DZ55HIG.js} +1 -1
  11. package/dist/cdn/{OIGQMEOA.js → 5O6454VY.js} +1 -1
  12. package/dist/cdn/{AHGIIRD2.js → 5O6E2RIA.js} +1 -1
  13. package/dist/cdn/{76MTNIFR.js → 5OMXJXRL.js} +1 -1
  14. package/dist/cdn/{M6KMGWHY.js → 64DMFXX3.js} +118 -118
  15. package/dist/cdn/{DASTXYVJ.js → 65VKA5R3.js} +1 -1
  16. package/dist/cdn/{QQL4IXXC.js → 6A4MHJFZ.js} +1 -1
  17. package/dist/cdn/6JPXLTNI.js +358 -0
  18. package/dist/cdn/{SRUCCYYK.js → 6MQWDLJ6.js} +1 -1
  19. package/dist/cdn/{ZSTTH25D.js → 6RHFFYNC.js} +1 -1
  20. package/dist/cdn/{L3DICS7J.js → 7IN2LLKR.js} +1 -1
  21. package/dist/cdn/{AKGLWV53.js → 7LP2DUHS.js} +1 -1
  22. package/dist/cdn/{PGY6VBLA.js → 7SZY3VBD.js} +1 -1
  23. package/dist/cdn/{LT6TNRF6.js → 7ZZNR4FQ.js} +1 -1
  24. package/dist/cdn/{SYKVEYMY.js → ABPXUFXN.js} +1 -1
  25. package/dist/cdn/{EGBJGHKB.js → AIUJXRA5.js} +1 -1
  26. package/dist/cdn/{HWD4BGMW.js → AONULVO2.js} +1 -1
  27. package/dist/cdn/{U26OIB2P.js → AQ2USXUY.js} +1 -1
  28. package/dist/cdn/{WZSXP6GC.js → BA3J7L5N.js} +1 -1
  29. package/dist/cdn/{NT2KAJ24.js → BAVVBOOM.js} +1 -1
  30. package/dist/cdn/{WQ5UIZ6O.js → BDVFJJR4.js} +1 -1
  31. package/dist/cdn/{6VUGQJW4.js → BOA6VQK6.js} +1 -1
  32. package/dist/cdn/BPHZAC66.js +2 -0
  33. package/dist/cdn/{NISCRPTA.js → CNNBPMQT.js} +1 -1
  34. package/dist/cdn/{TCPO7PEE.js → CNV2ZCFA.js} +1 -1
  35. package/dist/cdn/{3562Z3EC.js → COEHM4BJ.js} +1 -1
  36. package/dist/cdn/{EXPBVOCZ.js → COJMQQT5.js} +1 -1
  37. package/dist/cdn/{DZ6PL4HK.js → COKMQSEA.js} +1 -1
  38. package/dist/cdn/{2EEHG5XR.js → CPWYI2FO.js} +1 -1
  39. package/dist/cdn/{GDBULXEH.js → D65S424V.js} +1 -1
  40. package/dist/cdn/{UZVU2CPJ.js → DERWSE25.js} +1 -1
  41. package/dist/cdn/{NTFCCNHZ.js → DMMSPGOK.js} +1 -1
  42. package/dist/cdn/{X5HRQ34A.js → ECJQJ4BY.js} +1 -1
  43. package/dist/cdn/{WB4DH4SS.js → F5EJPIW4.js} +1 -1
  44. package/dist/cdn/{XYGCPNIM.js → FLPXST7W.js} +1 -1
  45. package/dist/cdn/{OQUU2BPX.js → FPF7E4SX.js} +1 -1
  46. package/dist/cdn/{YTIFVDAA.js → FX2C3BL4.js} +1 -1
  47. package/dist/cdn/{DP6WOAWH.js → G2OBSHPX.js} +1 -1
  48. package/dist/cdn/{PHCPY4ZR.js → GEEQWXOZ.js} +1 -1
  49. package/dist/cdn/{R2UFZXIQ.js → GWLE7PJQ.js} +1 -1
  50. package/dist/cdn/{CEQ7OSXE.js → H3QX6XOJ.js} +1 -1
  51. package/dist/cdn/{3Q6BLEUW.js → HBB7AS7K.js} +1 -1
  52. package/dist/cdn/{YCHAOPMX.js → HW4LYJUR.js} +1 -1
  53. package/dist/cdn/{AO6C3Y72.js → IBSFJBIL.js} +1 -1
  54. package/dist/cdn/{K64MB7UB.js → IDJHBEJC.js} +1 -1
  55. package/dist/cdn/{U2J33BNN.js → ILEHAZV2.js} +1 -1
  56. package/dist/cdn/{DUFBYCNV.js → IYZ2PDYK.js} +1 -1
  57. package/dist/cdn/{KMN7UYCS.js → JNZBNQ3F.js} +1 -1
  58. package/dist/cdn/JRUIRTL7.js +2 -0
  59. package/dist/cdn/{KXJZZIT3.js → JXERXJF5.js} +1 -1
  60. package/dist/cdn/{Q5USRVF5.js → K3ALRIQF.js} +1 -1
  61. package/dist/cdn/{XT7FRIZE.js → KC3LIHE2.js} +1 -1
  62. package/dist/cdn/{IHC3D35G.js → KF64ALRP.js} +1 -1
  63. package/dist/cdn/{7MHXB6MA.js → KJTTBON2.js} +1 -1
  64. package/dist/cdn/{LQHZEFT7.js → KN2PNGQX.js} +1 -1
  65. package/dist/cdn/{TBPIA7X3.js → KOIHVAUY.js} +1 -1
  66. package/dist/cdn/{YKWVEXEV.js → L5DQOHD5.js} +1 -1
  67. package/dist/cdn/{7NRAPL4U.js → LGJMYSGU.js} +1 -1
  68. package/dist/cdn/{7TAWNPBZ.js → LX3ZJGZ3.js} +1 -1
  69. package/dist/cdn/{MPOW6X2Q.js → M6CYGIKU.js} +1 -1
  70. package/dist/cdn/{AK6SGWFY.js → MBZESGLB.js} +1 -1
  71. package/dist/cdn/{YRN3GNV2.js → MECI4R4R.js} +1 -1
  72. package/dist/cdn/{TM3HQUQN.js → MXLUHQFQ.js} +1 -1
  73. package/dist/cdn/{ZNNM4VOZ.js → NF77ALHM.js} +1 -1
  74. package/dist/cdn/{WDSHKWCQ.js → O37KXBBH.js} +1 -1
  75. package/dist/cdn/{QAVOSU5J.js → O3FK6QQ2.js} +1 -1
  76. package/dist/cdn/{WFFDEQ3T.js → O62JG2Y6.js} +1 -1
  77. package/dist/cdn/{SSE3OV4D.js → OJH4NUGT.js} +1 -1
  78. package/dist/cdn/{YZCNLWCK.js → OQMMSCLX.js} +1 -1
  79. package/dist/cdn/{E33FRS3A.js → OZVQRDTO.js} +1 -1
  80. package/dist/cdn/{E7C4ISUJ.js → P3YHSJCB.js} +1 -1
  81. package/dist/cdn/{2PTMXOMF.js → PHGSNNMQ.js} +1 -1
  82. package/dist/cdn/{H3NTIWHD.js → QBPJLGAM.js} +1 -1
  83. package/dist/cdn/{TWCRSSGO.js → QLTSABSA.js} +1 -1
  84. package/dist/cdn/{2GXKCJ2T.js → QMUSSZL2.js} +1 -1
  85. package/dist/cdn/{5Z4SUP7T.js → QNGGDSZS.js} +1 -1
  86. package/dist/cdn/{ZGEPGEKV.js → QPMXVWMP.js} +1 -1
  87. package/dist/cdn/{FETSFCBL.js → QPQKALNN.js} +1 -1
  88. package/dist/cdn/{UK7FBP7U.js → RD7MZ7SN.js} +1 -1
  89. package/dist/cdn/{T5H5QDAS.js → RGOUIRT7.js} +1 -1
  90. package/dist/cdn/{CL3AYK25.js → RI7U6FA5.js} +1 -1
  91. package/dist/cdn/{N63JOPKM.js → RPLXKWJA.js} +1 -1
  92. package/dist/cdn/{NYLOU7ZM.js → RSJVFZPY.js} +1 -1
  93. package/dist/cdn/{CTCWANBA.js → RUPNX57X.js} +1 -1
  94. package/dist/cdn/{HXRZFGOY.js → RX2VR5KK.js} +1 -1
  95. package/dist/cdn/{ZDXFFQJI.js → SEBM4AAA.js} +1 -1
  96. package/dist/cdn/{2S26J4GF.js → SNRLIWGC.js} +1 -1
  97. package/dist/cdn/{BOTOPHKQ.js → SOELU2Q6.js} +1 -1
  98. package/dist/cdn/{VINK2SLZ.js → SONZCBAV.js} +1 -1
  99. package/dist/cdn/{MCHVWDD7.js → SSNO5VHY.js} +1 -1
  100. package/dist/cdn/{Z7SEICRM.js → ST2WEDFS.js} +1 -1
  101. package/dist/cdn/{3ADRLEU7.js → SV2XM7U2.js} +1 -1
  102. package/dist/cdn/{7QSOGNZM.js → SYHEO472.js} +1 -1
  103. package/dist/cdn/{FM47F4IP.js → SZYWQAVW.js} +1 -1
  104. package/dist/cdn/{3BNJMNCD.js → T5DCIH4Q.js} +1 -1
  105. package/dist/cdn/{7Q5LNER7.js → T6F3TWF6.js} +1 -1
  106. package/dist/cdn/{JLQOOJFJ.js → T7JWS4CF.js} +1 -1
  107. package/dist/cdn/{YQI2AE2N.js → TBB4KG37.js} +1 -1
  108. package/dist/cdn/{3DWPAQFI.js → TRNQ5OTY.js} +1 -1
  109. package/dist/cdn/{3VP33LM6.js → TTXN5R4E.js} +1 -1
  110. package/dist/cdn/{6R6R4TFH.js → U4D4YJ7L.js} +1 -1
  111. package/dist/cdn/{6OHUYDZC.js → UK5XQCTX.js} +1 -1
  112. package/dist/cdn/{WRO2YCVL.js → UNN6SVUI.js} +1 -1
  113. package/dist/cdn/{UNGZMOQE.js → VCKCRMSD.js} +1 -1
  114. package/dist/cdn/{RFKW5BFU.js → VM2LS6TR.js} +1 -1
  115. package/dist/cdn/{AZJ5EUBD.js → VNWIFVKC.js} +1 -1
  116. package/dist/cdn/{YMJF3GAO.js → VW4UJ7IY.js} +1 -1
  117. package/dist/cdn/{5DFDXWTM.js → VWNMKVMJ.js} +1 -1
  118. package/dist/cdn/{KIGTSUFO.js → VYOCZUVH.js} +1 -1
  119. package/dist/cdn/{7ESYN6XO.js → W6GIBBBE.js} +1 -1
  120. package/dist/cdn/{S2E4VZKV.js → WCFHQRWL.js} +1 -1
  121. package/dist/cdn/{2MNK2M2M.js → WMXP3LPH.js} +1 -1
  122. package/dist/cdn/{QCME7YYI.js → WQUZG2NJ.js} +1 -1
  123. package/dist/cdn/{QCLWTDIC.js → WVRDKKBC.js} +1 -1
  124. package/dist/cdn/{LJTZPQQH.js → X3YWKGD7.js} +1 -1
  125. package/dist/cdn/{NFLDV2BR.js → XGUD7O6G.js} +1 -1
  126. package/dist/cdn/{JH2LBLK4.js → XRQNNWH3.js} +1 -1
  127. package/dist/cdn/{LFBK5LL3.js → Y2Y7HUJR.js} +1 -1
  128. package/dist/cdn/{COSMV4TW.js → YEER3LD7.js} +1 -1
  129. package/dist/cdn/{S5QUASO4.js → YEMYE6JK.js} +1 -1
  130. package/dist/cdn/{DQHGHZDB.js → YGVATVII.js} +1 -1
  131. package/dist/cdn/{2W2FGE2Q.js → YR6F4HW7.js} +1 -1
  132. package/dist/cdn/{2VVUA5HG.js → Z4LGN5M5.js} +1 -1
  133. package/dist/cdn/{PFI2WBBU.js → ZFPRM3GK.js} +1 -1
  134. package/dist/cdn/index.js +1 -1
  135. package/dist/chunks/runtime.js +1 -1
  136. package/dist/components/arcgis-solutions-assistant/customElement.js +335 -324
  137. package/dist/components/solutions-deploy-app/customElement.js +3 -3
  138. package/dist/docs/api.json +1 -1
  139. package/dist/docs/docs.json +1 -1
  140. package/dist/docs/web-types.json +1 -1
  141. package/dist/solutions-components_commit.txt +9 -6
  142. package/package.json +1 -1
  143. package/dist/cdn/JGPIG5MJ.js +0 -358
  144. package/dist/cdn/VQ7WZGV2.js +0 -2
  145. package/dist/cdn/XXE533EC.js +0 -2
@@ -1,358 +0,0 @@
1
- /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{d as kr,e as po,f as Gi,g as Ji,h as Zi}from"./NQH7ZZWD.js";import{a as Vi}from"./MHMM4RFR.js";import{a as Cc,b as kc,c as Ec,f as gs,g as ys,j as Pc}from"./JNQB7T54.js";import b from"./NISCRPTA.js";import a from"./XOPNEAS5.js";import{b as rc,c as nc}from"./2B4SGB3I.js";import{b as Li}from"./RLSY4VUQ.js";import"./AO7XKW2U.js";import{a as tc}from"./YMJF3GAO.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as dc,Aa as xc,Ab as uo,Ba as ps,Ca as ms,Da as Ic,Ea as vc,Eb as fs,Fa as Cr,Fb as hs,Ga as Tc,Gb as ge,Ha as v,Ia as L,J as ac,Ja as Wi,K as ke,Ka as Hi,L as lc,M as ns,N as Fi,O as ji,P as os,Q as lo,R as W,S as zi,T as U,U as dt,Ua as O,V as pt,W as ss,X as cc,Y as uc,Z as Ui,_ as is,a as he,aa as pc,b as V,ba as co,ca as as,da as mc,ea as fc,fa as hc,g as ic,ga as ls,ha as gc,ia as Dt,j as Ve,ja as qi,k as Lt,ka as cs,la as N,ma as A,na as Ft,nb as Sc,oa as mt,pa as yc,qa as us,ra as _c,s as ts,sa as wc,ta as ds,ua as Bi,va as Sr,wa as Ki,xa as bc,y as rs,ya as Ac}from"./M6KMGWHY.js";import"./TEHBW75B.js";import"./RSPNBIIE.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./36LRAUE4.js";import"./JMY4B4WQ.js";import"./VQ5ZAQUF.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./6ERMTA3J.js";import"./GF4QELNV.js";import{l as oc,v as Di}from"./3TAQSXLA.js";import"./PY6RTQDR.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as ec}from"./ZGEPGEKV.js";import{F as Ql,G as Yl,H as Xl,L as Ni,h as Wl,i as ut,k as Hl,l as Ri,q as $i,t as Vl,w as Gl,x as Jl,y as Zl}from"./T3EPRHTT.js";import{c as Kl}from"./EXBEKVP5.js";export default $arcgis.t(([Rl,VW,JW,gp,yy,_y,Ey,tH,nH,pJ,XA,Np,xr,fl,qp,,Lp,Ry,{addressToLocations:$y},Ny,Ly,Bp,{createRenderer:Dy},{getSchemesByTag:Fy,getSchemes:jy},{getBackgroundColorTheme:Dp},{createAgeRenderer:zy,createContinuousRenderer:Uy},{getSchemesByTag:vl},{createContinuousRenderer:qy},{createRenderer:By},{getSchemesByTag:Ky},{createRenderer:Wy},{getSchemesByTag:Hy},{createRenderer:Vy},{getSchemesByTag:Gy},{createRenderer:Jy},{getSchemesByTag:Zy},{createAgeRenderer:Qy,createContinuousRenderer:Yy},{createRenderer:Xy},{getSchemesByTag:e_},t_,Kp,Wp,{formatDateOnly:r_,convertDateFormatToIntlOptions:ci,formatTimeOnly:n_,formatDate:Fp},o_,s_,i_,a_,l_,Hp,,{fetchKnowledgeGraph:jp,executeQueryStreaming:c_,executeSearchStreaming:u_},d_,{getBindParametersFromCypherQuery:p_},,,,,,,,,,,,,,,,,,,,,,,,,m4,h4,,,,,,,,,,,,,fx,hx,{r:sc},{r:ao}])=>{var mo=class extends Zl{constructor(e){if(super(e),this.it=Ri,e.type!==Gl.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===Ri||e==null)return this._t=void 0,this.it=e;if(e===Hl)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:[]}}};mo.directiveName="unsafeHTML",mo.resultType=1;var Oc=Jl(mo);var d=v;async function Qi(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
-
4
- If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
5
-
6
- Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
7
- |`,`
8
- \u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
9
- `].join(" "));let n=await pc(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var Y=async(t,e)=>{await Qi("trace_message",t,e)},ye=async(t,e)=>{await Qi("graph_ux_suggestion",t,e)};var Em={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},nv=Object.keys(Em);var ea=Symbol.for("langgraph-zod");ea in globalThis||(globalThis[ea]=new WeakSet);function $c(t){let e=globalThis[ea];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return hs(r,{jsonSchemaExtra:n})},reducer(n,o){return hs(r,{default:cs(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{$c(A.ZodType.prototype),$c(v.ZodType.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var Nc=class extends fc{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=cs(t);n!=null&&(r.default=n)}return super.add(t,...e)}},Rm=new Nc(fs);var Jm=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),Zm=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),Qm=["approve","edit","reject"],Ym=A.enum(Qm),Xm=A.object({allowedDecisions:A.array(Ym),description:A.union([A.string(),Zm]).optional(),argsSchema:A.record(A.any()).optional(),when:Jm.optional()}),pC=A.object({interruptOn:A.record(A.union([A.boolean(),Xm])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var rf=`<role>
10
- Context Extraction Assistant
11
- </role>
12
-
13
- <primary_objective>
14
- Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
15
- </primary_objective>
16
-
17
- <objective_information>
18
- You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
19
- This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
20
- </objective_information>
21
-
22
- <instructions>
23
- The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
24
- You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
25
- </instructions>
26
-
27
- The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
28
-
29
- With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
30
- Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
31
-
32
- <messages>
33
- Messages to summarize:
34
- {messages}
35
- </messages>`;var nf=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),aa=A.object({fraction:A.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().positive("Tokens must be greater than 0").optional(),messages:A.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Bc=A.object({fraction:A.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:A.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),PC=A.object({model:A.custom(),trigger:A.union([aa,A.array(aa)]).optional(),keep:Bc.optional(),tokenCounter:nf.optional(),summaryPrompt:A.string().default(rf),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var UC=A.object({model:A.string().or(A.instanceof(_c)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var GC=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var XC=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var of=["continue","error","end"],sf="continue";var af=A.enum(of).default(sf);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:af});var uk=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var lf=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),cf=A.object({content:A.string().describe("Content of the todo item"),status:lf}),_k=A.object({todos:A.array(cf).default([])});var Ik=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),vk=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var _s=A.object({maxRetries:A.number().min(0).default(2),retryOn:A.union([A.function().args(A.instanceof(Error)).returns(A.boolean()),A.array(A.custom())]).default(()=>()=>!0),backoffFactor:A.number().min(0).default(2),initialDelayMs:A.number().min(0).default(1e3),maxDelayMs:A.number().min(0).default(6e4),jitter:A.boolean().default(!0)});var Fk=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(_s);var Hk=A.object({tools:A.array(A.union([A.custom(),A.custom(),A.string()])).optional(),onFailure:A.union([A.literal("error"),A.literal("continue"),A.literal("raise"),A.literal("return_message"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(_s);var aE=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var dE=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function fo(t,e){return t.lc_error_code=e,t.message=`${t.message}
36
-
37
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
38
- `,t}function P(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 zt=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return zt=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 ho(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var go=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 C=class extends Error{},G=class t extends C{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 ht({message:n,cause:go(r)});let s=r?.error;return e===400?new Pr(e,s,n,o):e===401?new Or(e,s,n,o):e===403?new Mr(e,s,n,o):e===404?new Rr(e,s,n,o):e===409?new $r(e,s,n,o):e===422?new Nr(e,s,n,o):e===429?new Lr(e,s,n,o):e>=500?new Dr(e,s,n,o):new t(e,s,n,o)}},H=class extends G{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ht=class extends G{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Fe=class extends ht{constructor({message:e}={}){super({message:e??"Request timed out."})}},Pr=class extends G{},Or=class extends G{},Mr=class extends G{},Rr=class extends G{},$r=class extends G{},Nr=class extends G{},Lr=class extends G{},Dr=class extends G{},Fr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},jr=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},je=class extends Error{constructor(e){super(e)}},Ut=class extends G{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}},yo=class extends C{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var wf=/^[a-z][a-z0-9+.-]*:/i,Kc=t=>wf.test(t),de=t=>(de=Array.isArray,de(t)),la=de;function ws(t){return typeof t!="object"?{}:t??{}}function ca(t){if(!t)return!0;for(let e in t)return!1;return!0}function Wc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _o(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Hc=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var Vc=t=>{try{return JSON.parse(t)}catch{return}};var ze=t=>new Promise(e=>setTimeout(e,t));var gt="6.48.0";var Qc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function bf(){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 Af=()=>{let t=bf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gt,"X-Stainless-OS":Jc(Deno.build.os),"X-Stainless-Arch":Gc(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":gt,"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":gt,"X-Stainless-OS":Jc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Gc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=xf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gt,"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":gt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function xf(){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 Gc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Jc=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"),Zc,Yc=()=>Zc??(Zc=Af());function bs(){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 ua(...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 wo(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return ua({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function As(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 da(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 eu=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var pa="RFC3986",ma=t=>String(t),fa={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ma},tu="RFC1738";var xs=(t,e)=>(xs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xs(t,e)),Ue=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var ha=1024,ru=(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+=ha){let c=s.length>=ha?s.slice(a,a+ha):s,l=[];for(let u=0;u<c.length;++u){let p=c.charCodeAt(u);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===tu&&(p===40||p===41)){l[l.length]=c.charAt(u);continue}if(p<128){l[l.length]=Ue[p];continue}if(p<2048){l[l.length]=Ue[192|p>>6]+Ue[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=Ue[224|p>>12]+Ue[128|p>>6&63]+Ue[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Ue[240|p>>18]+Ue[128|p>>12&63]+Ue[128|p>>6&63]+Ue[128|p&63]}i+=l.join("")}return i};function nu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ga(t,e){if(de(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var su={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},iu=function(t,e){Array.prototype.push.apply(t,de(e)?e:[e])},ou,re={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ru,encodeValuesOnly:!1,format:pa,formatter:ma,indices:!1,serializeDate(t){return(ou??(ou=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function vf(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var ya={};function au(t,e,r,n,o,s,i,a,c,l,u,p,f,w,x,g,b,S){let h=t,I=S,E=0,D=!1;for(;(I=I.get(ya))!==void 0&&!D;){let K=I.get(t);if(E+=1,typeof K<"u"){if(K===E)throw new RangeError("Cyclic object value");D=!0}typeof I.get(ya)>"u"&&(E=0)}if(typeof l=="function"?h=l(e,h):h instanceof Date?h=f?.(h):r==="comma"&&de(h)&&(h=ga(h,function(K){return K instanceof Date?f?.(K):K})),h===null){if(s)return c&&!g?c(e,re.encoder,b,"key",w):e;h=""}if(vf(h)||nu(h)){if(c){let K=g?e:c(e,re.encoder,b,"key",w);return[x?.(K)+"="+x?.(c(h,re.encoder,b,"value",w))]}return[x?.(e)+"="+x?.(String(h))]}let k=[];if(typeof h>"u")return k;let q;if(r==="comma"&&de(h))g&&c&&(h=ga(h,c)),q=[{value:h.length>0?h.join(",")||null:void 0}];else if(de(l))q=l;else{let K=Object.keys(h);q=u?K.sort(u):K}let ue=a?String(e).replace(/\./g,"%2E"):String(e),B=n&&de(h)&&h.length===1?ue+"[]":ue;if(o&&de(h)&&h.length===0)return B+"[]";for(let K=0;K<q.length;++K){let Q=q[K],ql=typeof Q=="object"&&typeof Q.value<"u"?Q.value:h[Q];if(i&&ql===null)continue;let Mi=p&&a?Q.replace(/\./g,"%2E"):Q,Cm=de(h)?typeof r=="function"?r(B,Mi):B:B+(p?"."+Mi:"["+Mi+"]");S.set(t,E);let Bl=new WeakMap;Bl.set(ya,S),iu(k,au(ql,Cm,r,n,o,s,i,a,r==="comma"&&g&&de(h)?null:c,l,u,p,f,w,x,g,b,Bl))}return k}function Tf(t=re){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||re.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=pa;if(typeof t.format<"u"){if(!xs(fa,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=fa[r],o=re.filter;(typeof t.filter=="function"||de(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in su?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=re.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:re.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:re.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:re.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:re.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?re.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:re.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:re.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:re.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:re.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:re.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:re.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:re.strictNullHandling}}function lu(t,e={}){let r=t,n=Tf(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):de(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=su[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 w=o[f];n.skipNulls&&r[w]===null||iu(i,au(r[w],w,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),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),u.length>0?p+u:""}function cu(t){return lu(t,{arrayFormat:"brackets"})}function pu(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 uu;function we(t){let e;return(uu??(e=new globalThis.TextEncoder,uu=e.encode.bind(e)))(t)}var du;function _a(t){let e;return(du??(e=new globalThis.TextDecoder,du=e.decode.bind(e)))(t)}var be,Ae,qt=class{constructor(){be.set(this,void 0),Ae.set(this,void 0),P(this,be,new Uint8Array,"f"),P(this,Ae,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?we(e):e;P(this,be,pu([_(this,be,"f"),r]),"f");let n=[],o;for(;(o=Cf(_(this,be,"f"),_(this,Ae,"f")))!=null;){if(o.carriage&&_(this,Ae,"f")==null){P(this,Ae,o.index,"f");continue}if(_(this,Ae,"f")!=null&&(o.index!==_(this,Ae,"f")+1||o.carriage)){n.push(_a(_(this,be,"f").subarray(0,_(this,Ae,"f")-1))),P(this,be,_(this,be,"f").subarray(_(this,Ae,"f")),"f"),P(this,Ae,null,"f");continue}let s=_(this,Ae,"f")!==null?o.preceding-1:o.preceding,i=_a(_(this,be,"f").subarray(0,s));n.push(i),P(this,be,_(this,be,"f").subarray(o.index),"f"),P(this,Ae,null,"f")}return n}flush(){return _(this,be,"f").length?this.decode(`
39
- `):[]}};be=new WeakMap,Ae=new WeakMap;qt.NEWLINE_CHARS=new Set([`
40
- `,"\r"]);qt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Cf(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 mu(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 vs={off:0,error:200,warn:300,info:400,debug:500},wa=(t,e,r)=>{if(t){if(Wc(vs,t))return t;X(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(vs))}`)}};function bo(){}function Is(t,e,r){return!e||vs[t]>vs[r]?bo:e[t].bind(e)}var kf={error:bo,warn:bo,info:bo,debug:bo},fu=new WeakMap;function X(t){let e=t.logger,r=t.logLevel??"off";if(!e)return kf;let n=fu.get(e);if(n&&n[0]===r)return n[1];let o={error:Is("error",e,r),warn:Is("warn",e,r),info:Is("info",e,r),debug:Is("debug",e,r)};return fu.set(e,[r,o]),o}var Ge=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()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Ao,_e=class t{constructor(e,r,n){this.iterator=e,Ao.set(this,void 0),this.controller=r,P(this,Ao,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,i=n?X(n):console;async function*a(){if(s)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let l of Ef(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(p){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),p}if(u&&u.error)throw new G(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(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new G(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}c=!0}catch(l){if(ho(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 qt,c=e.getReader(),l=!1,u,p=()=>{u??(u=c.cancel()),u.catch(()=>{})};r.signal.addEventListener("abort",p,{once:!0});try{if(r.signal.aborted){p();return}for(;;){let{value:f,done:w}=await c.read();if(w){l=!0;break}if(r.signal.aborted)return;for(let x of a.decode(f)){if(r.signal.aborted)return;yield x}}if(r.signal.aborted)return;for(let f of a.flush()){if(r.signal.aborted)return;yield f}}finally{r.signal.removeEventListener("abort",p),l||p(),c.releaseLock()}}async function*i(){if(o)throw new C("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(r.signal.aborted||ho(c))return;throw c}finally{a||r.abort()}}return new t(i,r,n)}[(Ao=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,Ao,"f")),new t(()=>o(r),this.controller,_(this,Ao,"f"))]}toReadableStream(){let e=this,r;return ua({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=we(JSON.stringify(o)+`
41
- `);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Ef(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("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 C("Attempted to iterate over a response with no body");let r=new ba,n=new qt,o=As(t.body);for await(let s of Pf(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*Pf(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"?we(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=mu(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ba=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(`
42
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Of(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Of(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Ts(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return X(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):_e.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.json();return Aa(f,r)}return await r.text()})();return X(t).debug(`[${n}] response parsed`,Ge({retryOfRequestLogID:o,url:r.url,status:r.status,body:i,durationMs:Date.now()-s})),i}function Aa(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var xo,Bt=class t extends Promise{constructor(e,r,n=Ts){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,xo.set(this,void 0),P(this,xo,e,"f")}_thenUnwrap(e){return new t(_(this,xo,"f"),this.responsePromise,async(r,n)=>Aa(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,xo,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};xo=new WeakMap;var Ss,zr=class{constructor(e,r,n,o){Ss.set(this,void 0),P(this,Ss,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,Ss,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ss=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Io=class extends Bt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await Ts(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},pe=class extends zr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},$=class extends zr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...ws(this.options.query),after:r}}:null}},j=class extends zr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ws(this.options.query),after:e}}:null}},ee=class extends zr{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ws(this.options.query),after:e}}:null}};var Rf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},$f="urn:ietf:params:oauth:grant-type:token-exchange",Cs=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??bs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r={grant_type:$f,subject_token:e,subject_token_type:Rf[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let c=await n.text(),l;try{l=JSON.parse(c)}catch{}throw n.status===400||n.status===401||n.status===403?new Ut(n.status,l,n.headers):G.generate(n.status,l,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new C("Token exchange response missing 'access_token' field");let s=o.access_token,i=o.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:s,expiresAt:a},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var hu=Symbol("brand.privateNullableHeaders"),Nf=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*Lf(t){if(!t)return;if(hu in t){let{values:n,nulls:o}=t;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():la(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=la(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,i]of Lf(n)){if(!Nf.test(s))throw new TypeError(`Header name must be a valid HTTP token ["${s}"]`);let a=s.toLowerCase();o.has(a)||(e.delete(a),o.add(a)),i===null?(e.delete(a),r.add(a)):(e.append(a,i),r.delete(a))}}return{[hu]:!0,values:e,nulls:r}};var yu=Symbol("brand.privateStreamingFile");function Es(t,e,r){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[yu]:!0,data:t,name:e,...r?.type?{type:r.type}:{}}}var Sa=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Br(t,e,r){return Sa(),new File(t,e??"unknown_file",r)}function qr(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Kr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",yt=async(t,e)=>Ia(t.body)?ks(t.body)?wu(t):{...t,body:await _u(t.body,e)}:t,me=async(t,e)=>ks(t.body)?wu(t):{...t,body:await _u(t.body,e)},gu=new WeakMap;function Df(t){let e=typeof t=="function"?t:t.fetch,r=gu.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return gu.set(e,n),n}var _u=async(t,e)=>{if(!await Df(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,o])=>Ta(r,n,o))),r},Ps=t=>t instanceof Blob&&"name"in t,Ca=t=>typeof t=="object"&&t!==null&&"getReader"in t&&typeof t.getReader=="function",vo=t=>typeof t=="object"&&t!==null&&yu in t,ka=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Kr(t)||Ca(t)||vo(t)||Ps(t)),ks=t=>{if(vo(t)||Kr(t)||Ca(t))return!0;if(Array.isArray(t))return t.some(ks);if(t&&typeof t=="object"&&!Ps(t)&&!(t instanceof Response)){for(let e in t)if(ks(t[e]))return!0}return!1},Ia=t=>{if(ka(t))return!0;if(Array.isArray(t))return t.some(Ia);if(t&&typeof t=="object"){for(let e in t)if(Ia(t[e]))return!0}return!1},wu=t=>{let e=`openai-${Math.random().toString(36).slice(2)}`,r=wo(Ff(t.body,e));return{...t,body:r,headers:T([{"content-type":`multipart/form-data; boundary=${e}`},t.headers])}};async function*Ff(t,e){for await(let{key:r,value:n}of jf(t)){if(yield we(`--${e}\r
43
- `),ka(n)){let o=zf(n),s=Uf(n);yield we(`Content-Disposition: form-data; name="${xa(r)}"; filename="${xa(o)}"\r
44
- Content-Type: ${s}\r
45
- \r
46
- `),yield*Ur(qf(n))}else yield we(`Content-Disposition: form-data; name="${xa(r)}"\r
47
- \r
48
- ${String(n)}`);yield we(`\r
49
- `)}yield we(`--${e}--\r
50
- `)}async function*jf(t){if(!(!t||typeof t!="object"))for(let[e,r]of Object.entries(t))yield*va(e,r)}async function*va(t,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||ka(e))yield{key:t,value:e};else if(Array.isArray(e))for(let r of e)yield*va(t+"[]",r);else if(typeof e=="object")for(let[r,n]of Object.entries(e))yield*va(`${t}[${r}]`,n);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function zf(t){return vo(t)?t.name:qr(t)??"unknown_file"}function Uf(t){return vo(t)?t.type||"application/octet-stream":Ps(t)&&t.type?t.type:t instanceof Response&&t.headers.get("content-type")||"application/octet-stream"}function qf(t){return vo(t)?t.data:t}async function*Ur(t){if(typeof t=="string")yield we(t);else if(ArrayBuffer.isView(t))yield new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)yield new Uint8Array(t);else if(t instanceof Response)t.body?yield*Ur(t.body):yield*Ur(await t.blob());else if(t instanceof Blob)typeof t.stream=="function"?yield*Ur(t.stream()):yield new Uint8Array(await t.arrayBuffer());else if(Ca(t))for await(let e of As(t))yield*Ur(e);else if(Kr(t))for await(let e of t)yield*Ur(e);else throw new TypeError(`Invalid streaming file chunk: ${String(t)}`)}function xa(t){return t.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var Ta=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Br([await r.blob()],qr(r)));else if(Kr(r))t.append(e,Br([await new Response(wo(r)).blob()],qr(r)));else if(Ps(r))t.append(e,r,qr(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Ta(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Ta(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var bu=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Bf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&bu(t),Kf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function To(t,e,r){if(Sa(),t=await t,Bf(t))return t instanceof File?t:Br([await t.arrayBuffer()],t.name);if(Kf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Br(await Ea(o),e,r)}let n=await Ea(t);if(e||(e=qr(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Br(n,e,r)}async function Ea(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(bu(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Kr(t))for await(let r of t)e.push(...await Ea(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Wf(t)}`)}return e}function Wf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var y=class{constructor(e){this._client=e}};function xu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Au=Object.freeze(Object.create(null)),Vf=(t=xu)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i=r.reduce((u,p,f)=>{/[?#]/.test(p)&&(o=!0);let w=n[f],x=(o?encodeURIComponent:t)(""+w);return f!==n.length&&(w==null||typeof w=="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??Au)??Au)?.toString)&&(x=w+"",s.push({start:u.length+p.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),u+p+(f===n.length?"":x)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((u,p)=>u.start-p.start),s.length>0){let u=0,p=s.reduce((f,w)=>{let x=" ".repeat(w.start-u),g="^".repeat(w.length);return u=w.start+w.length,f+x+g},"");throw new C(`Path parameters result in path with invalid segments:
51
- ${s.map(f=>f.error).join(`
52
- `)}
53
- ${i}
54
- ${p}`)}return i},m=Vf(xu);var Kt=class extends y{list(e,r={},n){return this._client.getAPIList(m`/chat/completions/${e}/messages`,$,{query:r,...n,__security:{bearerAuth:!0}})}};function So(t){return t!==void 0&&"function"in t&&t.function!==void 0}function vu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Co(t){return t?.$brand==="auto-parseable-response-format"}function Wt(t){return t?.$brand==="auto-parseable-tool"}function Tu(t,e){return!e||!Pa(e)?{...t,choices:t.choices.map(r=>(Cu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:ko(t,e)}function ko(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Fr;if(n.finish_reason==="content_filter")throw new jr;return Cu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Zf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Jf(e,n.message.content):null}}});return{...t,choices:r}}function Jf(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Zf(t,e){let r=t.tools?.find(n=>So(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Wt(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Su(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>So(n)&&n.function?.name===e.function.name);return So(r)&&(Wt(r)||r?.function.strict||!1)}function Pa(t){return Co(t.response_format)?!0:t.tools?.some(e=>Wt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Cu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ku(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _t=t=>t?.role==="assistant",Eo=t=>t?.role==="tool";var Po,Os,Ms,Oo,Mo,Rs,Ro,Je,$s,$o,Ns,Ls,Wr,Eu,Oa,wt=class{constructor(){Po.add(this),this.controller=new AbortController,Os.set(this,void 0),Ms.set(this,()=>{}),Oo.set(this,()=>{}),Mo.set(this,void 0),Rs.set(this,()=>{}),Ro.set(this,()=>{}),Je.set(this,{}),$s.set(this,[]),$o.set(this,!1),Ns.set(this,!1),Ls.set(this,!1),Wr.set(this,!1),P(this,Os,new Promise((e,r)=>{P(this,Ms,e,"f"),P(this,Oo,r,"f")}),"f"),P(this,Mo,new Promise((e,r)=>{P(this,Rs,e,"f"),P(this,Ro,r,"f")}),"f"),_(this,Os,"f").catch(()=>{}),_(this,Mo,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(r){_(this,Po,"m",Oa).call(this,r);return}this._emit("end")},_(this,Po,"m",Oa).bind(this))},0)}_connected(){this.ended||(_(this,Ms,"f").call(this),this._emit("connect"))}get ended(){return _(this,$o,"f")}get errored(){return _(this,Ns,"f")}get aborted(){return _(this,Ls,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),_(this,$s,"f").push({signal:e,listener:r})}on(e,r){return(_(this,Je,"f")[e]||(_(this,Je,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,Je,"f")[e];if(!n)return this;let o=n.findIndex(s=>s.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(_(this,Je,"f")[e]||(_(this,Je,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{P(this,Wr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}events(e){let r=[],n=[],o=this.ended,s,i=!1,a=()=>({value:void 0,done:!0}),c=()=>{for(;n.length;)n.shift().resolve(a())},l=()=>{!s||i||!n.length||(i=!0,n.shift().reject(s))},u=()=>{this.off(e,p),this.off("end",w),e!=="error"&&this.off("error",f),e!=="abort"&&this.off("abort",f)},p=(...x)=>{if(o)return;let g=n.shift();g?g.resolve({value:x,done:!1}):r.push(x)},f=x=>{s=x,r.length||l()},w=()=>{o=!0,u(),r.length||(l(),c())};return o||(this.on(e,p),this.on("end",w),e!=="error"&&this.on("error",f),e!=="abort"&&this.on("abort",f)),{next:()=>{let x=r.shift();return x?Promise.resolve({value:x,done:!1}):s&&!i?(i=!0,Promise.reject(s)):o?Promise.resolve(a()):new Promise((g,b)=>{n.push({resolve:g,reject:b})})},return:()=>(o=!0,r.length=0,u(),c(),Promise.resolve(a())),[Symbol.asyncIterator](){return this}}}async done(){P(this,Wr,!0,"f"),await _(this,Mo,"f")}_emit(e,...r){if(_(this,$o,"f"))return;e==="end"&&(_(this,Po,"m",Eu).call(this),P(this,$o,!0,"f"),_(this,Rs,"f").call(this));let n=_(this,Je,"f")[e];if(n&&(_(this,Je,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,Wr,"f")&&!n?.length&&Promise.reject(o),_(this,Oo,"f").call(this,o),_(this,Ro,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Wr,"f")&&!n?.length&&Promise.reject(o),_(this,Oo,"f").call(this,o),_(this,Ro,"f").call(this,o),this._emit("end")}}_emitFinal(){}};Os=new WeakMap,Ms=new WeakMap,Oo=new WeakMap,Mo=new WeakMap,Rs=new WeakMap,Ro=new WeakMap,Je=new WeakMap,$s=new WeakMap,$o=new WeakMap,Ns=new WeakMap,Ls=new WeakMap,Wr=new WeakMap,Po=new WeakSet,Eu=function(){for(let{signal:e,listener:r}of _(this,$s,"f").splice(0))e.removeEventListener("abort",r)},Oa=function(e){if(P(this,Ns,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new H),e instanceof H)return P(this,Ls,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function Pu(t){return typeof t.parse=="function"}var fe,Ma,Ds,Ra,$a,Na,Ou,Mu,Qf=10;function Yf(t){for(let e of t.choices)for(let r of e.message.tool_calls??[])r.id||(r.id=`call_${zt()}`)}var Hr=class extends wt{constructor(){super(...arguments),fe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Yf(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),Eo(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_t(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,fe,"m",Ma).call(this)}async finalMessage(){return await this.done(),_(this,fe,"m",Ds).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,fe,"m",Ra).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,fe,"m",$a).call(this)}async totalUsage(){return await this.done(),_(this,fe,"m",Na).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,fe,"m",Ds).call(this);r&&this._emit("finalMessage",r);let n=_(this,fe,"m",Ma).call(this);n&&this._emit("finalContent",n);let o=_(this,fe,"m",Ra).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,fe,"m",$a).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",_(this,fe,"m",Na).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),_(this,fe,"m",Ou).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ko(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:i="auto",stream:a,toolContext:c,...l}=r,u=c,p=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=Qf,afterCompletion:w}=o||{},x=r.tools.map(h=>{if(Wt(h)){if(!h.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),g={};for(let h of x)h.type==="function"&&(g[h.function.name||h.function.function.name]=h.function);let b="tools"in r?x.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of r.messages)this._addMessage(h,!1);let S=async h=>{if(h.type!=="function")return{message:void 0,functionCalled:!1};let I=h.id,{name:E,arguments:D}=h.function,k=g[E];if(!k){let B=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(g).map(K=>JSON.stringify(K)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:I,content:B},functionCalled:!1}}if(p&&p!==E){let B=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:s,tool_call_id:I,content:B},functionCalled:!1}}let q;if(Pu(k)){let B;try{B=await k.parse(D)}catch(K){let Q=K instanceof Error?K.message:String(K);return{message:{role:s,tool_call_id:I,content:Q},functionCalled:!1}}q=await k.function(B,n,u)}else q=await k.function(D,n,u);let ue=_(this,fe,"m",Mu).call(this,q);return{message:{role:s,tool_call_id:I,content:ue},functionCalled:!0}};for(let h=0;h<f;++h){let I=await this._createChatCompletion(e,{...l,tool_choice:i,tools:b,messages:[...this.messages]},o),E=I.choices[0]?.message;if(!E)throw new C("missing message in ChatCompletion response");if(!E.tool_calls?.length){await w?.(I,n);return}if(p||r.parallel_tool_calls===!1)for(let D of E.tool_calls){let k=await S(D);if(k.message&&this._addMessage(k.message),p&&k.functionCalled){await w?.(I,n);return}}else{let D=await Promise.allSettled(E.tool_calls.map(S));for(let k of D)if(k.status==="rejected")throw k.reason;for(let k of D)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message)}await w?.(I,n)}}};fe=new WeakSet,Ma=function(){return _(this,fe,"m",Ds).call(this).content??null},Ds=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(_t(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},Ra=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(_t(r)&&r?.tool_calls?.length)for(let n=r.tool_calls.length-1;n>=0;n--){let o=r.tool_calls[n];if(o?.type==="function")return o.function}}},$a=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Eo(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(o=>o.type==="function"&&o.id===r.tool_call_id)))return r.content}},Na=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},Ou=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Mu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var No=class t extends Hr{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),_t(e)&&e.content&&this._emit("content",e.content)}};var se={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},La=class extends Error{},Da=class extends Error{};function Xf(t,e=se.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return eh(t.trim(),e)}var eh=(t,e)=>{let r=t.length,n=0,o=f=>{throw new La(`${f} at position ${n}`)},s=f=>{throw new Da(`${f} at position ${n}`)},i=()=>(p(),n>=r&&o("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||se.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||se.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||se.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||se.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||se.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||se.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let f=n,w=!1;for(n++;n<r&&(t[n]!=='"'||w&&t[n-1]==="\\");)w=t[n]==="\\"?!w:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(w)))}catch(x){s(String(x))}else if(se.STR&e)try{return JSON.parse(t.substring(f,n-Number(w))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,p();let f={};try{for(;t[n]!=="}";){if(p(),n>=r&&se.OBJ&e)return f;let w=a();p(),n++;try{let x=i();Object.defineProperty(f,w,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(se.OBJ&e)return f;throw x}p(),t[n]===","&&n++}}catch{if(se.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(i()),p(),t[n]===","&&n++}catch{if(se.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){t==="-"&&se.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(w){if(se.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(w))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(se.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&se.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(x){s(String(x))}}},p=()=>{for(;n<r&&`
55
- \r `.includes(t[n]);)n++};return i()},Fa=t=>Xf(t,se.ALL^se.NUM);var te,Ze,Vr,Ee,ja,Fs,za,Ua,qa,Lo,Ba,Ru,Wa="chat.completion.chunk.message:";function $u(t,e,r){let n={type:"message",message:e,...r?{tool_call_ids:r}:{}};return{id:t.id,choices:[],created:t.created,model:t.model,object:`${Wa}${JSON.stringify(n)}`}}function th(t){return"type"in t&&t.type==="message"&&"message"in t||"object"in t&&typeof t.object=="string"&&t.object.startsWith(Wa)}function rh(t){return"type"in t?t:JSON.parse(t.object.slice(Wa.length))}var Ht=class t extends Hr{constructor(e){super(),te.add(this),Ze.set(this,void 0),Vr.set(this,void 0),Ee.set(this,void 0),P(this,Ze,e,"f"),P(this,Vr,[],"f")}get currentChatCompletionSnapshot(){return _(this,Ee,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion,this._listenForAbort(n?.signal),_(this,te,"m",ja).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)_(this,te,"m",za).call(this,s);if(o.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,te,"m",Lo).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,te,"m",ja).call(this),this._connected();let n=_e.fromReadableStream(e,this.controller),o;for await(let i of n){if(th(i)){let c=rh(i);if(_(this,Ee,"f")){let l=_(this,Ee,"f").choices[0]?.message.tool_calls;for(let[u,p]of c.tool_call_ids?.entries()??[]){let f=l?.[u];f&&p&&(f.id=p)}this._addChatCompletion(_(this,te,"m",Lo).call(this)),o=void 0}this._addMessage(c.message);continue}let a=i;o&&a.id&&o!==a.id&&this._addChatCompletion(_(this,te,"m",Lo).call(this)),_(this,te,"m",za).call(this,a),a.id&&(o=a.id)}if(n.controller.signal?.aborted)throw new H;if(_(this,Ee,"f"))return this._addChatCompletion(_(this,te,"m",Lo).call(this));let s=this._chatCompletions[this._chatCompletions.length-1];if(s)return s;throw new C("request ended without sending any chunks")}[(Ze=new WeakMap,Vr=new WeakMap,Ee=new WeakMap,te=new WeakSet,ja=function(){this.ended||P(this,Ee,void 0,"f")},Fs=function(r){let n=_(this,Vr,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},_(this,Vr,"f")[r.index]=n,n)},za=function(r){if(this.ended)return;let n=_(this,te,"m",Ru).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index],{delta:i}=o;i?.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",i.content,s.message.content),this._emit("content.delta",{delta:i.content,snapshot:s.message.content,parsed:s.message.parsed})),i?.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:i.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=_(this,te,"m",Fs).call(this,s);s.finish_reason&&(_(this,te,"m",qa).call(this,s),a.current_tool_call_index!=null&&_(this,te,"m",Ua).call(this,s,a.current_tool_call_index));for(let c of i?.tool_calls??[])a.current_tool_call_index!==c.index&&(_(this,te,"m",qa).call(this,s),a.current_tool_call_index!=null&&_(this,te,"m",Ua).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=c.index;for(let c of i?.tool_calls??[]){let l=s.message.tool_calls?.[c.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:c.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(l?.type,void 0))}}},Ua=function(r,n){if(_(this,te,"m",Fs).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let i=_(this,Ze,"f")?.tools?.find(a=>So(a)&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Wt(i)?i.$parseRaw(s.function.arguments):i?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},qa=function(r){let n=_(this,te,"m",Fs).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,te,"m",Ba).call(this);this._emit("content.done",{content:r.message.content,parsed:o?o.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Lo=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,Ee,"f");if(!r)throw new C("request ended without sending any chunks");return P(this,Ee,void 0,"f"),P(this,Vr,[],"f"),nh(r,_(this,Ze,"f"))},Ba=function(){let r=_(this,Ze,"f")?.response_format;return Co(r)?r:null},Ru=function(r){var n,o,s,i;let a=_(this,Ee,"f"),{choices:c,...l}=r;a?r.id&&Object.assign(a,l):a=P(this,Ee,{...l,choices:[]},"f");for(let{delta:u,finish_reason:p,index:f,logprobs:w=null,...x}of r.choices){let g=a.choices[f];if(g||(g=a.choices[f]={finish_reason:p,index:f,message:{},logprobs:w,...x}),w)if(!g.logprobs)g.logprobs=Object.assign({},w);else{let{content:k,refusal:q,...ue}=w;Object.assign(g.logprobs,ue),k&&((n=g.logprobs).content??(n.content=[]),g.logprobs.content.push(...k)),q&&((o=g.logprobs).refusal??(o.refusal=[]),g.logprobs.refusal.push(...q))}if(p&&(g.finish_reason=p,_(this,Ze,"f")&&Pa(_(this,Ze,"f")))){if(p==="length")throw new Fr;if(p==="content_filter")throw new jr}if(Object.assign(g,x),!u)continue;let{content:b,refusal:S,function_call:h,role:I,tool_calls:E,...D}=u;if(Object.assign(g.message,D),S&&(g.message.refusal=(g.message.refusal||"")+S),I&&(g.message.role=I),h&&(g.message.function_call?(h.name&&(g.message.function_call.name=h.name),h.arguments&&((s=g.message.function_call).arguments??(s.arguments=""),g.message.function_call.arguments+=h.arguments)):g.message.function_call=h),b&&(g.message.content=(g.message.content||"")+b,!g.message.refusal&&_(this,te,"m",Ba).call(this)&&(g.message.parsed=g.message.content.trim()?Fa(g.message.content):null)),E){g.message.tool_calls||(g.message.tool_calls=[]);for(let{index:k,id:q,type:ue,function:B,...K}of E){let Q=(i=g.message.tool_calls)[k]??(i[k]={});Object.assign(Q,K),q&&(Q.id=q),ue&&(Q.type=ue),B&&(Q.function??(Q.function={name:B.name??"",arguments:""})),B?.name&&(Q.function.name=B.name),B?.arguments&&(Q.function.arguments+=B.arguments,Su(_(this,Ze,"f"),Q)&&(Q.function.parsed_arguments=Fa(Q.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new _e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function nh(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:i,...a}=t,c={...a,id:r,choices:n.map(({message:l,finish_reason:u,index:p,logprobs:f,...w})=>{if(!u)throw new C(`missing finish_reason for choice ${p}`);let{content:x=null,function_call:g,tool_calls:b,...S}=l,h=l.role;if(!h)throw new C(`missing role for choice ${p}`);if(g){let{arguments:I,name:E}=g;if(I==null)throw new C(`missing function_call.arguments for choice ${p}`);if(!E)throw new C(`missing function_call.name for choice ${p}`);return{...w,message:{content:x,function_call:{arguments:I,name:E},role:h,refusal:l.refusal??null},finish_reason:u,index:p,logprobs:f}}return b?{...w,index:p,finish_reason:u,logprobs:f,message:{...S,role:h,content:x,refusal:l.refusal??null,tool_calls:b.map((I,E)=>{let{function:D,type:k,id:q,...ue}=I,{arguments:B,name:K,...Q}=D||{};if(k==null)throw new C(`missing choices[${p}].tool_calls[${E}].type
56
- ${Ka(t)}`);if(K==null)throw new C(`missing choices[${p}].tool_calls[${E}].function.name
57
- ${Ka(t)}`);if(B==null)throw new C(`missing choices[${p}].tool_calls[${E}].function.arguments
58
- ${Ka(t)}`);return{...ue,id:q||`call_${zt()}`,type:k,function:{...Q,name:K,arguments:B}}})}}:{...w,message:{...S,content:x,role:h,refusal:l.refusal??null},finish_reason:u,index:p,logprobs:f}}),created:o,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Tu(c,e)}function Ka(t){return JSON.stringify(t)}var Do=class t extends Ht{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}toReadableStream(){let e=[],r=[],n=!1,o,s,i=l=>{let u=r.shift();u?u.resolve(l):e.push(l)};this.on("chunk",l=>{o=l,i(l)}),this.on("message",l=>{if(_t(l)){s=l.tool_calls?.map(u=>u.id);return}if(Eo(l)){if(!o)throw new C("cannot serialize a tool message before receiving any chunks");i($u(o,l,s))}}),this.on("end",()=>{n=!0;for(let l of r)l.resolve(void 0);r.length=0}),this.on("abort",l=>{n=!0;for(let u of r)u.reject(l);r.length=0}),this.on("error",l=>{n=!0;for(let u of r)u.reject(l);r.length=0});let a=()=>({next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((u,p)=>r.push({resolve:u,reject:p})).then(u=>u?{value:u,done:!1}:{value:void 0,done:!0});let l=e.shift();return l?{value:l,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new _e(a,this.controller).toReadableStream()}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var Qe=class extends y{constructor(){super(...arguments),this.messages=new Kt(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return ku(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>ko(n,e))}runTools(e,r){return e.stream?Do.runTools(this._client,e,r):No.runTools(this._client,e,r)}stream(e,r){return Ht.createChatCompletion(this._client,e,r)}};Qe.Messages=Kt;var bt=class extends y{constructor(){super(...arguments),this.completions=new Qe(this._client)}};bt.Completions=Qe;var Gr=class extends y{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends y{list(e={},r){return this._client.getAPIList("/organization/audit_logs",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends y{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(m`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",pe,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends y{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends y{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends y{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",ee,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var en=class extends y{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var tn=class extends y{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var rn=class extends y{create(e,r,n){return this._client.post(m`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(m`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/groups/${e}/roles`,ee,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(m`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var nn=class extends y{create(e,r,n){return this._client.post(m`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(m`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/groups/${e}/users`,ee,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(m`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var At=class extends y{constructor(){super(...arguments),this.users=new nn(this._client),this.roles=new rn(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",ee,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};At.Users=nn;At.Roles=rn;var on=class extends y{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/api_keys`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var sn=class extends y{list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/certificates`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(m`/organization/projects/${e}/certificates/activate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(m`/organization/projects/${e}/certificates/deactivate`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var an=class extends y{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var ln=class extends y{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var cn=class extends y{retrieve(e,r){return this._client.get(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var un=class extends y{listRateLimits(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/rate_limits`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var dn=class extends y{create(e,r,n){return this._client.post(m`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/projects/${e}/roles`,ee,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var pn=class extends y{create(e,r,n){return this._client.post(m`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/spend_alerts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var mn=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/projects/${o}/groups/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,group_id:s}=r;return this._client.get(m`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(m`/projects/${o}/groups/${e}/roles`,ee,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(m`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends y{constructor(){super(...arguments),this.roles=new mn(this._client)}create(e,r,n){return this._client.post(m`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(m`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/groups`,ee,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Vt.Roles=mn;var fn=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/service_accounts/${e}/api_keys`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends y{constructor(){super(...arguments),this.apiKeys=new fn(this._client)}create(e,r,n){return this._client.post(m`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/service_accounts`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Gt.APIKeys=fn;var hn=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/projects/${o}/users/${e}/roles`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,user_id:s}=r;return this._client.get(m`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(m`/projects/${o}/users/${e}/roles`,ee,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(m`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends y{constructor(){super(...arguments),this.roles=new hn(this._client)}create(e,r,n){return this._client.post(m`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(m`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(m`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/projects/${e}/users`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(m`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Jt.Roles=hn;var ie=class extends y{constructor(){super(...arguments),this.users=new Jt(this._client),this.serviceAccounts=new Gt(this._client),this.apiKeys=new on(this._client),this.rateLimits=new un(this._client),this.modelPermissions=new cn(this._client),this.hostedToolPermissions=new ln(this._client),this.groups=new Vt(this._client),this.roles=new dn(this._client),this.dataRetention=new an(this._client),this.spendAlerts=new pn(this._client),this.certificates=new sn(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(m`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(m`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ie.Users=Jt;ie.ServiceAccounts=Gt;ie.APIKeys=on;ie.RateLimits=un;ie.ModelPermissions=cn;ie.HostedToolPermissions=ln;ie.Groups=Vt;ie.Roles=dn;ie.DataRetention=an;ie.SpendAlerts=pn;ie.Certificates=sn;var gn=class extends y{create(e,r,n){return this._client.post(m`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(m`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/organization/users/${e}/roles`,ee,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(m`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends y{constructor(){super(...arguments),this.roles=new gn(this._client)}retrieve(e,r){return this._client.get(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(m`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",j,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(m`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Zt.Roles=gn;var ae=class extends y{constructor(){super(...arguments),this.auditLogs=new Jr(this._client),this.adminAPIKeys=new Gr(this._client),this.usage=new tn(this._client),this.invites=new Yr(this._client),this.users=new Zt(this._client),this.groups=new At(this._client),this.roles=new Xr(this._client),this.dataRetention=new Qr(this._client),this.spendAlerts=new en(this._client),this.certificates=new Zr(this._client),this.projects=new ie(this._client)}};ae.AuditLogs=Jr;ae.AdminAPIKeys=Gr;ae.Usage=tn;ae.Invites=Yr;ae.Users=Zt;ae.Groups=At;ae.Roles=Xr;ae.DataRetention=Qr;ae.SpendAlerts=en;ae.Certificates=Zr;ae.Projects=ie;var xt=class extends y{constructor(){super(...arguments),this.organization=new ae(this._client)}};xt.Organization=ae;var yn=class extends y{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:T([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var _n=class extends y{create(e,r){return this._client.post("/audio/transcriptions",me({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var wn=class extends y{create(e,r){return this._client.post("/audio/translations",me({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var qe=class extends y{constructor(){super(...arguments),this.transcriptions=new _n(this._client),this.translations=new wn(this._client),this.speech=new yn(this._client)}};qe.Transcriptions=_n;qe.Translations=wn;qe.Speech=yn;var Qt=class extends y{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",$,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var bn=class extends y{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/assistants/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",$,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var An=class extends y{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var xn=class extends y{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var It=class extends y{constructor(){super(...arguments),this.sessions=new An(this._client),this.transcriptionSessions=new xn(this._client)}};It.Sessions=An;It.TranscriptionSessions=xn;var In=class extends y{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var vn=class extends y{retrieve(e,r){return this._client.get(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",j,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(m`/chatkit/threads/${e}/items`,j,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var vt=class extends y{constructor(){super(...arguments),this.sessions=new In(this._client),this.threads=new vn(this._client)}};vt.Sessions=In;vt.Threads=vn;var Tn=class extends y{list(e,r={},n){let{betas:o,...s}=r??{};return this._client.getAPIList(m`/responses/${e}/input_items?beta=true`,$,{query:s,...n,headers:T([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};var Sn=class extends y{count(e={},r){let{betas:n,...o}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:o,...r,headers:T([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var Tt=class extends y{constructor(){super(...arguments),this.inputItems=new Tn(this._client),this.inputTokens=new Sn(this._client)}create(e,r){let{betas:n,...o}=e;return this._client.post("/responses?beta=true",{body:o,...r,headers:T([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r={},n){let{betas:o,...s}=r??{};return this._client.get(m`/responses/${e}?beta=true`,{query:s,...n,headers:T([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},n?.headers]),stream:r?.stream??!1,__security:{bearerAuth:!0}})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(m`/responses/${e}?beta=true`,{...n,headers:T([{Accept:"*/*",...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r={},n){let{betas:o}=r??{};return this._client.post(m`/responses/${e}/cancel?beta=true`,{...n,headers:T([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}compact(e,r){let{betas:n,...o}=e;return this._client.post("/responses/compact?beta=true",{body:o,...r,headers:T([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};Tt.InputItems=Tn;Tt.InputTokens=Sn;var Cn=class extends y{create(e,r,n){return this._client.post(m`/threads/${e}/messages`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(m`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(m`/threads/${o}/messages/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/threads/${e}/messages`,$,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(m`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var kn=class extends y{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(m`/threads/${o}/runs/${s}/steps/${e}`,{query:i,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(m`/threads/${o}/runs/${e}/steps`,$,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Nu=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var Pe=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var le,Xt,Ha,Be,js,Oe,er,En,Yt,qs,xe,zs,Us,zo,Fo,jo,Lu,Du,Fu,ju,zu,Uu,qu,Ye=class extends wt{constructor(){super(...arguments),le.add(this),Ha.set(this,[]),Be.set(this,{}),js.set(this,{}),Oe.set(this,void 0),er.set(this,void 0),En.set(this,void 0),Yt.set(this,void 0),qs.set(this,void 0),xe.set(this,void 0),zs.set(this,void 0),Us.set(this,void 0),zo.set(this,void 0)}[(Ha=new WeakMap,Be=new WeakMap,js=new WeakMap,Oe=new WeakMap,er=new WeakMap,En=new WeakMap,Yt=new WeakMap,qs=new WeakMap,xe=new WeakMap,zs=new WeakMap,Us=new WeakMap,zo=new WeakMap,le=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=structuredClone(o),i=r.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Xt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=_e.fromReadableStream(e,this.controller);for await(let o of n)_(this,le,"m",Fo).call(this,o);if(n.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",jo).call(this))}toReadableStream(){return new _e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Xt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},i=await e.submitToolOutputs(r,s,{...o,signal:this.controller.signal});this._connected();for await(let a of i)_(this,le,"m",Fo).call(this,a);if(i.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",jo).call(this))}static createThreadAssistantStream(e,r,n){let o=new Xt;return o._run(()=>o._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new Xt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,zs,"f")}currentRun(){return _(this,Us,"f")}currentMessageSnapshot(){return _(this,Oe,"f")}currentRunStepSnapshot(){return _(this,zo,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Be,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,js,"f"))}async finalRun(){if(await this.done(),!_(this,er,"f"))throw Error("Final run was not received.");return _(this,er,"f")}async _createThreadAssistantStream(e,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let i of s)_(this,le,"m",Fo).call(this,i);if(s.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",jo).call(this))}async _createAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},i=await e.create(r,s,{...o,signal:this.controller.signal});this._connected();for await(let a of i)_(this,le,"m",Fo).call(this,a);if(i.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",jo).call(this))}static accumulateDelta(e,r){for(let[n,o]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=o;continue}let s=e[n];if(s==null){e[n]=o;continue}if(n==="index"||n==="type"){e[n]=o;continue}if(typeof s=="string"&&typeof o=="string")s+=o;else if(typeof s=="number"&&typeof o=="number")s+=o;else if(_o(s)&&_o(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(i=>typeof i=="string"||typeof i=="number")){s.push(...o);continue}for(let i of o){if(!_o(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s[a]=i:s[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};Xt=Ye,Fo=function(e){if(!this.ended)switch(P(this,zs,e,"f"),_(this,le,"m",Fu).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":_(this,le,"m",qu).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":_(this,le,"m",Du).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":_(this,le,"m",Lu).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},jo=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,er,"f"))throw Error("Final run has not been received");return _(this,er,"f")},Lu=function(e){let[r,n]=_(this,le,"m",zu).call(this,e,_(this,Oe,"f"));P(this,Oe,r,"f"),_(this,js,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,i=r.content[o.index];if(i&&i.type=="text")this._emit("textDelta",s,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=_(this,En,"f")){if(_(this,Yt,"f"))switch(_(this,Yt,"f").type){case"text":this._emit("textDone",_(this,Yt,"f").text,_(this,Oe,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Yt,"f").image_file,_(this,Oe,"f"));break}P(this,En,o.index,"f")}P(this,Yt,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,En,"f")!==void 0){let o=e.data.content[_(this,En,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,Oe,"f"));break;case"text":this._emit("textDone",o.text,_(this,Oe,"f"));break}}_(this,Oe,"f")&&this._emit("messageDone",e.data),P(this,Oe,void 0,"f")}},Du=function(e){let r=_(this,le,"m",ju).call(this,e);switch(P(this,zo,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==_(this,qs,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,xe,"f")&&this._emit("toolCallDone",_(this,xe,"f")),P(this,qs,s.index,"f"),P(this,xe,r.step_details.tool_calls[s.index],"f"),_(this,xe,"f")&&this._emit("toolCallCreated",_(this,xe,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":P(this,zo,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,xe,"f")&&(this._emit("toolCallDone",_(this,xe,"f")),P(this,xe,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Fu=function(e){_(this,Ha,"f").push(e),this._emit("event",e)},ju=function(e){switch(e.event){case"thread.run.step.created":return _(this,Be,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Be,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=Xt.accumulateDelta(r,n.delta);_(this,Be,"f")[e.data.id]=o}return _(this,Be,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":_(this,Be,"f")[e.data.id]=e.data;break}if(_(this,Be,"f")[e.data.id])return _(this,Be,"f")[e.data.id];throw new Error("No snapshot available")},zu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let i=r.content[s.index];r.content[s.index]=_(this,le,"m",Uu).call(this,s,i)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Uu=function(e,r){return Xt.accumulateDelta(r,e)},qu=function(e){switch(P(this,Us,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":P(this,er,e.data,"f"),_(this,xe,"f")&&(this._emit("toolCallDone",_(this,xe,"f")),P(this,xe,void 0,"f"));break;case"thread.run.cancelling":break}};var tr=class extends y{constructor(){super(...arguments),this.steps=new kn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(m`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(m`/threads/${o}/runs/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(m`/threads/${o}/runs/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/threads/${e}/runs`,$,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(m`/threads/${o}/runs/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return Ye.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await ze(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Ye.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(m`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return Ye.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};tr.Steps=kn;var St=class extends y{constructor(){super(...arguments),this.runs=new tr(this._client),this.messages=new Cn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/threads/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ye.createThreadAssistantStream(e,this._client.beta.threads,r)}};St.Runs=tr;St.Messages=Cn;var ve=class extends y{constructor(){super(...arguments),this.realtime=new It(this._client),this.responses=new Tt(this._client),this.chatkit=new vt(this._client),this.assistants=new bn(this._client),this.threads=new St(this._client)}};ve.Realtime=It;ve.Responses=Tt;ve.ChatKit=vt;ve.Assistants=bn;ve.Threads=St;var rr=class extends y{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Pn=class extends y{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(m`/containers/${o}/files/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var nr=class extends y{constructor(){super(...arguments),this.content=new Pn(this._client)}create(e,r,n){return this._client.post(m`/containers/${e}/files`,yt({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(m`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/containers/${e}/files`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(m`/containers/${o}/files/${e}`,{...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};nr.Content=Pn;var Ct=class extends y{constructor(){super(...arguments),this.files=new nr(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Ct.Files=nr;var On=class extends y{create(e,r,n){let{include:o,...s}=r;return this._client.post(m`/conversations/${e}/items`,{query:{include:o},body:s,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{conversation_id:o,...s}=r;return this._client.get(m`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/conversations/${e}/items`,j,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(m`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var kt=class extends y{constructor(){super(...arguments),this.items=new On(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};kt.Items=On;var or=class extends y{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&X(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:o},...r,__security:{bearerAuth:!0}});return n?s:(X(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=Nu(c)}),i)))}};var Mn=class extends y{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(m`/evals/${o}/runs/${s}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r,n){let{eval_id:o,...s}=r;return this._client.getAPIList(m`/evals/${o}/runs/${e}/output_items`,$,{query:s,...n,__security:{bearerAuth:!0}})}};var sr=class extends y{constructor(){super(...arguments),this.outputItems=new Mn(this._client)}create(e,r,n){return this._client.post(m`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(m`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/evals/${e}/runs`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(m`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(m`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};sr.OutputItems=Mn;var Et=class extends y{constructor(){super(...arguments),this.runs=new sr(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Et.Runs=sr;var ir=class extends y{create(e,r){return this._client.post("/files",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(m`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),i=await this.retrieve(e);for(;!i.status||!o.has(i.status);)if(await ze(r),i=await this.retrieve(e),Date.now()-s>n)throw new Fe({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var Rn=class extends y{};var $n=class extends y{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var ar=class extends y{constructor(){super(...arguments),this.graders=new $n(this._client)}};ar.Graders=$n;var Nn=class extends y{create(e,r,n){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,pe,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,j,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(m`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var lr=class extends y{constructor(){super(...arguments),this.permissions=new Nn(this._client)}};lr.Permissions=Nn;var Ln=class extends y{list(e,r={},n){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,$,{query:r,...n,__security:{bearerAuth:!0}})}};var cr=class extends y{constructor(){super(...arguments),this.checkpoints=new Ln(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",$,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,$,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};cr.Checkpoints=Ln;var Me=class extends y{constructor(){super(...arguments),this.methods=new Rn(this._client),this.jobs=new cr(this._client),this.checkpoints=new lr(this._client),this.alpha=new ar(this._client)}};Me.Methods=Rn;Me.Jobs=cr;Me.Checkpoints=lr;Me.Alpha=ar;var Dn=class extends y{};var Pt=class extends y{constructor(){super(...arguments),this.graderModels=new Dn(this._client)}};Pt.GraderModels=Dn;var ur=class extends y{createVariation(e,r){return this._client.post("/images/variations",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",me({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var dr=class extends y{retrieve(e,r){return this._client.get(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",pe,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var pr=class extends y{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Fn=class extends y{accept(e,r,n){return this._client.post(m`/realtime/calls/${e}/accept`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(m`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(m`/realtime/calls/${e}/refer`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(m`/realtime/calls/${e}/reject`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var jn=class extends y{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Xe=class extends y{constructor(){super(...arguments),this.clientSecrets=new jn(this._client),this.calls=new Fn(this._client)}};Xe.ClientSecrets=jn;Xe.Calls=Fn;function Bu(t,e){if(!e||!mg(e)){let r={...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(o=>({...o,parsed:null}))}:n)};return Ku(t,r)&&Ie(r),r}return Va(t,e)}function Va(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?gg(e,s):null};if(s.type==="message"){let i=s.content.map(a=>a.type==="output_text"?{...a,parsed:r?pg(e,a.text):null}:a);return{...s,content:i}}return s}),o=Object.assign({},t,{output:n});return Ku(t,o)&&Ie(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let s of o.output)if(s.type==="message"){for(let i of s.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),o}function pg(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function mg(t){return!!Co(t.text?.format)}function fg(t){return t?.$brand==="auto-parseable-tool"}function hg(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function gg(t,e){let r=hg(t.tools??[],e.name);return{...e,...e,parsed_arguments:fg(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Ku(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function Ie(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}function Hu(t,e){if(!e){if(t.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Wu(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&Ie(e);break}case"response.output_item.done":{F(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&Ie(e);break}case"response.content_part.added":{let r=F(e,t.output_index),n=r.type,o=t.part;n==="message"&&o.type!=="reasoning_text"?(r.content.push(structuredClone(o)),o.type==="output_text"&&Ie(e)):n==="reasoning"&&o.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(o)));break}case"response.content_part.done":{let r=F(e,t.output_index),n=t.part;if(r.type==="message"&&n.type!=="reasoning_text")Te(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&Ie(e);else if(r.type==="reasoning"&&n.type==="reasoning_text"){let o=r.content;if(!o)throw new C(`missing content at index ${t.content_index}`);Te(o,t.content_index),o[t.content_index]=structuredClone(n)}break}case"response.output_text.delta":{let r=F(e,t.output_index);if(r.type==="message"){let n=Te(r.content,t.content_index);if(n.type!=="output_text")throw new C(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=F(e,t.output_index);if(r.type==="message"){let n=Te(r.content,t.content_index);if(n.type!=="output_text")throw new C(`expected content to be 'output_text', got ${n.type}`);n.text=t.text,Ie(e)}break}case"response.output_text.annotation.added":{let r=F(e,t.output_index);if(r.type==="message"){let n=Te(r.content,t.content_index);if(n.type!=="output_text")throw new C(`expected content to be 'output_text', got ${n.type}`);n.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=F(e,t.output_index);if(r.type==="message"){let n=Te(r.content,t.content_index);if(n.type!=="refusal")throw new C(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}break}case"response.refusal.done":{let r=F(e,t.output_index);if(r.type==="message"){let n=Te(r.content,t.content_index);if(n.type!=="refusal")throw new C(`expected content to be 'refusal', got ${n.type}`);n.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=F(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=F(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=F(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let n=Te(r.content,t.content_index);if(n.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.reasoning_text.done":{let r=F(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new C(`missing content at index ${t.content_index}`);let n=Te(r.content,t.content_index);if(n.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${n.type}`);n.text=t.text}break}case"response.reasoning_summary_part.added":{let r=F(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=F(e,t.output_index);r.type==="reasoning"&&(Te(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=F(e,t.output_index);if(r.type==="reasoning"){let n=Te(r.summary,t.summary_index);n.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=F(e,t.output_index);if(r.type==="reasoning"){let n=Te(r.summary,t.summary_index);n.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=F(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=F(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=F(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=F(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=F(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=F(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=F(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=F(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=F(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=F(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=F(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=F(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=F(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=F(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=F(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=F(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=F(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=F(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=F(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=F(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=F(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=Wu(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":break;default:yg(t)}return e}function Wu(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&Ie(e),e}function F(t,e){let r=t.output[e];if(!r)throw new C(`missing output at index ${e}`);return r}function Te(t,e){let r=t[e];if(!r)throw new C(`missing content at index ${e}`);return r}function yg(t){throw new C(`Unhandled response stream event: ${JSON.stringify(t)}`)}var Ot,Bs,mr,Ks,Ga,Ja,Za,Ws=class t extends wt{constructor(e){super(),Ot.add(this),Bs.set(this,void 0),mr.set(this,void 0),Ks.set(this,void 0),P(this,Bs,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}async _createOrRetrieveResponse(e,r,n){this._listenForAbort(n?.signal),_(this,Ot,"m",Ga).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let i of o)_(this,Ot,"m",Ja).call(this,i,s);if(o.controller.signal?.aborted)throw new H;return _(this,Ot,"m",Za).call(this)}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),_(this,Ot,"m",Ga).call(this),this._connected();let n=_e.fromReadableStream(e,this.controller);for await(let o of n)_(this,Ot,"m",Ja).call(this,o,null);if(n.controller.signal?.aborted)throw new H;return _(this,Ot,"m",Za).call(this)}[(Bs=new WeakMap,mr=new WeakMap,Ks=new WeakMap,Ot=new WeakSet,Ga=function(){this.ended||P(this,mr,void 0,"f")},Ja=function(r,n){if(this.ended)return;let o=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},s=Hu(r,_(this,mr,"f"));switch(P(this,mr,s,"f"),o("event",r),r.type){case"response.output_text.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new C(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new C(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:o(r.type,r);break}},Za=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,mr,"f");if(!r)throw new C("request ended without sending any events");P(this,mr,void 0,"f");let n=_g(r,_(this,Bs,"f"));return P(this,Ks,n,"f"),n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=_(this,Ks,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function _g(t,e){return Bu(t,e)}var zn=class extends y{list(e,r={},n){return this._client.getAPIList(m`/responses/${e}/input_items`,$,{query:r,...n,__security:{bearerAuth:!0}})}};var Un=class extends y{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Ke=class extends y{constructor(){super(...arguments),this.inputItems=new zn(this._client),this.inputTokens=new Un(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Ie(n),n))}retrieve(e,r={},n){return this._client.get(m`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&Ie(o),o))}delete(e,r){return this._client.delete(m`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Va(n,e))}stream(e,r){return Ws.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(m`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};Ke.InputItems=zn;Ke.InputTokens=Un;var qn=class extends y{retrieve(e,r){return this._client.get(m`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Bn=class extends y{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(m`/skills/${o}/versions/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var fr=class extends y{constructor(){super(...arguments),this.content=new Bn(this._client)}create(e,r={},n){return this._client.post(m`/skills/${e}/versions`,yt({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(m`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/skills/${e}/versions`,$,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(m`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};fr.Content=Bn;var et=class extends y{constructor(){super(...arguments),this.content=new qn(this._client),this.versions=new fr(this._client)}create(e={},r){return this._client.post("/skills",yt({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};et.Content=qn;et.Versions=fr;var Kn=class extends y{create(e,r,n){return this._client.post(m`/uploads/${e}/parts`,me({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Mt=class extends y{constructor(){super(...arguments),this.parts=new Kn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(m`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(m`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};Mt.Parts=Kn;var Vu=async t=>{let e=await Promise.allSettled(t),r=e.filter(o=>o.status==="rejected");if(r.length){for(let o of r)console.error(o.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let o of e)o.status==="fulfilled"&&n.push(o.value);return n};var Wn=class extends y{create(e,r,n){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(m`/vector_stores/${o}/file_batches/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(m`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(m`/vector_stores/${o}/file_batches/${e}/files`,$,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await ze(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,i=Math.min(s,r.length),a=this._client,c=r.values(),l=[...n];async function u(f){for(let w of f){let x=await a.files.create({file:w,purpose:"assistants"},o);l.push(x.id)}}let p=Array(i).fill(c).map(u);return await Vu(p),await this.createAndPoll(e,{file_ids:l})}};var Hn=class extends y{create(e,r,n){return this._client.post(m`/vector_stores/${e}/files`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(m`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(m`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(m`/vector_stores/${e}/files`,$,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(m`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),i=s.data;switch(i.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await ze(a);break;case"failed":case"completed":return i}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(m`/vector_stores/${o}/files/${e}/content`,pe,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var tt=class extends y{constructor(){super(...arguments),this.files=new Hn(this._client),this.fileBatches=new Wn(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(m`/vector_stores/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",$,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(m`/vector_stores/${e}/search`,pe,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};tt.Files=Hn;tt.FileBatches=Wn;var hr=class extends y{create(e,r){return this._client.post("/videos",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",j,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(m`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(m`/videos/${e}/content`,{query:r,...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",me({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(m`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(m`/videos/${e}/remix`,yt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Vn,Gu,Hs,gr=class extends y{constructor(){super(...arguments),Vn.add(this)}async unwrap(e,r,n=this._client.webhookSecret,o=300){return await this.verifySignature(e,r,n,o),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");_(this,Vn,"m",Gu).call(this,n);let s=T([r]).values,i=_(this,Vn,"m",Hs).call(this,s,"webhook-signature"),a=_(this,Vn,"m",Hs).call(this,s,"webhook-timestamp"),c=_(this,Vn,"m",Hs).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new je("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>o)throw new je("Webhook timestamp is too old");if(l>u+o)throw new je("Webhook timestamp is too new");let p=i.split(" ").map(g=>g.startsWith("v1,")?g.substring(3):g),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),w=c?`${c}.${a}.${e}`:`${a}.${e}`,x=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of p)try{let b=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",x,b,new TextEncoder().encode(w)))return}catch{continue}throw new je("The given webhook signature does not match the expected signature")}};Vn=new WeakSet,Gu=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Hs=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Zu=Symbol.for("openai.node.providerDefinitions.v1"),Qu=globalThis,Yu=Qu[Zu],Xu=Yu??new WeakMap;Yu||Object.defineProperty(Qu,Zu,{value:Xu});function ed(t){let e=Xu.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Qa,Ya,Uo,td,Cg="workload-identity-auth",M=class{constructor(e={}){Qa.add(this),Uo.set(this,void 0),this.completions=new rr(this),this.chat=new bt(this),this.embeddings=new or(this),this.files=new ir(this),this.images=new ur(this),this.audio=new qe(this),this.moderations=new pr(this),this.models=new dr(this),this.fineTuning=new Me(this),this.graders=new Pt(this),this.vectorStores=new tt(this),this.webhooks=new gr(this),this.beta=new ve(this),this.batches=new Qt(this),this.uploads=new Mt(this),this.admin=new xt(this),this.responses=new Ke(this),this.realtime=new Xe(this),this.conversations=new kt(this),this.evals=new Et(this),this.containers=new Ct(this),this.skills=new et(this),this.videos=new hr(this);let r=e.provider;if(r){let g=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(b=>e[b]!=null);if(g.length)throw new C(`The \`provider\` option cannot be used with ${g.map(b=>`\`${b}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=r?null:Pe("OPENAI_BASE_URL"),apiKey:o=r?null:Pe("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:Pe("OPENAI_ADMIN_KEY")??null,organization:i=r?null:Pe("OPENAI_ORG_ID")??null,project:a=r?null:Pe("OPENAI_PROJECT_ID")??null,webhookSecret:c=Pe("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...u}=e,p=r?ed(r):void 0,f={apiKey:o,adminAPIKey:s,organization:i,project:a,webhookSecret:c,workloadIdentity:l,provider:r,...u,baseURL:p?.baseURL??(n||"https://api.openai.com/v1")};if(o&&l)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!o&&!s&&!l)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Qc())throw new C(`It looks like you're running in a browser-like environment.
59
-
60
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
61
- If you understand the risks and have appropriate mitigations in place,
62
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
63
-
64
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
65
-
66
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
67
- `);this.baseURL=f.baseURL,this.timeout=f.timeout??Ya.DEFAULT_TIMEOUT,this.logger=f.logger??console;let w="warn";this.logLevel=w,this.logLevel=wa(f.logLevel,"ClientOptions.logLevel",this)??wa(Pe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??w,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??bs(),P(this,Uo,eu,"f");let x=r?void 0:Pe("OPENAI_CUSTOM_HEADERS");if(x){let g={};for(let b of x.split(`
68
- `)){let S=b.indexOf(":");S>=0&&(g[b.substring(0,S).trim()]=b.substring(S+1).trim())}f.defaultHeaders=T([g,f.defaultHeaders])}this._options=f,this._provider=p,l&&(this._workloadIdentityAuth=new Cs(l,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=s,this.organization=i,this.project=a,this.webhookSecret=c}withOptions(e){let r=this._options.provider,n=e.provider??r,o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,n!==r&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return T([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return T([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return T([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return T([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return cu(e)}getUserAgent(){return`${this.constructor.name}/JS ${gt}`}defaultIdempotencyKey(){return`stainless-node-retry-${zt()}`}makeStatusError(e,r,n,o){return G.generate(e,r,n,o)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof C?n:new C(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,Qa,"m",td).call(this)&&n||this.baseURL,s=Kc(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!ca(i)||!ca(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new Bt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:i,url:a,timeout:c}=await this.buildRequest(o,{retryCount:s-r}),l=o.__metadata?.hasStreamingBody===!0;await this.prepareRequest(i,{url:a,options:o}),await this._provider?.prepareRequest?.(i,{url:a,options:o});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(X(this).debug(`[${u}] sending request`,Ge({retryOfRequestLogID:n,method:o.method,url:a,options:o,headers:i.headers})),o.signal?.aborted)throw new H;let w=o.__security??{bearerAuth:!0},x=new AbortController,g=await this.fetchWithAuth(a,i,c,x,w).catch(go),b=Date.now();if(g instanceof globalThis.Error){let I=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new H;let E=ho(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(r&&!l)return X(this).info(`[${u}] connection ${E?"timed out":"failed"} - ${I}`),X(this).debug(`[${u}] connection ${E?"timed out":"failed"} (${I})`,Ge({retryOfRequestLogID:n,url:a,durationMs:b-f,message:g.message})),this.retryRequest(o,r,n??u);let D=l?"error; streaming body cannot be retried":"error; no more retries left";throw X(this).info(`[${u}] connection ${E?"timed out":"failed"} - ${D}`),X(this).debug(`[${u}] connection ${E?"timed out":"failed"} (${D})`,Ge({retryOfRequestLogID:n,url:a,durationMs:b-f,message:g.message})),g instanceof Ut||g instanceof yo?g:E?new Fe:new ht({message:kg(g),cause:g})}let S=[...g.headers.entries()].filter(([I])=>I==="x-request-id").map(([I,E])=>", "+I+": "+JSON.stringify(E)).join(""),h=`[${u}${p}${S}] ${i.method} ${a} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${b-f}ms`;if(!g.ok){if(g.status===401&&this._workloadIdentityAuth&&w.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await da(g.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??u);let I=await this.shouldRetry(g);if(r&&I&&!l){let B=`retrying, ${r} attempts remaining`;return await da(g.body),X(this).info(`${h} - ${B}`),X(this).debug(`[${u}] response error (${B})`,Ge({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:b-f})),this.retryRequest(o,r,n??u,g.headers)}let E=I?l?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";X(this).info(`${h} - ${E}`);let D=await g.text().catch(B=>go(B).message),k=Vc(D),q=k?void 0:D;throw X(this).debug(`[${u}] response error (${E})`,Ge({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:q,durationMs:Date.now()-f})),this.makeStatusError(g.status,k,q,g.headers)}return X(this).info(h),X(this).debug(`[${u}] response start`,Ge({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:b-f})),{response:g,options:o,controller:x,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Io(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let a=r.headers,c=a.get("Authorization");if(!c||c===`Bearer ${Cg}`){let l=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:i,...a}=r||{},c=this._makeAbort(o);s&&s.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,p={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(p.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,i=o?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(s=c)}let a=o?.get("retry-after");if(a&&!s){let c=parseFloat(a);Number.isNaN(c)?s=Date.parse(a)-Date.now():s=c*1e3}if(s===void 0){let c=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await ze(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,i=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:i,defaultBaseURL:a}=n,c=this.buildURL(s,i,a);"timeout"in n&&Hc("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u,isStreamingBody:p}=this.buildBody({options:n});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let i=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Yc(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:n}=e;if(!r)return r===void 0&&"body"in e?{..._(this,Uo,"f").call(this,{body:r,headers:T([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=T([n]),s=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,i=!s&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&o.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||s?{bodyHeaders:void 0,body:r,isStreamingBody:!i}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:wo(r),isStreamingBody:!0}:typeof r=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{..._(this,Uo,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};Ya=M,Uo=new WeakMap,Qa=new WeakSet,td=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};M.OpenAI=Ya;M.DEFAULT_TIMEOUT=6e5;M.OpenAIError=C;M.APIError=G;M.APIConnectionError=ht;M.APIConnectionTimeoutError=Fe;M.APIUserAbortError=H;M.NotFoundError=Rr;M.ConflictError=$r;M.RateLimitError=Lr;M.BadRequestError=Pr;M.AuthenticationError=Or;M.InternalServerError=Dr;M.PermissionDeniedError=Mr;M.UnprocessableEntityError=Nr;M.InvalidWebhookSignatureError=je;M.toFile=To;M.toStreamingFile=Es;M.Completions=rr;M.Chat=bt;M.Embeddings=or;M.Files=ir;M.Images=ur;M.Audio=qe;M.Moderations=pr;M.Models=dr;M.FineTuning=Me;M.Graders=Pt;M.VectorStores=tt;M.Webhooks=gr;M.Beta=ve;M.Batches=Qt;M.Uploads=Mt;M.Admin=xt;M.Responses=Ke;M.Realtime=Xe;M.Conversations=kt;M.Evals=Et;M.Containers=Ct;M.Skills=et;M.Videos=hr;function kg(t){if(Eg(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function Eg(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}function Pg(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function Se(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Fe.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===H.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Pg(t)?e=lc.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=fo(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=fo(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=fo(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=fo(t,"MODEL_NOT_FOUND"):e=t,e}var Re=t=>t();function rt(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Og(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Vs(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Mg="LC_AUTOGENERATED";function yr(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),Mg)}function nt(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!ss.isInstance(t))throw new Error("Invalid generic chat message");return Og(t);default:throw new Error(`Unknown message type: ${e}`)}}function rd(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function ot(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((n||i)&&o&&e)return`${o}/${e}`;if((n||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function el(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function nd(t){let e=Re(()=>{if(el(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&el(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,n])=>typeof n=="string").map(([n,o])=>[n,o]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function od(){let t=ac();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function st(t,e=!1,r="1.0.0"){let n=nd(t),o=od(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function sd(t,e){let r;return Cr(t)?r=Hi(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Rg(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function id(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(ad(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
69
- `)}function ad(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${Gs(o,e)},`):r.push(`${n}?: ${Gs(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
70
- `)}function Gs(t,e){if(Rg(t))return t.anyOf.map(r=>Gs(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",ad(t,e+2),"}"].join(`
71
- `);case"array":return t.items?`${Gs(t.items,e)}[]`:"any[]";default:return""}}function Js(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function Gn(t){return"type"in t&&t.type!=="function"}function ld(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function cd(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function _r(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Zs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function ud(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function dd(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function pd(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function md(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function fd(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function hd(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var yd=Symbol("Let zodToJsonSchema decide on which parser to use"),gd={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},_d=t=>typeof t=="string"?{...gd,basePath:["#"],definitions:{},name:t}:{...gd,basePath:["#"],definitions:{},...t};var qo=t=>"_def"in t?t._def:t;function wd(t){if(!t)return!0;for(let e in t)return!1;return!0}var bd=t=>{let e=_d(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[qo(o),{def:qo(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function tl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function z(t,e,r,n,o){t[e]=r,tl(t,e,n,o)}function Ad(){return{}}function xd(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=R(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&z(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&z(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(z(r,"minItems",t.exactLength.value,t.exactLength.message,e),z(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Id(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?z(r,"minimum",n.value,n.message,e):z(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),z(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?z(r,"maximum",n.value,n.message,e):z(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),z(r,"maximum",n.value,n.message,e));break;case"multipleOf":z(r,"multipleOf",n.value,n.message,e);break}return r}function vd(){return{type:"boolean"}}function Td(t,e,r){return R(t.type._def,e,r)}var Sd=(t,e,r)=>R(t.innerType._def,e,r);function rl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>rl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return $g(t,e)}}var $g=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":z(r,"minimum",n.value,n.message,e);break;case"max":z(r,"maximum",n.value,n.message,e);break}return r};function Cd(t,e,r){return{...R(t.innerType._def,e,r),default:t.defaultValue()}}function kd(t,e,r){return e.effectStrategy==="input"?R(t.schema._def,e,r):{}}function Ed(t){return{type:"string",enum:[...t.values]}}var Ng=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Pd(t,e){let r=[R(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),R(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Ng(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Od(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var nl,wr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(nl===void 0&&(nl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nl),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Qs(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Lg(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":z(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":z(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":$e(r,"email",o.message,e);break;case"format:idn-email":$e(r,"idn-email",o.message,e);break;case"pattern:zod":Ne(r,wr.email,o.message,e);break}break;case"url":$e(r,"uri",o.message,e);break;case"uuid":$e(r,"uuid",o.message,e);break;case"regex":Ne(r,o.regex,o.message,e);break;case"cuid":Ne(r,wr.cuid,o.message,e);break;case"cuid2":Ne(r,wr.cuid2,o.message,e);break;case"startsWith":Ne(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":Ne(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":$e(r,"date-time",o.message,e);break;case"date":$e(r,"date",o.message,e);break;case"time":$e(r,"time",o.message,e);break;case"duration":$e(r,"duration",o.message,e);break;case"length":z(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),z(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{Ne(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&$e(r,"ipv4",o.message,e),o.version!=="v4"&&$e(r,"ipv6",o.message,e);break}case"emoji":Ne(r,wr.emoji,o.message,e);break;case"ulid":{Ne(r,wr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{$e(r,"binary",o.message,e);break}case"contentEncoding:base64":{z(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Ne(r,wr.base64,o.message,e);break}}break}case"nanoid":Ne(r,wr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Lg=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),$e=(t,e,r,n)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):z(t,"format",e,r,n)},Ne=(t,e,r,n)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Md(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):z(t,"pattern",Md(e,n),r,n)},Md=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",i=!1,a=!1,c=!1;for(let l=0;l<o.length;l++){if(i){s+=o[l],i=!1;continue}if(n.i){if(a){if(o[l].match(/[a-z]/)){c?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),c=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],c=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
72
- ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
73
- ]))`;continue}}if(n.s&&o[l]==="."){s+=a?`${o[l]}\r
74
- `:`[${o[l]}\r
75
- ]`;continue}s+=o[l],o[l]==="\\"?i=!0:a&&o[l]==="]"?a=!1:!a&&o[l]==="["&&(a=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Ys(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Qs(t.keyType._def,e)).reduce((o,[s,i])=>s==="type"?o:{...o,[s]:i},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function Rd(t,e){if(e.mapStrategy==="record")return Ys(t,e);let r=R(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function $d(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Nd(){return{not:{}}}function Ld(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Bo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Fd(t,e){if(e.target==="openApi3")return Dd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Bo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Bo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Dd(t,e)}var Dd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>R(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function jd(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Bo[t.innerType._def.typeName],nullable:!0}:{type:[Bo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=R(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function zd(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",tl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?z(r,"minimum",n.value,n.message,e):z(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),z(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?z(r,"maximum",n.value,n.message,e):z(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),z(r,"maximum",n.value,n.message,e));break;case"multipleOf":z(r,"multipleOf",n.value,n.message,e);break}return r}function Dg(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":R(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ud(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let i=[...e.currentPath,"properties",o],a=R(s._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:a},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:Dg(t,e)};return r.required.length||delete r.required,r}var qd=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return R(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=R(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Bd=(t,e,r)=>{if(e.pipeStrategy==="input")return R(t.in._def,e,r);if(e.pipeStrategy==="output")return R(t.out._def,e,r);let n=R(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=R(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Kd(t,e,r){return R(t.type._def,e,r)}function Wd(t,e){let n={type:"array",uniqueItems:!0,items:R(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&z(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&z(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Hd(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:R(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>R(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Vd(){return{not:{}}}function Gd(){return{}}var Jd=(t,e,r)=>R(t.innerType._def,e,r);function R(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==yd)return s}if(n&&!r){let s=Fg(n,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let s=Ug(t,t.typeName,e,r);return s&&qg(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var Fg=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((n,o)=>o===0?n:jg(n)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:zg(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Zd="_x_",jg=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Zd))return t;let e=Zd;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},zg=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},Ug=(t,e,r,n)=>{switch(e){case N.ZodString:return Qs(t,r);case N.ZodNumber:return zd(t,r);case N.ZodObject:return Ud(t,r);case N.ZodBigInt:return Id(t,r);case N.ZodBoolean:return vd();case N.ZodDate:return rl(t,r);case N.ZodUndefined:return Vd();case N.ZodNull:return Ld(r);case N.ZodArray:return xd(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return Fd(t,r);case N.ZodIntersection:return Pd(t,r);case N.ZodTuple:return Hd(t,r);case N.ZodRecord:return Ys(t,r);case N.ZodLiteral:return Od(t,r);case N.ZodEnum:return Ed(t);case N.ZodNativeEnum:return $d(t);case N.ZodNullable:return jd(t,r,n);case N.ZodOptional:return qd(t,r,n);case N.ZodMap:return Rd(t,r);case N.ZodSet:return Wd(t,r);case N.ZodLazy:return R(t.getter()._def,r,n);case N.ZodPromise:return Kd(t,r,n);case N.ZodNaN:case N.ZodNever:return Nd();case N.ZodEffects:return kd(t,r,n);case N.ZodAny:return Ad();case N.ZodUnknown:return Gd();case N.ZodDefault:return Cd(t,r,n);case N.ZodBranded:return Td(t,r,n);case N.ZodReadonly:return Jd(t,r,n);case N.ZodCatch:return Sd(t,r,n);case N.ZodPipeline:return Bd(t,r,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},qg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ol=(t,e)=>{let r=bd(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=R(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let i=(()=>{if(wd(r.definitions))return;let c={},l=new Set;for(let u=0;u<500;u++){let p=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(p.length===0)break;for(let[f,w]of p)c[f]=R(qo(w),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return c})(),a=n===void 0?i?{...o,[r.definitionPath]:i}:o:r.nameStrategy==="duplicate-ref"?{...o,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function Qd(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return it(e,[],e)}function sl(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(sl(e))return!0;for(let e of t.anyOf??[])if(sl(e))return!0;return!1}function it(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!br(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(br(n))for(let[f,w]of Object.entries(n))it(w,[...e,"$defs",f],r);let o=t.definitions;if(br(o))for(let[f,w]of Object.entries(o))it(w,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(br(a)){for(let[f,w]of Object.entries(a))if(!sl(w)&&!i.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([f,w])=>[f,it(w,[...e,"properties",f],r)]))}let c=t.items;br(c)&&(t.items=it(c,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,w)=>it(f,[...e,"anyOf",String(w)],r)));let u=t.allOf;if(Array.isArray(u))if(u.length===1){let f=it(u[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=u.map((f,w)=>it(f,[...e,"allOf",String(w)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Kg(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let f=Bg(r,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!br(f))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,it(t,e,r)}return t}function Bg(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!br(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function br(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kg(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function Wg(t,e){return ol(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Hg(t){return Qd(hc(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function Vg(t){return"_zod"in t}function Gg(t,e){let r=JSON.parse(e),n=t.parse;return typeof n=="function"?n.call(t,r):Tc(t,r)}function Yd(t,e,r){let n=t;return vu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Vg(n)?Hg(n):Wg(n,{name:e})}},o=>Gg(t,o))}var Xd=["jsonSchema","functionCalling","jsonMode"];function ep(t,e){if(typeof e<"u"&&!Xd.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Xd.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Jg(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function tp(t,e,r){if(gc(t))return Yd(t,e,r);if(ls(t))return Jg({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Ft(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>mc(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function rp(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(n=>typeof n?.image_url?.url=="string").map(n=>({type:"image",url:n.image_url.url}));return[{type:"text",text:t},...r]}return t}var np={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function Jn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Ar=class extends ps{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??ke("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ke("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.5")}_getReasoningParams(t){if(!rt(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Dt(t.json_schema.schema)?tp(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=ot({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=st(r.defaultHeaders),this.client=new M(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return _r(t)?hd(t.metadata.customTool):us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:sd(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(n=>{if(Gn(n)||_r(n))return n;if(ld(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return Cr(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[i,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(nt(s))]),c=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=i+r+a+c,u=s;if(u._getType()==="function"&&(l-=2),u.additional_kwargs?.function_call&&(l+=3),u?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(u.additional_kwargs.function_call?.name)),u.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(u.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(u.additional_kwargs.function_call)),l+=await this.getNumTokens(u.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=id(e);n+=await this.getNumTokens(o),n+=9}return e&&t.find(o=>o._getType()==="system")&&(n-=4),r==="none"?n+=1:typeof r=="object"&&(n+=await this.getNumTokens(r.name)+4),n}async moderateContent(t,e){let r=this._getClientOptions(e?.options),n={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(n,r)}catch(o){throw Se(o)}})}get profile(){return np[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=ep(this.model,e?.method);if(a==="jsonMode"){n=Ki(o);let c=Ft(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...c}}})}else if(a==="jsonSchema"){let c=Ft(o),l={name:s??"extract",description:qi(c),schema:Dt(o)?o:c,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...c}}}),Dt(o)||as(o)){let u=Ki(o);n=mt.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:u.invoke(p.content))}else n=new wc}else{let c=s??"extract",l=Ft(o),u;Dt(o)||as(o)?u={name:c,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(u=o,c=o.name):(c=o.title??c,u={name:c,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:u}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=bc(o,c)}return Ac(r,n,i)}};var Xs={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=ji({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=Fi(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:n.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Fi(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=ji({dataUrl:t.url}),r=yr(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=yr(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},il=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],i=[];for(let l of n??[])try{s.push(ds(l,{returnId:!0}))}catch(u){i.push(Sr(l,u.message))}let a={function_call:t.function_call,tool_calls:n};r!==void 0&&(a.__raw_response=e),o!==void 0&&(a.reasoning_content=o);let c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new U({content:rp(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new ss(t.content||"",t.role??"unknown")}},al=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ui({content:s,response_metadata:a});if(o==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)c.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new pt({content:s,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return o==="system"?new is({content:s,response_metadata:a}):o==="developer"?new is({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new uc({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new zi({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new cc({content:s,role:o,response_metadata:a})},op=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=dc(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=yr(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},sp=({message:t,model:e})=>{let r=nt(t);if(r==="system"&&rt(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(s=>s.type==="text")};return U.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(Bi):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&W.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let i=op(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},Zn=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return sp({message:r});let n=nt(r);n==="system"&&rt(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>ns(i)?os(i,Xs):typeof i=="object"&&i!==null&&"type"in i&&(i.type==="tool_use"||i.type==="tool_call"||i.type==="reasoning"||i.type==="reasoning_content"||i.type==="thinking")?[]:i),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),U.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Bi):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),W.isInstance(r)&&r.tool_call_id!=null&&(s.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[s,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:s});var ei=class extends Ar{constructor(t,e){super(Jn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:Js(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...n,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(o.reasoning_effort=s.effort),rt(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,r){e.signal?.throwIfAborted();let n={},o=this.invocationParams(e),s=Zn({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let w of i){w.message.response_metadata={...w.generationInfo,...w.message.response_metadata};let x=w.generationInfo?.completion??0;a[x]===void 0?a[x]=w:a[x]=a[x].concat(w)}let c=Object.entries(a).sort(([w],[x])=>parseInt(w,10)-parseInt(x,10)).map(([w,x])=>x),{functions:l,function_call:u}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,u),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=p,n.output_tokens=f,n.total_tokens=p+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let i=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:l,prompt_tokens_details:u,completion_tokens_details:p}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),c&&(n.input_tokens=(n.input_tokens??0)+c),l&&(n.total_tokens=(n.total_tokens??0)+l),(u?.audio_tokens!==null||u?.cached_tokens!==null)&&(n.input_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.cached_tokens!==null&&{cache_read:u?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let f=[];for(let w of i?.choices??[]){let x={text:w.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(w.message??{role:"assistant"},i)};x.generationInfo={...w.finish_reason?{finish_reason:w.finish_reason}:{},...w.logprobs?{logprobs:w.logprobs}:{}},dt(x.message)&&(x.message.usage_metadata=n),x.message=new U(Object.fromEntries(Object.entries(x.message).filter(([g])=>!g.startsWith("lc_")))),f.push(x)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=Zn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),i=this.streamUsage??e.streamUsage;yield*ms(async function*(c,l){for await(let u of c){if(l?.aborted)return;yield u}}(s,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=Zn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,i=await this.completionWithRetry(o,e),a;for await(let c of i){if(e.signal?.aborted)return;let l=c?.choices?.[0];if(c.usage&&(a=c.usage),!l)continue;let{delta:u}=l;if(!u)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(u,c,s);s=u.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let w={...f};l.finish_reason!=null&&(w.finish_reason=l.finish_reason,w.system_fingerprint=c.system_fingerprint,w.model_name=c.model,w.service_tier=c.service_tier),this.logprobs&&(w.logprobs=l.logprobs);let x=new co({message:p,text:p.content,generationInfo:w});yield x,await r?.handleLLMNewToken(x.text??"",f,void 0,void 0,void 0,{chunk:x})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},l={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},u=new co({message:new pt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield u,await r?.handleLLMNewToken(u.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:u})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Se(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return al({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return il({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var ti="__openai_function_call_ids__",ri="__openai_custom_tool_call_ids__";function pp(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Qg(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var Ko=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},ni=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(pp),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(ds(c,{returnId:!0}))}catch(l){let u;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(u=l.message),n.push(Sr(c,u))}i[ti]??={},a.id&&(i[ti][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(l=>l.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=ud(a);c?(r.push(c),i[ri]??={},a.id&&a.call_id&&(i[ri][a.call_id]=a.id)):n.push(Sr(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=dd(a);c?r.push(c):n.push(Sr(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new U({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:Ko(t.usage),additional_kwargs:i,response_metadata:s})},mp=t=>{let e=(t.summary.length>1?t.summary.reduce((r,n)=>{let o=r[r.length-1];return o.index===n.index?o.text+=n.text:r.push(n),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([n])=>n!=="index")));return{...t,summary:e}},ll=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[pp(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[ti]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[ri]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let c=ni(t.response);if(n=Ko(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[l,u]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=c.response_metadata.output:s[l]=u)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,c,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:l}}}else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let c=t.item.summary?t.item.summary.map((u,p)=>({...u,index:p})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let l=t.item.summary?.map(u=>u.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new co({text:e.map(c=>c.text).join(""),message:new pt({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},fp=t=>{let e=U.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Re(()=>{try{let h=nt(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"assistant"}catch{return"assistant"}}),o=h=>n==="assistant"?{type:"output_text",text:h,annotations:[]}:{type:"input_text",text:h},s,i=new Set,a=new Set,c=new Map,l=new Map;function*u(){if(!s)return;let h=s.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield s),s=void 0}let p=(h,I)=>{s||(s={type:"message",role:n,content:[],...I?{phase:I}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[o(s.content),...h]:[...h]:s.content.push(...h)},f=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},w=h=>{let I=Re(()=>{let E=h.metadata?.detail;return E==="low"||E==="high"||E==="auto"?E:"auto"});if(h.fileId)return{type:"input_image",detail:I,file_id:h.fileId};if(h.url)return{type:"input_image",detail:I,image_url:h.url};if(h.data){let E=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_image",detail:I,image_url:`data:${h.mimeType??"image/png"};base64,${E}`}}},x=h=>{if(h.fileId){let I=Vs(h);return{type:"input_file",file_id:h.fileId,...I?{filename:I}:{}}}if(h.url){let I=Vs(h);return{...I?{filename:I}:{},type:"input_file",file_url:h.url}}if(h.data){let I=yr(h),E=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${E}`,filename:I}}},g=h=>{let I=Re(()=>{if(Array.isArray(h.summary)){let D=h.summary?.map(k=>k?.text).filter(k=>typeof k=="string")??[];if(D.length>0)return D}return h.reasoning?[h.reasoning]:[]}),E=I.length>0?I.map(D=>({type:"summary_text",text:D})):[{type:"summary_text",text:""}];return{type:"reasoning",...h.id?{id:h.id}:{},summary:E}},b=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:f(h.args)}),S=h=>{let I=f(h.output),E=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:I,...E?{status:E}:{}}};for(let h of t.contentBlocks)if(h.type==="text"){let I=Re(()=>{if("extras"in h&&typeof h.extras=="object"&&h.extras!==null&&"phase"in h.extras)return h.extras.phase});p([o(h.text)],I)}else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*u(),yield g(h);else if(h.type==="tool_call"){yield*u();let I=h.id??"";I&&(i.add(I),c.delete(I)),yield b(h)}else if(h.type==="tool_call_chunk"){if(h.id){let I=c.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),c.set(h.id,I)}}else if(h.type==="server_tool_call"){yield*u();let I=h.id??"";I&&(a.add(I),l.delete(I)),yield b(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){let I=l.get(h.id)??{name:h.name,args:[]};h.name&&(I.name=h.name),h.args&&I.args.push(h.args),l.set(h.id,I)}}else if(h.type==="server_tool_call_result")yield*u(),yield S(h);else if(h.type!=="audio")if(h.type==="file"){let I=x(h);I&&p([I])}else if(h.type==="image"){let I=w(h);I&&p([I])}else if(h.type==="video"){let I=x(h);I&&p([I])}else h.type==="text-plain"?h.text&&p([o(h.text)]):h.type==="non_standard"&&e&&(yield*u(),yield h.value)}yield*u();for(let[h,I]of c){if(!h||i.has(h))continue;let E=I.args.join("");!I.name&&!E||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:E})}for(let[h,I]of l){if(!h||a.has(h))continue;let E=I.args.join("");!I.name&&!E||(yield{type:"function_call",call_id:h,name:I.name??"",arguments:E})}}return Array.from(r())},Wo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return fp(n);let s=n.additional_kwargs,i=nt(n);if(i==="system"&&rt(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(f=>f.type==="input_image");if(l)return l;let u=a.content.find(f=>f.type==="computer_screenshot");if(u)return u;let p=a.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(g=>"type"in g))return o?.output;let a=[],c=s?.reasoning,l=!!c?.encrypted_content;if(c&&(!e||l)){let g=mp(c);a.push(g)}let{content:u}=n;if(s?.refusal&&(typeof u=="string"&&(u=[{type:"output_text",text:u,annotations:[]}]),u=[...u,{type:"refusal",refusal:s.refusal}]),typeof u=="string"||u.length>0){let g={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Re(()=>typeof u=="string"?u:u.flatMap(b=>{if(b.type==="text"){let S=b;return{type:"output_text",text:S.text,annotations:(S.annotations??[]).map(Qg)}}return b.type==="output_text"||b.type==="refusal"?b:[]})),phase:Re(()=>{if(Array.isArray(u))return u.find(b=>"phase"in b&&typeof b.phase=="string")?.phase})};a.push(g)}let p=s?.[ti],f=s?.[ri];U.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(g=>md(g,f)?{type:"custom_tool_call",id:"call_id"in g&&typeof g.call_id=="string"?g.call_id:f?.[g.id??""]??"",call_id:g.id??"",input:g.args.input,name:g.name}:pd(g)?{type:"computer_call",id:g.call_id,call_id:g.id??"",action:g.args.action}:{type:"function_call",name:g.name,arguments:JSON.stringify(g.args),call_id:g.id,...e?{}:{id:p?.[g.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(g=>({type:"function_call",name:g.function.name,call_id:g.id,arguments:g.function.arguments,...e?{}:{id:p?.[g.id]}})));let w=o?.output?.length?o?.output:s.tool_outputs,x=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(w!=null){let g=w?.filter(b=>x.includes(b.type));g.length>0&&a.push(...g)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],c=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),ns(l)){if(l.type==="file"){let u=Vs(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...u?{filename:u}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...u?{filename:u}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:yr(l)}}return os(l,Xs)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Re(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Re(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*cl(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,i=0,a=!1,c,l,u,p,f=new Set,w=(b,S)=>{let h=s.get(b);if(h!==void 0)return{index:h,isNew:!1};let I=i++;return s.set(b,I),o.set(I,{...S}),{index:I,isNew:!0}},x=function*(){a||(a=!0,yield{event:"message-start",id:c})},g=function*(b){if(f.has(b))return;let S=o.get(b);S&&(f.add(b),yield{event:"content-block-finish",index:b,content:xc(S)})};for await(let b of t){if(b.type==="response.created"){c=b.response.id,yield*x(),yield{event:"provider",provider:n,name:"response.created",payload:{model:b.response.model,id:b.response.id}};continue}if(b.type==="response.output_text.delta"){yield*x();let{index:S,isNew:h}=w(`text:${b.output_index}:${b.content_index}`,{type:"text",text:""});h&&(yield{event:"content-block-start",index:S,content:{type:"text",text:""}});let I=o.get(S);I.text=(I.text??"")+b.delta,yield{event:"content-block-delta",index:S,delta:{type:"text-delta",text:b.delta}};continue}if(b.type==="response.reasoning_summary_text.delta"){yield*x();let{index:S,isNew:h}=w(`reasoning:${b.output_index}:${b.summary_index}`,{type:"reasoning",reasoning:""});h&&(yield{event:"content-block-start",index:S,content:{type:"reasoning",reasoning:""}});let I=o.get(S);I.reasoning=(I.reasoning??"")+b.delta,yield{event:"content-block-delta",index:S,delta:{type:"reasoning-delta",reasoning:b.delta}};continue}if(b.type==="response.output_item.added"&&(b.item.type==="function_call"||b.item.type==="custom_tool_call")){yield*x();let S=`tool:${b.output_index}`,h=b.item.type==="custom_tool_call",I=b.item.type==="function_call"?b.item.arguments??"":b.item.input??"",{index:E,isNew:D}=w(S,{type:"tool_call_chunk",id:b.item.call_id,name:b.item.name,args:I,index:b.output_index,...h?{isCustomTool:!0}:{}});if(D&&(yield{event:"content-block-start",index:E,content:{type:"tool_call_chunk",id:b.item.call_id,name:b.item.name,args:I,index:b.output_index}}),I){let k=o.get(E);yield{event:"content-block-delta",index:E,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...k.id!=null?{id:k.id}:{},...k.name!=null?{name:k.name}:{},args:k.args}}}}continue}if(b.type==="response.function_call_arguments.delta"||b.type==="response.custom_tool_call_input.delta"){yield*x();let{index:S,isNew:h}=w(`tool:${b.output_index}`,{type:"tool_call_chunk",args:"",index:b.output_index,...b.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});h&&(yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",args:"",index:b.output_index}});let I=o.get(S);I.args=(I.args??"")+b.delta,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...I.id!=null?{id:I.id}:{},...I.name!=null?{name:I.name}:{},args:I.args}}};continue}if(b.type==="response.output_item.done"&&(b.item.type==="function_call"||b.item.type==="custom_tool_call")){yield*x();let S=`tool:${b.output_index}`,h=b.item.type==="function_call"?b.item.arguments??"":b.item.input??"",{index:I,isNew:E}=w(S,{type:"tool_call_chunk",id:b.item.call_id,name:b.item.name,args:h,index:b.output_index});if(E)yield{event:"content-block-start",index:I,content:{type:"tool_call_chunk",id:b.item.call_id,name:b.item.name,args:h,index:b.output_index}};else{let D=o.get(I);D.args=h,D.id=b.item.call_id,D.name=b.item.name}yield*g(I);continue}if(b.type==="response.completed"||b.type==="response.incomplete"){yield*x(),c=b.response.id,u=Yg(b.response.status,b.type),p={model_provider:n,id:b.response.id,model:b.response.model,status:b.response.status},r&&b.response.usage&&(l=Ko(b.response.usage),yield{event:"usage",usage:l});continue}b.type!=="response.image_generation_call.partial_image"&&(yield*x(),yield{event:"provider",provider:n,name:b.type,payload:b})}a||(yield{event:"message-start"});for(let[b]of o)f.has(b)||(yield*g(b));yield{event:"message-finish",reason:u,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function Yg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var oi=class extends Ar{constructor(t,e){super(Jn(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:cd(t?.tool_choice)?t?.tool_choice:(()=>{let o=Js(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let i of o)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},s=s?.concat(i)??i;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:Wo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:ni(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:Wo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*cl(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:Wo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of n){if(e.signal?.aborted)return;let s=ll(o);s!=null&&(yield s,await r?.handleLLMNewToken(s.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:s}))}}catch(o){throw Se(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw Se(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(Gn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(_r(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(us(n)){let o={};for(let[s,i]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=i);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Zs(n)&&r.push(fd(n));return r}};var si=class hp extends Ar{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let n=Jn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new oi(n),this.completions=n?.completions??new ei(n)}_useResponsesApi(e){let r=e?.tools?.some(Gn),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,o=e?.tools?.some(Zs)||e?.tools?.some(_r);return this.useResponsesApi||r||n||o||rd(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,n){return this._useResponsesApi(r)?this.responses._generate(e,r,n):this.completions._generate(e,r,n)}async*_streamChatModelEvents(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),n)}async*_streamResponseChunks(e,r,n){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),n)}withConfig(e){let r=new hp(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var ii=class extends yc{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??ke("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ke("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Wi(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let i={model:this.model,input:s};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let i=e[s],{data:a}=n[s];for(let c=0;c<i.length;c+=1)o.push(a[c].embedding)}return o}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=ot({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=st(n.defaultHeaders),this.client=new M(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw Se(r)}})}};var ry=v.object({type:v.literal("screenshot")}),ny=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),oy=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),sy=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),iy=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),ay=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),ly=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),cy=v.object({type:v.literal("type"),text:v.string()}),uy=v.object({type:v.literal("wait"),duration:v.number().optional()}),dy=v.union([ry,ny,oy,sy,iy,ay,ly,cy,uy]),s2=v.object({action:dy});var py=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),c2=v.union([py]);var m2=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var my=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),fy=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),hy=v.object({type:v.literal("delete_file"),path:v.string()}),y2=v.union([my,fy,hy]);var yp={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},dl={default:"text-embedding-ada-002"},ul=new Map,ai=null,wy=()=>{let t=gp.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},_p=async t=>{let e=wy();ul.size===0&&(ai||(ai=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>ul.set(o.name,o))}catch(n){throw ai=null,n}})()),await ai);let r=ul.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},by=async(t="default")=>await _p(yp[t]),wp=async(t="default")=>await _p(dl[t]),Yn=(t,e)=>e,bp=(t,e)=>({...t,...e}),Ap=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
76
-
77
- `);return o[o.length-1]?.trim()===r?t:`${t}
78
-
79
- ${r}`},xp=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Rt=()=>({agentExecutionContext:O({reducer:bp,default:xp}),outputMessage:O({reducer:Ap,default:()=>""}),summary:O({reducer:Yn,default:()=>""}),status:O({reducer:Yn})}),pl=()=>({...Rt(),sharedStatePatch:O({reducer:Yn})}),Ay=O.Root({agentExecutionContext:O({default:xp,reducer:bp}),currentIntent:O({default:()=>"none",reducer:Yn}),lastExecutedAgent:O({default:()=>"",reducer:Yn}),requiresFollowUp:O({default:()=>!0,reducer:Yn}),stepCount:O({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:O({default:()=>"",reducer:Ap})});var xy=t=>typeof t=="string"&&t.length>0?t:void 0,Iy=()=>Vl(),vy=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,Ty=t=>{let e=t?.configurable;return{conversationId:xy(e?.thread_id),abortSignal:t?.signal,requestId:Iy(),requestSource:vy(_y.applicationName)}},Ip=async({config:t})=>{let e=gp.getDefault(),r=(await yy.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:i,requestId:a,requestSource:c}=Ty(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",c)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),a.length>0&&l.set("X-Esri-Request-Id",a);let u=i&&o?.signal?AbortSignal.any([i,o.signal]):o?.signal??i;return await fetch(n,{...o,headers:l,signal:u})}},ml=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=yp[e],s=await by(e);return new si({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await Ip({config:n})}})},vp=async(t={})=>{let{tier:e="default",config:r}=t,n=dl[e],o=await wp(e);return new ii({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:await Ip({config:r})},batchSize:2048,maxConcurrency:10})},Sy=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(Sy);var Tp="0.1",Qn=1536,Sp="openai",Cp=dl.default,kp=`Name: {name}
80
- Title: {title}
81
- Description: {description}`,Ep=`Name: {name}
82
- Alias: {alias}
83
- Description: {description}`,Pp=v.object({schemaVersion:v.literal(Tp),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Sp),model:v.literal(Cp),dimensions:v.literal(Qn),templates:v.object({layer:v.string().default(kp),field:v.string().default(Ep)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Qn,{message:`Layer vector must be exactly ${Qn} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(Qn,{message:`Field vector must be exactly ${Qn} dimensions`})}))})).default([])});var Op=(t,e)=>{let r=Ic.fromTemplate(t);return vc.fromMessages([r,...e])},Cy=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=Op(e,o??[]),a=await ml({modelTier:r,temperature:n,config:s});return i.pipe(a)},li=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,config:i}=t,a=await(await Cy({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)},Ho=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i,config:a}=t,c=Op(e,o??[]),l=(await ml({modelTier:r,temperature:n,config:a})).withStructuredOutput(i);return await c.pipe(l).invoke(s??{},a)};var ky=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),zW=d.object({fields:d.array(ky)});var UW=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var Mp=async t=>{try{return await(await vp()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var $p=t=>Array.isArray(t)&&t.every(lo),Py=t=>typeof t=="object"&&t!=null&&"messages"in t&&$p(t.messages),Oy=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,at=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 lo(i)&&i.getType()==="tool"||Lt(i)?i:new W({status:"success",name:n.name,content:typeof i=="string"?i:JSON.stringify(i),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||rs(o))throw o;return new W({status:"error",content:`Error: ${o.message}
84
- Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(Oy(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if($p(t))s=t;else if(Py(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(dt(l)){a=l;break}}if(a==null||!dt(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(Lt))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Lt(s)?s.graph===Ve.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>ic(i))?o?o.goto.push(...s.goto):o=new Ve({graph:Ve.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var zH=O.Root({llmInputMessages:O({reducer:(t,e)=>uo([],e),default:()=>[]})});var Vo=(t,e)=>e??t,m_=O.Root({...pl(),intent:O({reducer:Vo}),vectorSearchLayerResults:O({reducer:Vo,default:()=>[]}),vectorSearchFieldResults:O({reducer:Vo}),navigationInternalState:O({reducer:Vo,default:()=>({toolCallMessage:void 0})})});async function f_(t,e){let r=xr.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=`${fl.assetsPath?.endsWith("/")?fl.assetsPath:`${fl.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await $y(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 Ny({url:s,width:24,height:24}),c=new Ry({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 h_=["mapView"];function We(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=h_.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function g_({address:t},e){let{mapView:r}=We(e);return await f_(t,r)}var y_=d.object({address:d.string().describe("The full address or place name to locate.")}),__=L(g_,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:y_});async function w_(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 b_({bookmarkName:t},e){let{mapView:r}=We(e);return await Promise.resolve(w_(t,r))}var A_=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),x_=L(b_,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:A_});async function I_(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 v_({layerId:t,where:e},r){let{mapView:n}=We(r);return await I_(t,e,n)}var T_=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),S_=L(v_,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:T_});async function C_(t){let e=new Ly({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 k_(t,e){let{mapView:r}=We(e);return await C_(r)}var E_=v.object({}),P_=L(k_,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:E_});async function O_(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 M_(t,e){let{mapView:r}=We(e);return await O_(r)}var R_=d.object({}),$_=L(M_,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:R_});async function N_(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 L_({layerId:t},e){let{mapView:r}=We(e);return await N_(t,r)}var D_=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),F_=L(L_,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:D_});async function j_(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function z_({scale:t},e){let{mapView:r}=We(e);return await j_(t,r)}var U_=d.object({scale:d.number().describe("The map scale of the view to go to.")}),q_=L(z_,{name:"goToScale",description:"Go to the specified view scale.",schema:U_});async function B_(t,e,r){let n={target:new Bp({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 K_({center:t,zoom:e,scale:r},n){let{mapView:o}=We(n);return await B_(t,o,{zoom:e,scale:r})}var W_=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.")}),H_=L(K_,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:W_});async function V_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function G_({zoom:t},e){let{mapView:r}=We(e);return await V_(t,r)}var J_=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Z_=L(G_,{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:J_}),zp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./O4VO5GNH.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./U5FCUMGO.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./6ND2JXTN.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("./A2LPB576.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 lt(t){let e=Object.entries(zp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
85
- Available prompts:
86
- ${Object.keys(zp).join(`
87
- `)}`);return await e[1]()}var to=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Q_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=Fy({basemapTheme:await Dp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=jy({basemapTheme:await Dp(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 Y_(t){return await Dy(t)}async function X_({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 Q_(c),u=await Y_(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 ew=["mapView"];function Le(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=ew.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function tw({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await X_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var rw=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)")}),nw=L(tw,{name:"chart",description:`Label: Charts
88
- Description: Show the values of two or more categories as a proportion of the total using a pie chart.
89
- Keywords: pie, chart, all categories, breakdown, proportion
90
- Example: Show the total number of homes built in each decade using a pie chart for each feature.
91
- Fields: This style requires 2-8 number fields.
92
-
93
- Label: Charts and Size
94
- Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
95
- Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
96
- Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
97
- Fields: This style requires 2-8 number fields.`,schema:rw});function ow(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,i=e[0],a;return s&&(a=vl({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:i,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:a}}async function sw(t){return await zy(t)}async function iw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme: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:"color-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=ow(c),u=await sw(l);return a.renderer=u.renderer,a.visible=!0,`Color-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function aw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await iw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var lw=d.object({layerId:d.string().describe("The id of the layer to apply the color-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),cw=L(aw,{name:"color-age",description:`Label: Age (color)
98
- Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
99
- Keywords: since, age, how old, how long
100
- Example: Show the age of each feature based on its reported date.
101
- Fields: This style requires at least one field with a date type.`,schema:lw});function uw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,i=e[1],a=e[0],c;return o&&(c=vl({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:a,normalizationField:i,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function dw(t){return await Uy(t)}async function pw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme: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:"color",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=uw(c),u=await dw(l);return a.renderer=u.renderer,a.visible=!0,`Color renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function mw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await pw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var fw=d.object({layerId:d.string().describe("The id of the layer to apply the color renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),hw=L(mw,{name:"color",description:`Label: Counts and Amounts (color)
102
- Description: Vary color along a continuous color ramp to represent numeric or ranked data.
103
- Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
104
- Example: Color each feature based on the population density.
105
- Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:fw});function gw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,i,a,c=e[0];return o&&(a=vl({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:c,normalizationField:i,theme:s,colorOptions:{colorScheme:a}}}async function yw(t){return await qy(t)}async function _w({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme: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:"color-size-univariate",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=gw(c),u=await yw(l);return a.renderer=u.renderer,a.visible=!0,`Color-size-univariate renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function ww({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await _w({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var bw=d.object({layerId:d.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:d.array(d.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Aw=L(ww,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
106
- Description: Vary symbol size and color based on the values of two numeric attributes.
107
- Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
108
- Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
109
- Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:bw});function xw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=Ky({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(i=>({field:i,label:r.fields.find(a=>a.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function Iw(t){return await By(t)}async function vw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"dot-density",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=xw(a),l=await Iw(c);return i.renderer=l.renderer,i.visible=!0,`Dot Density renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function Tw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await ye({type:"show-legend",data:{layerIds:[t]}},n),await vw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Sw=d.object({layerId:d.string().describe("The id of the layer to apply the dot density renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),Cw=L(Tw,{name:"dot-density",description:`Dot Density
110
- Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
111
- **Use cases:**
112
- - Population distribution visualization
113
- - Comparing multiple categories within areas
114
- - Showing spatial distribution patterns
115
- **Examples:**
116
- - Show the density of the population based on various race/ethnic groups
117
- - Visualize distribution of different crops across regions
118
- - Display demographic patterns within census tracts
119
- **Fields:** Requires 2-8 number fields.
120
- **Keywords:** density, how much, how many, total, number, amount`,schema:Sw});function kw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i=e[0];return o&&(s=Hy({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:i,heatmapScheme:s}}async function Ew(t){return await Wy(t)}async function Pw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"heatmap",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=kw(a),l=await Ew(c);return i.renderer=l.renderer,i.visible=!0,`Heatmap renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function Ow({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await ye({type:"show-legend",data:{layerIds:[t]}},n),await Pw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Mw=d.object({layerId:d.string().describe("The id of the layer to apply the heatmap renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),Rw=L(Ow,{name:"heatmap",description:`Label: Heat Map
121
- Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
122
- Keywords: density, heatmap, hot spots, pattern, cluster
123
- Example: Create a heatmap
124
- Fields: This typically requires zero or one field of type number.`,schema:Mw});function $w(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s&&(i=Gy({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(a=>({name:a})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:i}}async function Nw(t){return await Vy(t)}async function Lw({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?"predominance-size":"predominance",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=$w(c),u=await Nw(l);return a.renderer=u.renderer,a.visible=!0,`Predominance renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function Dw({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await Lw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Fw=d.object({layerId:d.string().describe("The id of the layer to apply the predominance renderer to"),fields:d.array(d.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),jw=L(Dw,{name:"predominance",description:`Label: Predominant category
125
- Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
126
- Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
127
- Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
128
- Fields: This style relies on 2-10 number fields.
129
-
130
- Label: Predominant category and Size
131
- Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
132
- Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
133
- Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
134
- Fields: This style relies on 2-10 number fields.`,schema:Fw});function zw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i={field:e[0]},a={field:e[1]};return o&&(s=Zy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:i,field2:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function Uw(t){return await Jy(t)}async function qw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"relationship",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=zw(a),l=await Uw(c);return i.renderer=l.renderer,i.visible=!0,`Relationship renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Bw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Le(n);return await ye({type:"show-legend",data:{layerIds:[t]}},n),await qw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Kw=d.object({layerId:d.string().describe("The id of the layer to apply the relationship renderer to"),fields:d.array(d.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),Ww=L(Bw,{name:"relationship",description:`Label: Relationship
135
- Description: Overlays two color ramps to represent the relationship between two numeric attributes.
136
- Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
137
- Example: Show the relationship between tree height and carbon storage
138
- Fields: This style requires two number fields.`,schema:Kw});function Hw(t){let{fields:e,layer:r,view:n,theme:o}=t,s=e[0];return{layer:r,view:n,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Vw(t){return await Qy(t)}async function Gw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme: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:"size-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=Hw(c),u=await Vw(l);return a.renderer=u.renderer,a.visible=!0,`Size-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Jw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await Gw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Zw=d.object({layerId:d.string().describe("The id of the layer to apply the size-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Qw=L(Jw,{name:"size-age",description:`Label: Age (size)
139
- Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
140
- Keywords: since, age, how old, how long
141
- Example: Change the size of features so older features are larger than new features.
142
- Fields: This style requires at least one field with a date type.`,schema:Zw});function Yw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],i=e[0];return{layer:r,view:n,field:i,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Xw(t){return await Yy(t)}async function eb({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme: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:"size",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=Yw(c),u=await Xw(l);return a.renderer=u.renderer,a.visible=!0,`Size renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function tb({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await eb({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var rb=d.object({layerId:d.string().describe("The id of the layer to apply the size renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),nb=L(tb,{name:"size",description:`Label: Counts and Amounts (size)
143
- Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
144
- Keywords: graduated size, proportional size, how much, total, number, amount, size
145
- Example: Vary the size of each point based on the total population.
146
- Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.
147
-
148
- Label: Continuous Timeline (size)
149
- Description: Vary symbol sizes along a continuous ramp to represent dates.
150
- Keywords: graduated size, proportional size, classed size, how much, total, number, when
151
- Example: Vary the size of each feature based on the date a ticket was completed.
152
- Fields: This style requires a single field with a date type.`,schema:rb});function ob(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],i=e[1],a=e[2],c;return o&&(c=e_({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:i,field3:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function sb(t){return await Xy(t)}async function ib({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme: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:"type",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=ob(c),u=await sb(l);return a.renderer=u.renderer,a.visible=!0,`Type renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function ab({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Le(o);return await ye({type:"show-legend",data:{layerIds:[t]}},o),await ib({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var lb=d.object({layerId:d.string().describe("The id of the layer to apply the type renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),cb=L(ab,{name:"type",description:`Label: Types (unique symbols)
153
- Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
154
- Keywords: categorical, category, type, unique, discrete, point of interest, region, group
155
- Example: Color each feature based on the region it belongs to
156
- Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:lb}),ub=O.Root({...Rt(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),selectedLayerId:O()}),db=O.Root({...Rt(),vectorSearchLayerIds:O(),vectorSearchFieldResults:O(),layerFieldInfo:O(),queryResponse:O(),dataExplorationMessages:O({reducer:uo,default:()=>[]})}),pb=["mapView"];function $t(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=pb.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var mb=t=>{let e=t.map?.allLayers.filter(n=>n.type==="feature"),r=0;return e?.forEach(n=>{let o=n;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},fb=async(t,e)=>{let{mapView:r}=$t(e);return mb(r)},ZV=L(fb,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:d.object({})}),hb=async t=>{t.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let n=r;n.featureEffect&&(n.featureEffect=null)});let e=t.map.initialViewProperties?.viewpoint?.targetGeometry;return e?(await t.goTo(e),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},gb=async(t,e)=>{let{mapView:r}=$t(e);return await hb(r)},QV=L(gb,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:d.object({})}),Up=750;function pi(t){return"point"in t&&t.point!==void 0}function Go(t){return"layerId"in t&&t.layerId!==void 0}var hi=async(t,e)=>{if(pi(t)){let{point:r}=t;return{geometry:new Bp({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Go(t)){let r=e.map?.allLayers.find(s=>s.id===t.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${t.layerId}`};let n=r.title??r.id,o=t.where?.trim()||"1=1";try{let s=await r.queryFeatures({where:o,returnGeometry:!0,outSpatialReference:e.spatialReference,num:Up+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Up)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let i=s.features.map(c=>c.geometry).filter(c=>!!c);if(!i.length)return{error:"No valid geometries found for the matched geometry layer features."};let a=i.length===1?i[0]:Wp.executeMany(i);return a?(a.spatialReference||(a.spatialReference=e.spatialReference),{geometry:a}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},yb=async(t,e,r,n,o,s)=>{let i=t.map?.allLayers.find(c=>c.id===e);if(!i)return{success:!1,error:`Layer '${e}' not found.`};let a=i.createQuery();a.where=r??"1=1",n&&(a.geometry=n,a.spatialRelationship="intersects",o&&(a.distance=o),s&&(a.units=s));try{let{extent:c,count:l}=await i.queryExtent(a);return!c||l===0?{success:!1,error:`No features found for filter (where: ${a.where}${n?", spatial filter used":""})`}:(await t.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},_b=async(t,e,r,n,o,s)=>{let i=e.map?.allLayers.find(p=>p.id===t.layerId);if(!i)return`Could not find target layer with ID: ${t.layerId}`;let a;if(o){let p=await hi(o,e);if("error"in p)return p.error;a=p.geometry}if(i.featureEffect=null,i.featureEffect=new t_({filter:new Kp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:a,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),i.visible=!0,s)return`Applied feature effects to "${i.title??t.layerId}" within current map extent.`;let c=t.objectIds?.length?`${i.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await yb(e,t.layerId,c,a,o?.distance,o?.units),u=i.title??t.layerId;return l.success?`Applied feature effects to target layer "${i.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${u}" but no features matched. ${l.error}`},wb=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Nt=d.enum(wb),bb=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:i}=$t(s);return await _b(t,i,n,o,e,r)},Ab=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Nt.optional().describe("The units for the distance buffer.")}),xb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Nt.optional().describe("The units for the distance buffer.")}),Ib=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:d.union([Ab,xb]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:d.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:d.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),YV=L(bb,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Ib}),vb=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Vp=t=>{if(!t)return!1;let e=t.toLowerCase();return vb.has(e)},gl=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},Tb=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Sb=t=>{if(typeof t=="string"&&t)return t;let e=gl(t);return e?e.toISOString().slice(0,10):null};var Cb=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Vp(n))return t;if(n==="date-only"){let s=Sb(t);return s?r_(s,ci("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return n_(t,ci("long-time"));let s=gl(t);return s?Fp(s,{...ci("long-time"),timeZone:"UTC"}):t}let o=gl(t);return o?Fp(o,{...ci("short-date-short-time"),timeZone:Tb(r)}):t},Gp=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(i=>i.code===e);return s?s.name:null}}return null},kb=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Eb=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(typeof t=="number"&&Number.isFinite(t)){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}if(typeof t=="string"&&t){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null},Pb=(t,e)=>{if(typeof t!="number")return t;let r={};e.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=e.minimumFractionDigits),e.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=e.maximumFractionDigits),e.useGrouping==="always"?r.useGrouping=!0:e.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(t)}catch{return t}},Ob=(t,e,r)=>{let n=Eb(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=kb(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Jp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,Zp=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?Pb(r,s):s?.type==="date-time"?!n||Vp(n)?Ob(r,s,o):r:Cb(r,n,o)},Mb=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Gp(e,r,t)??r;return Zp(t,e,s,o?.type,n)},Rb=(t,e)=>Jp(t,e),Qp=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(i=>i.attributes[n]),s=e.features.map(i=>{let a=i.attributes,c={};return t.fields.forEach(l=>{if(!Object.hasOwn(a,l.name))return;let u=a[l.name];if(l.name===n){c[l.name]=u;return}let p=Gp(l.name,u,t)??u,f=Jp(t,l.name);c[f]=Zp(t,l.name,p,l.type,r)}),c});return{objectIds:o,attributes:s}},$b=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Nb=async(t,e,r,n)=>{let o=n.map?.allLayers.find(u=>u.id===t),s=$b(o,e,r.where),i=(await o.queryFeatures(s)).features[0],a=i?i.attributes[e]:null,c=Mb(o,e,a,n.timeZone),l=Rb(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${c}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:c,where:r.where}}};async function Lb({layerId:t,fieldName:e,query:r},n){let{mapView:o}=$t(n),s=await Nb(t,e,r,o);return JSON.stringify(s,null,2)}var Db=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Fb=L(Lb,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Db}),Tl=(t,e,r)=>{if(!(r?t.hasAllFeaturesInView:t.hasAllFeatures))return!1;let n=new Set((t.availableFields??[]).map(o=>o.toLowerCase()));return n.has("*")?!0:e.every(o=>n.has(o.toLowerCase()))};function mi(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var jb=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:i}=t,a=o.map?.allLayers.find(S=>S.id===e.layerId);if(!a)throw new Error(`Layer '${e.layerId}' not found.`);let c=await o.whenLayerView(a),l=s.get(e.layerId)?.fieldRegistry.get(r),u=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,f;if(i){let S=await hi(i,o);if("error"in S)throw new Error(S.error);if(!S.geometry)throw Go(i)?new Error(`No features found matching: ${i.where}`):new Error("Failed to create geometry");if(Go(i)){let h=o.map?.allLayers.find(I=>I.id===i.layerId);p={geometryLayerName:h?.title??h?.id,geometryLayerId:i.layerId,geometryWhere:i.where,distance:i.distance,units:i.units,applied:!0}}else pi(i)&&(p={point:i.point,distance:i.distance,units:i.units,applied:!0});f=new Kp({geometry:S.geometry,distance:i.distance,units:i.units,spatialRelationship:"intersects"})}let w=Tl(c,[r],!1),x=null,g=null,b=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let S={layer:a,useFeaturesInView:w,view:w?o:void 0,field:r,sqlWhere:mi(a.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};x=await o_(S);let h=["string","small-integer","integer"],I=l.domain?.type==="coded-value"?l.domain:null;(h.includes(l.type)||I)&&(g=(await s_({layer:a,useFeaturesInView:w,view:w?o:void 0,field:r,sqlWhere:mi(a.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((E,D)=>D.count-E.count).slice(0,b)),g&&l.domain?.type==="coded-value"&&(g=g.map(E=>({...E,value:I?I.getName(E.value)??E.value:E.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:a.title??e.layerId,summary:`${n} = ${typeof x?.[n]=="number"?x[n]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:n,statistic:x?.[n]??null,summaryStatistics:x,uniqueValues:g,where:e.where,spatialFilterInfo:p}}};async function zb({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=to(o,"layersAndFieldsRegistry"),{mapView:i}=$t(o),a=await jb({targetLayer:t,fieldName:e,statisticType:r,mapView:i,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(a,null,2)}var Ub=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Nt.optional().describe("The units for the distance buffer.")}),qb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Nt.optional().describe("The units for the distance buffer.")}),Bb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([Ub,qb]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Kb=L(zb,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
157
-
158
- USE THIS TOOL FOR:
159
- - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
160
- - "Most common/frequent value of [field]?" \u2014 frequency analysis
161
- - Questions requiring a mathematical aggregation across many features
162
-
163
- DO NOT USE FOR:
164
- - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
165
- - "Show / list / find features" \u2014 use queryFeatures instead
166
- - Simple counts of features matching a condition \u2014 use queryFeatures instead
167
-
168
- Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Bb}),Wb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Hb=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),i=await r.whenLayerView(s),a=s.title??t.layerId,c;if(n){let f=await hi(n,r);if("error"in f)return{tool:"getTopFeatures",layerName:a,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:a,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};c=f.geometry}else o&&(c=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,u=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])];try{let f;if(l){let g=new i_({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new a_({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(g)}else{let g=s.createQuery();g.where=mi(s.definitionExpression,t.where||"1=1"),g.outFields=p.length?p:["*"],g.orderByFields=e.orderByFields,g.returnGeometry=!1,g.num=e.topCount,c&&(g.geometry=c,g.spatialRelationship="intersects"),n?.distance&&(g.distance=n.distance),n?.units&&(g.units=n.units),g.outSpatialReference=r.spatialReference;let b=[...new Set([...t.outFields,...Wb(e.orderByFields)])],S=Tl(i,b,o??!1);try{f=S?await i.queryFeatures(g):await s.queryFeatures(g)}catch(h){console.warn("Client-side query failed, falling back to server:",h),f=await s.queryFeatures(g)}}let w=f.features.map(g=>g.attributes[u]),{attributes:x}=Qp(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:a,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:x,objectIds:w,objectIdField:u,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:a,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},Vb=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=$t(o),i=await Hb(t,e,s,r,n);return JSON.stringify(i,null,2)},Gb=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Nt.optional().describe("The units for the distance buffer.")}),Jb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Nt.optional().describe("The units for the distance buffer.")}),Zb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([Gb,Jb]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),Qb=L(Vb,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:Zb}),hl=25,Yb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Xb=async(t,e,r,n)=>{let o=e.map?.allLayers.find(b=>b.id===t.layerId),s=await e.whenLayerView(o),i=o.title??t.layerId,a;if(r){let b=await hi(r,e);if("error"in b){let S={error:b.error};if(Go(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else pi(r)&&(S.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"Geometry lookup failed",details:S}}if(!b.geometry){let S={};if(Go(r)){let h=e.map?.allLayers.find(I=>I.id===r.layerId);S.error=`No features found matching: ${r.where}`,S.geometryLayerName=h?.title??h?.id,S.geometryLayerId=r.layerId,S.geometryWhere=r.where}else pi(r)&&(S.error="Failed to create point geometry",S.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"No features found for geometry filter",details:S}}a=b.geometry}else n&&(a=e.extent.clone());let c=[...new Set([...t.outFields,...Yb(t.orderByFields)])],l=Tl(s,c,n??!1),u=o.objectIdField,p=o.createQuery();p.where=mi(o.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])],p.orderByFields=t.orderByFields,a&&(p.geometry=a,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let f,w;try{f=l?await s.queryFeatureCount(p):await o.queryFeatureCount(p),f>0&&f<=hl&&(w=l?await s.queryFeatures(p):await o.queryFeatures(p))}catch(b){console.warn("Client-side query failed, falling back to server:",b),f=await o.queryFeatureCount(p),f>0&&f<=hl&&(w=await o.queryFeatures(p))}let{objectIds:x,attributes:g}=w?Qp(o,w,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:i,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...x&&{objectIds:x,objectIdField:u},...g&&{attributes:g},...f>hl&&{note:`${f} features found.`}}}};async function eA({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=$t(n),s=await Xb(t,o,e,r);return JSON.stringify(s,null,2)}var tA=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:Nt.optional().describe("The units for the distance buffer.")}),rA=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:Nt.optional().describe("The units for the distance buffer.")}),nA=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([tA,rA]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),oA=L(eA,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
169
-
170
- USE THIS TOOL FOR:
171
- - "Show / display / list features where..." \u2014 finding and listing features
172
- - "How many X are Y?" \u2014 counting features that match a condition
173
- - "Which features..." / "Find features..." \u2014 identifying specific features
174
- - Spatial queries \u2014 finding features near/within/intersecting other features
175
- - Any question where the user wants to SEE or COUNT matching features
176
-
177
- This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:nA}),Yp=[Fb,Kb,Qb,oA];var XV=new at(Yp,{handleToolErrors:!1});var sA=O.Root({...Rt(),helpInternalState:O({reducer:Vo,default:()=>({toolCallMessage:void 0})})}),iA=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(i=>i.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
178
- `);return`**${r.layerItem.title}** has ${n.length} field(s):
179
-
180
- ${o}`},aA=async({layerTitle:t},e)=>{let r=to(e,"layersAndFieldsRegistry");return iA(r,t)},lA=L(aA,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:d.object({layerTitle:d.string().describe("The title or partial title of the layer to list fields for.")})}),cA=O.Root({...Rt(),intent:O({reducer:(t,e)=>e}),arcgisKnowledgeMessages:O({reducer:uo,default:()=>[]}),arcgisKnowledgeToolResult:O({reducer:(t,e)=>e,default:()=>null})});function Xp(t){let e=t.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!e||e?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function ro(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function gi(t){!t||ro(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Zo(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in e))throw new Error("View context missing");let r=e.view;return r.map&&!("activeLinkChartLayer"in r.map)&&Xp(r),{view:r}}async function no(t){let e=t?.configurable?.context;if(uA(t)==="knowledgeGraph")return e;{let r=e.view.map;if(r&&"activeLinkChartLayer"in r){let n=r.knowledgeGraph?.url;if(!n)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await jp(n)}}else{Xp(e.view);let n=(e.view.map?.allLayers.find(o=>o.type==="knowledge-graph")).url;if(!n)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await jp(n)}}}}function uA(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in e&&"view"in e)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in e)return"knowledgeGraph";if("view"in e)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var yl=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=fi.fromDataModel(e)}},fi=class t{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(e){let r=new t;for(let n of e.entityTypes)r.entityTypes.push(Jo.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(_l.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:dA(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
181
- Relationship Types: ${n}.`}},Jo=class t{constructor(){this.name="",this.properties=[]}static fromEntityType(e){let r=new t;r.name=e.name,r.alias=e.alias?e.alias:void 0,r.role=pA(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:mA(n.role),geometryDef:n.fieldType==="esriFieldTypeGeometry"?{geometryType:n.geometryType??"esriGeometryAny",hasM:n.hasM?n.hasM:void 0,hasZ:n.hasZ?n.hasZ:void 0}:void 0};r.properties.push(o)}return r}},_l=class extends Jo{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=Jo.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},dA=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},pA=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function mA(t){switch(t){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function yi(t){return t?.signal}async function fA(t,e){let r=await lt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
182
-
183
- Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
184
-
185
- Attempt Number: ${e.attemptCount}
186
- Execution Error: ${e.executionError}
187
- Failed Query:
188
- ${e.failedGraphQuery}`:`${t} ${r}`}async function hA(t,e,r,n){let{graphQuery:o,explanation:s}=await Sl(t,e,r,n);return{graphQuery:o,explanation:s}}async function Sl(t,e,r,n,o){let s={message:await fA(t,o),context:new yl(e)},i=yi(n);await Y({text:"Attempting to generate a cypher query from your prompt..."},n);let a=await Lp(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:Np.findCredential(xr.getDefault().url)?.token??""},signal:i});if(a.httpStatus!==200)throw new Error(`Graph query service returned an error: ${a.httpStatus}`,{cause:a.data});let c=!1,l=Date.now(),u=a.data.sequenceNumber,p="",f="",w=1;for(;!c;){await new Promise(g=>setTimeout(g,1e3)),await Y({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,w)}`},n),w=w%3+1;let x=await Lp(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:a.data.conversationId,inquiryId:a.data.inquiryId,ackSequenceNumber:u}),headers:{"Content-Type":"application/json",token:Np.findCredential(xr.getDefault().url)?.token??""},signal:i});if(x.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${x.httpStatus}`,{cause:x.data});if(x.data.context?.kind){if(x.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${x.data.message}`,{cause:x.data});p=x.data.context.graphQuery,f=x.data.message||"",c=!0}else if(!x.data.hasMore)c=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");u=x.data.sequenceNumber}return{graphQuery:p,explanation:f}}function gA(t,e){Xn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Xn(t,e){if(!(!t||typeof t!="object")){if(_A(t))for(let r of t.path)Xn(r,e);else if(yA(t))e(t);else if(Array.isArray(t))for(let r of t)Xn(r,e);else if(wA(t))for(let r of Object.values(t.properties??{}))Xn(r,e)}}function yA(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function _A(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function wA(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function bA(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,i]of o)for(let a of s){let c=t.getMemberIdsByType(a.name);i.push(...c)}return{entityIds:r,relationshipIds:n}}function AA(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(a=>a.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],i=!0;for(let[a,c]of s)for(let l of a){let u=o.namedTypeDefinitions.get(l.name);if(!u){i=!1,n.push(l.name);continue}if(!u.useAllData){i=!1,n.push(l.name);for(let[p]of u.members||[])c.push(p)}}return{allNamedTypesFullyDynamic:i,bindParameters:r,nonDynamicTypes:n}}var eo=3;function em(t,e=100){let r={};for(let n of Object.entries(t.properties??{})){let[o,s]=n;typeof s=="string"&&s.length>e?r[o]=`${s.slice(0,e)}... (truncated, original length: ${s.length})`:r[o]=s}return t.properties=r,t}function oo(t){return typeof t!="object"||t===null?String(t):"details"in t&&typeof t.details=="object"&&t.details!==null&&"errorMessage"in t.details&&typeof t.details.errorMessage=="string"?t.details.errorMessage:"message"in t&&typeof t.message=="string"?t.message:String(t)}var xA=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:i})=>{let a=null,c=r,l=new AbortController,u=o?.signal,p=()=>{l.abort(u?.reason)};u&&(u.aborted?l.abort(u.reason):u.addEventListener("abort",p,{once:!0}));try{let f=await c_(t,e,o);a=f.resultHeader;let w=f.resultRowsStream.getReader(),x=0,g=Date.now(),b=!1;for(;;){let{done:S,value:h}=await w.read();if(S)break;if(!b&&i&&Date.now()-g>i)return l.abort(),{type:"timeout"};for(let I of h){if(x++,s&&x>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:a,processedResult:c};c=n(c,I)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:oo(f),error:f}}finally{u?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:a,processedResult:c}};async function tm({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c,config:l}){let u;for(let p=1;p<=eo;p++){let f;try{f=await Sl(t,r.dataModel,n,l,u)}catch(b){return{type:"generation-error",errorMessage:oo(b),error:b}}await Y({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let w=await IA(f.graphQuery,e),x=await xA({kg:r,queryParams:new Hp({openCypherQuery:f.graphQuery,bindParameters:w}),targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c}),g=x.type==="aborted"?"Query execution was aborted.":x.type==="timeout"?"Query execution timed out.":x.type==="error"?`Query failed with error: ${x.errorMessage}`:"";if(x.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:x.rowLimitReached,resultHeader:x.resultHeader,processedResult:x.processedResult};if(x.type==="aborted")return{type:"aborted",errorMessage:g,graphQuery:f.graphQuery,explanation:f.explanation};if(p>=eo)return x.type==="timeout"?{type:"timeout",errorMessage:g,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:g,error:x.error,graphQuery:f.graphQuery,explanation:f.explanation};u={failedGraphQuery:f.graphQuery,executionError:g,attemptCount:p},await Y({text:`Attempt ${p} failed with error: ${g}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${eo} attempts.`)}var IA=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await p_(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},vA=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let i=[],a=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(a=["entity","relationship"]);let c=o??1/0;try{for(let l of a){let u=c-i.length;if(u<=0)break;let p=(await u_(t,new d_({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:u}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:w,value:x}=await p.read();if(w){f=!0;break}for(let g of x)for(let b of g)i.push(b)}}}catch(l){let u=oo(l);return s?.signal?.aborted?{type:"aborted",errorMessage:u,error:l}:{type:"error",errorMessage:u,error:l}}return{type:"success",results:i}},rm="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function nm({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(rm),!ro(e)){let u=await lt("arcgis_knowledge_current_lc_context"),p=bA(e.map,r);return o.push(u),{enhancedPrompt:o.join(`
189
-
190
- `),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:i,bindParameters:a,nonDynamicTypes:c}=AA(s,r);if(i)return{enhancedPrompt:o.join(`
191
-
192
- `),bindParameters:a,allNamedTypesFullyDynamic:!0};let l=(await lt("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(c));return o.push(l),{enhancedPrompt:o.join(`
193
-
194
- `),bindParameters:a,allNamedTypesFullyDynamic:i}}async function TA(t,e,r,n,o,s){let{view:i}=o,a=await tm({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,w)=>{for(let x of w)gA(x,f);return f},requestOptions:{signal:yi(s),timeout:s?.timeout},config:s});if(a.type!=="success"){let f=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:c,explanation:l,processedResult:u}=a,p=Array.from(u.values());return await Y({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),!ro(i)&&i?.map?(await i.map.addRecords(p),await gi(i),{generatedQuery:c,explanation:l,addedIdTypePairs:p}):(await i?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(p),{generatedQuery:c,explanation:l,addedIdTypePairs:p})}var ui="addRecords",SA=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),CA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await no(e),n=Zo(e),{view:o}=n,s=xr.getDefault().helperServices,{enhancedPrompt:i,bindParameters:a,allNamedTypesFullyDynamic:c}=await nm({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(c)return{toolName:ui,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:u,addedIdTypePairs:p}=await TA(i,a,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:ui,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
195
-
196
- Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:u,addedIdTypePairs:p}}}catch(l){let u=oo(l);return{toolName:ui,status:"error",errorMessage:`Failed to add records to the link chart. ${u}`,error:l}}},kA=L(CA,{name:ui,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
197
-
198
- example prompts:
199
- - "add all suppliers and the parts they produce to the link chart"
200
- - "show me the competitors of company x and add them to the link chart"
201
- - "add the relationships between company x and company y to the link chart"
202
- - "expand all the companies"
203
- - "expand company x through all the buildings it owns"
204
- - "connect company x and company y"
205
- - "connect all buildings on the link chart"
206
- `,schema:SA});async function EA(t,e){return await e.map?.applyLayout(t),await gi(e),{appliedLayout:t}}var wl="applyLayout",PA=d.object({layout:d.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),OA=async({layout:t},e)=>{let{view:r}=Zo(e);if(ro(r))return{toolName:wl,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await EA(t,r);return{toolName:wl,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},MA=L(OA,{name:wl,description:"Apply a diagram layout to the link chart",schema:PA});async function RA(t,e){return e.map?.changeNonspatialDataDisplay(t),await gi(e),{appliedNonspatialDataDisplayMode:t}}var bl="changeNonspatialVisibility",$A=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),NA=async({setting:t},e)=>{let{view:r}=Zo(e);if(ro(r))return{toolName:bl,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await RA(t,r);return{toolName:bl,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},LA=L(NA,{name:bl,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:$A});async function DA(t,e,r,n,o){let s,i="";for(let a=1;a<=eo;a++){let{graphQuery:c,explanation:l}=await Sl(t,e.dataModel,r,o,s);try{await Y({text:`Attempting to create link chart from derived query: ${c}`},o);let u=await l_.fromCypherQuery(e,new Hp({openCypherQuery:c}));await Y({text:"Link chart created successfully, loading..."},o),await u.load();let p=n.map;return n.map=u,await n.when(),await qp.whenOnce(()=>!n.updating),u.entityCount===0&&u.relationshipCount===0?(n.map===u&&(n.map=p),u.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
207
- ${c}
208
-
209
- Explanation: ${l}`}):(await gi(n),{type:"success",graphQuery:c,explanation:l})}catch(u){let p=oo(u);if(a>=eo){i=p;break}s={failedGraphQuery:c,executionError:p,attemptCount:a},await Y({text:`Attempt ${a} to create link chart failed with error: ${p}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${eo} attempts. Last error: ${i}`}}var di="createLinkChart",FA=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),jA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await no(e),{view:n}=Zo(e);if(ro(n))return{toolName:di,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=xr.getDefault().helperServices,s=await DA(`${t}
210
-
211
- ${rm}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:di,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:i,explanation:a}=s;return{toolName:di,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
212
- ${i}
213
-
214
- Explanation: ${a}`,details:{generatedQuery:i,explanation:a}}}},zA=L(jA,{name:di,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt using language like 'create new link chart' or 'add to new link chart'.",schema:FA}),Al="queryGraphData",UA=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),qA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await no(e),n=xr.getDefault().helperServices,o=t,s=null,i=null;try{({view:i}=Zo(e))}catch{}i&&({enhancedPrompt:o,bindParameters:s}=await nm({prompt:t,view:i,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let a=await tm({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(g,b)=>(g.push(b),g),requestOptions:{signal:yi(e),timeout:e?.timeout},config:e});if(a.type!=="success"){let g=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;return{toolName:Al,status:"error",errorMessage:`Failed to query the knowledge graph. ${g}`,error:"error"in a?a.error:null}}let{graphQuery:c,explanation:l,processedResult:u,resultHeader:p}=a,f=p.headerKeys;for(let g of u)for(let b of g)Xn(b,S=>em(S));let w=50,x=u.slice(0,w).map(g=>JSON.stringify(g));return{toolName:Al,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
215
-
216
- \`\`\`cypher
217
- ${c}
218
- \`\`\`
219
-
220
- Query Results:
221
- ${x.length} result(s) found.
222
-
223
- Column Headers: ${f.join(", ")}
224
-
225
- ${x.length>w?`Showing top ${w} results:
226
-
227
- `:`Results:
228
-
229
- `}${x.join(`
230
- `)}
231
- `,details:{generatedQuery:c,explanation:l,resultHeader:p,queryResults:u}}},BA=L(qA,{name:Al,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:UA}),xl="generateCypher",KA=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),WA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await no(e),n=xr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await hA(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:xl,status:"success",summary:`Generated Graph Query:
232
- ${o}
233
-
234
- Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=oo(o);return{toolName:xl,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},HA=L(WA,{name:xl,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:KA}),VA=t=>{let e=t.dataModel,r=new Map;for(let a of e.searchIndexes)if(a.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[c,l]of a.searchProperties.entries()){let u=r.get(c)??new Set;l.propertyNames.forEach(p=>u.add(p)),r.set(c,u)}let n=e.entityTypes.filter(a=>r.has(a.name)),o=e.relationshipTypes.filter(a=>r.has(a.name)),s=`Entity Types:
235
- ${n.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
236
- `)}`,i=`Relationship Types:
237
- ${o.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
238
- `)}`;return`${s}
239
-
240
- ${i}`};async function GA(t,e,r){let n=await lt("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:VA(e)},s=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),i=d.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),a=d.array(d.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),c=d.object({query:d.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:a.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:i});return await Ho({promptText:n,inputVariables:o,schema:c,config:r})}var Il="searchGraphData",JA=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),ZA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await no(e);await Y({text:"Generating search query for the user inquiry"},e);let n=await GA(t,r,e);await Y({text:"Executing graph search with generated search query"},e);let o=await vA({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:yi(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:Il,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let a of o.results)Xn(a,c=>em(c));let s=10,i=o.results.slice(0,s);return{toolName:Il,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
241
- Query: ${n.query}
242
- Type Category Filter: ${n.typeCategoryFilter}
243
- Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
244
- Result Limit: ${n.resultLimit??"No limit"}
245
-
246
- Search Results: ${o.results.length} result(s) found.
247
-
248
- ${o.results.length>s?`Showing top ${s} results:
249
-
250
- `:""}${i.map(a=>JSON.stringify(a)).join(`
251
- `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},QA=L(ZA,{name:Il,description:`
252
- Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
253
- Example prompts:
254
- - "Find 'Bradley'"
255
- - "find the person john smith"
256
- - "find all people named smith"
257
- - "Find all references to 'delayed parts shipment'"
258
- - "Find all reports authored by someone with the title of 'Researcher'"
259
- - "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
260
- - "Search for all john smiths and show their global ids`,schema:JA});var gG=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
261
- This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
262
-
263
- Supported actions:
264
- - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
265
- - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
266
- - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
267
- - **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
268
- - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
269
- - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
270
- - **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
271
- - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
272
-
273
- _Example: “Zoom to Texas”_
274
- _Example: “Go to the water mains layer”_
275
- _Example: “Zoom to to the extent of my link chart”_
276
- _Example: “Center the map on San Francisco at scale 50000”_
277
- _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
278
- _Example: “Go to the Downtown bookmark”_
279
- _Example: “Where is Mount Rainier?”_`;var HG=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
280
- _Example: “Color points by sales amount”_
281
- _Example: “Show population density with a color gradient”_
282
- _Example: “Create a relationship map between height and depth”_
283
- _Example: “Vary circle sizes according to population”_`;var g4=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
284
- The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
285
- _Example: “Only show stations where Brand is Shell”_
286
- _Example: “Make Shell stations stand out on the map”_
287
- _Example: “Gray out all stations that aren’t Shell”_
288
- 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.
289
- _Example: “How many features are there?”_
290
- _Example: “What’s the average population?”_
291
- _Example: “Which values are in the status field?”_
292
-
293
- 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 R4=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
294
-
295
- _Example: “Tell me about this map”_
296
- _Example: “List all layers in this map”_
297
- _Example: “List fields in protected areas layer”_
298
- _Example: “What agents are available to me?”_
299
- _Example: “What can you do?”_
300
- _Example: “What can I ask”_
301
-
302
- 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.
303
-
304
- 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.
305
- _Example: "Create a chart"_
306
- _Example: "Create a table"_`;var Q4=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).
307
- 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.
308
- For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
309
- expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
310
- that exist out from specified entities and adding those to the link chart, changing whether or not nonspatial data is visible, or changing the layout of the link chart.
311
- This agent is designed to handle requests that manipulate the specific link chart.
312
- For knowledge graph data more generally, the agent can generate Open Cypher queries based on user prompts that represent inquiries into the data of the knowledge service and its graph database,
313
- and can alternatively use those queries to create a new link chart visualization from the results if requested.
314
-
315
- Supported actions:
316
- - **Change or Apply Layout**: Changes the current layout visualization strategy of the link chart (e.g., "Change the layout to basic-grid", "Apply hierarchical layout"). Valid layout types include organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline. A best effort should be made to transform the user's request into one of these layout types.
317
- - **Change Nonspatial Data Visibility**: Changes whether or not nonspatial data is visible on the link chart (e.g., "Show nonspatial data", "Hide nonspatial data"). Valid settings are "hidden" and "visible". A best effort should be made to transform the user's request into one of these settings.
318
- - **Generate a cypher query**: Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance. The user should explicitly request that a cypher query be returned - if they do not, the purpose of the query is for one of the other tools or skills.
319
- - **Create a New Link Chart from a user prompt**: Identifies that the users prompt is an inquiry into the data of the knowledge service and its graph database and creates a new link chart from the results. The user should have requested that a link chart be created or made(or similar term) from their prompt
320
- - **Add Records (entities or relationships)**: Identifies that the users prompt is an inquiry into the data of the knowledge graph service and its graph database, and that the user wants to take the result of the inquiry and add those entities and/or relationships to the link chart. The generated query should be syntactically correct and optimized for performance.
321
- - **Search Graph Data**: Generates and runs a lucene syntax query based on the user's prompt, returning matching entity and relationship records from the knowledge graph.
322
- - **Query Graph Data**: Generates and executes a cypher query based on the user's prompt, and displays the results in the chat pane, allowing the user to explore the data in their knowledge graph.
323
-
324
- _example: "Change the layout to hierarchical-bottom-to-top"_
325
- _example: "Apply radial-root-centric layout"_
326
- _example: "Show nonspatial data"_
327
- _example: "Hide nonspatial data"_
328
- _example: "Turn off nonspatial visibility"_
329
- _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
330
- _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
331
- _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
332
- _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
333
- _example: "Find all people who work for Microsoft and put them on a new link chart"_
334
- _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
335
- _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
336
- _example: "Find all the products supplied by Supplier X and add them to my visualization"_
337
- _example: "Expand the link chart from 'Entity D' to show its direct connections"_
338
- _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
339
- _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
340
- _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
341
- _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
342
- _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
343
- _example: "Find John Smith and all people he has made phone calls to in the last year"_
344
- _example: "What is the average age of all people who work for Esri?"_`;var ex=(t,e)=>{if(t.length!==e.length)throw new Error("Vectors must be the same length");let r=0,n=0,o=0;for(let a=0;a<t.length;++a){let c=t[a],l=e[a];r+=c*l,n+=c*c,o+=l*l}let s=Math.sqrt(n*o);if(s===0)return 0;let i=r/s;return Math.max(-1,Math.min(1,i))},om=li,ct=Ho;var De=Y,sm=Mp,im=ex;var wi=()=>Rt();var kl={};Kl(kl,{JsonPatchError:()=>J,_areEquals:()=>es,applyOperation:()=>Ir,applyPatch:()=>io,applyReducer:()=>sx,deepClone:()=>nx,getValueByPointer:()=>vi,validate:()=>lm,validator:()=>Ti});var tx=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),rx=Object.prototype.hasOwnProperty;function Ai(t,e){return rx.call(t,e)}function xi(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var o in t)Ai(t,o)&&n.push(o);return n}function ce(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Ii(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function He(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Yo(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function bi(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(bi(t[e]))return!0}else if(typeof t=="object"){for(var n=xi(t),o=n.length,s=0;s<o;s++)if(bi(t[n[s]]))return!0}}return!1}function am(t,e){var r=[t];for(var n in e){var o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(n+": "+o)}return r.join(`
345
- `)}var Xo=(function(t){tx(e,t);function e(r,n,o,s,i){var a=this.constructor,c=t.call(this,am(r,{name:n,index:o,operation:s,tree:i}))||this;return c.name=n,c.index=o,c.operation=s,c.tree=i,Object.setPrototypeOf(c,a.prototype),c.message=am(r,{name:n,index:o,operation:s,tree:i}),c}return e})(Error);var J=Xo,nx=ce,so={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=vi(r,this.path);n&&(n=ce(n));var o=Ir(r,{op:"remove",path:this.from}).removed;return Ir(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=vi(r,this.from);return Ir(r,{op:"add",path:this.path,value:ce(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:es(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},ox={add:function(t,e,r){return Ii(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:so.move,copy:so.copy,test:so.test,_get:so._get};function vi(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ir(t,r),r.value}function Ir(t,e,r,n,o,s){if(r===void 0&&(r=!1),n===void 0&&(n=!0),o===void 0&&(o=!0),s===void 0&&(s=0),r&&(typeof r=="function"?r(e,0,t,e.path):Ti(e,0)),e.path===""){var i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=vi(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=es(t,e.value),i.test===!1)throw new J("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new J("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=ce(t));var a=e.path||"",c=a.split("/"),l=t,u=1,p=c.length,f=void 0,w=void 0,x=void 0;for(typeof r=="function"?x=r:x=Ti;;){if(w=c[u],w&&w.indexOf("~")!=-1&&(w=Yo(w)),o&&(w=="__proto__"||w=="prototype"&&u>0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&f===void 0&&(l[w]===void 0?f=c.slice(0,u).join("/"):u==p-1&&(f=e.path),f!==void 0&&x(e,0,t,f)),u++,Array.isArray(l)){if(w==="-")w=l.length;else{if(r&&!Ii(w))throw new J("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Ii(w)&&(w=~~w)}if(u>=p){if(r&&e.op==="add"&&w>l.length)throw new J("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var i=ox[e.op].call(e,l,w,t);if(i.test===!1)throw new J("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(u>=p){var i=so[e.op].call(e,l,w,t);if(i.test===!1)throw new J("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(l=l[w],r&&u<p&&(!l||typeof l!="object"))throw new J("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function io(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new J("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=ce(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=Ir(t,e[i],r,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function sx(t,e,r){var n=Ir(t,e);if(n.test===!1)throw new J("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Ti(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new J("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(so[t.op]){if(typeof t.path!="string")throw new J("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new J('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new J("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new J("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&bi(t.value))throw new J("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,s=n.split("/").length;if(o!==s+1&&o!==s)throw new J("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new J("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},a=lm([i],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new J("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new J("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function lm(t,e,r){try{if(!Array.isArray(t))throw new J("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)io(ce(e),ce(t),r||!0);else{r=r||Ti;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(o){if(o instanceof J)return o;throw o}}function es(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),o,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!es(t[o],e[o]))return!1;return!0}if(r!=n)return!1;var a=Object.keys(t);if(s=a.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=s;o--!==0;)if(i=a[o],!es(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var Ml={};Kl(Ml,{compare:()=>mx,generate:()=>El,observe:()=>px,unobserve:()=>dx});var Pl=new WeakMap,ix=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),ax=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function lx(t){return Pl.get(t)}function cx(t,e){return t.observers.get(e)}function ux(t,e){t.observers.delete(e.callback)}function dx(t,e){e.unobserve()}function px(t,e){var r=[],n,o=lx(t);if(!o)o=new ix(t),Pl.set(t,o);else{var s=cx(o,e);n=s&&s.observer}if(n)return n;if(n={},o.value=ce(t),e){n.callback=e,n.next=null;var i=function(){El(n)},a=function(){clearTimeout(n.next),n.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return n.patches=r,n.object=t,n.unobserve=function(){El(n),clearTimeout(n.next),ux(o,n),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new ax(e,n)),n}function El(t,e){e===void 0&&(e=!1);var r=Pl.get(t.object);Ol(r.value,t.object,t.patches,"",e),t.patches.length&&io(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function Ol(t,e,r,n,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=xi(e),i=xi(t),a=!1,c=!1,l=i.length-1;l>=0;l--){var u=i[l],p=t[u];if(Ai(e,u)&&!(e[u]===void 0&&p!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof p=="object"&&p!=null&&typeof f=="object"&&f!=null&&Array.isArray(p)===Array.isArray(f)?Ol(p,f,r,n+"/"+He(u),o):p!==f&&(a=!0,o&&r.push({op:"test",path:n+"/"+He(u),value:ce(p)}),r.push({op:"replace",path:n+"/"+He(u),value:ce(f)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+He(u),value:ce(p)}),r.push({op:"remove",path:n+"/"+He(u)}),c=!0):(o&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),a=!0)}if(!(!c&&s.length==i.length))for(var l=0;l<s.length;l++){var u=s[l];!Ai(t,u)&&e[u]!==void 0&&r.push({op:"add",path:n+"/"+He(u),value:ce(e[u])})}}}function mx(t,e,r){r===void 0&&(r=!1);var n=[];return Ol(t,e,n,"",r),n}var vJ=Object.assign({},kl,Ml,{JsonPatchError:Xo,deepClone:ce,escapePathComponent:He,unescapePathComponent:Yo});var gx=Wl`: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 Ce(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
346
- Available prompts:
347
- ${Object.keys(t).join(`
348
- `)}`);return await r[1]()}function Pi(t){return t?.configurable?.context?.translations}function dm(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 pm(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var yx=v.object({needsContext:v.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:v.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),cm=t=>t?.signal?.aborted??!1,mm=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./AS6VINEU.js").then(t=>t.default),"./prompts/transformQuery.md":()=>import("./KLIO37YK.js").then(t=>t.default)});function _x(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">&#91;$1&#93;</a></sup>')}function wx(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function fm(t){let e=(t??"").trim();if(!e)return"en";let r=e.split(/[-_]/)[0]?.toLowerCase();return r?r.slice(0,2):"en"}function bx(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 Ax(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function hm(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function Nl(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 xx=t=>new Promise(e=>setTimeout(e,t));async function Ix(t,e){let r=t.agentExecutionContext.userRequest,n=e?.configurable?.context?.lastTurnAgent,o=t.agentExecutionContext.messages??[];if(!n||o.length<=1)return r;try{let s=await Ce(mm,"transformQuery"),i=await ct({promptText:s,modelTier:"advanced",temperature:0,schema:yx,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return i.rewrittenQuery.trim()}catch{}return r}var vx=O.Root({...wi(),solutionResponse:O({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:O({reducer:(t,e)=>e??null,default:()=>null}),conversationId:O({reducer:(t,e)=>e??t,default:()=>null})}),Tx=()=>new ge(vx).addNode("initializeAgent",Cx).addNode("askSolutionsQuestions",Sx).addEdge(he,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",V),gm=async(t,e,r,n)=>{if(!t)return;let o=hm(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:fm(r),use_llm:!1}}}}};n&&(s.conversationId=n),Nl(s,o,e??"")},Sx=async(t,e)=>{if(cm(e))return{};let r=Pi(e),n=t.documentSkillUrl,o=[],s=await Ix(t,e);await De({text:r.agentProgress.explorerAgentSearching},e);let i=await Nl({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:fm(e?.configurable?.context?.configContext.locale),use_llm:!1},rephrase_query:{allow:!1},conversation_title:{allow:!1},follow_up:{allow:!1},distill_query:{allow:!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 p=u.context?.results?.[0]?.reply??"";if(p!==""){let w=_x(p),x=wx(w),g=bx(x,e);c=g.source,o=[...o,...g.allMatches.filter(b=>!o.some(S=>S.solution.id===b.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let w="";f===1?w=r.agentProgress.explorerAgentReading:f===2?w=r.agentProgress.explorerAgentReviewing:f===3&&(w=r.agentProgress.explorerAgentPreparing),await De({text:w},e)}};for(await l(i);a.hasMore;){if(cm(e))return{};await xx(500),i=await Nl({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 hm(e?.configurable?.context.portal)&&gm(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?pm(o[0].solution.id):dm(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},Cx=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=Ax(e.configurable.context.portal)),{documentSkillUrl:r}};await Ce(mm,"solutions_explorer_description");var ym=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"},kx=t=>{let e=ym(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)}},Ex=t=>ym(t)==="human",Px=(t,e=3)=>t.filter(r=>Ex(r)).slice(-e).map(kx),Ox=(t,e=" ")=>Px(t).map(r=>r.content).join(e).trim(),Mx={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?"},Rx={builderMessages:Mx},Ei=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.FIELD_NAME_MAX_LENGTH=31}static{this.ALLOWED_FIELD_TYPES=new Set(["string","integer","double","date","guid"])}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=gs(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=ys(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(){for(let e of this.response.items){let r=gs(e.title??"");if(r.isValid||this._tryFixName(r.errorType,e.title??"",n=>{e.title=n},`Item '${e.id}' title`,"Item Title")||this._logIssue(`Item '${e.id}' title is invalid (${r.errorType}).`),e.description){let n=ys(e.description,t.DESCRIPTION_MAX_LENGTH,!0);n.isValid||this._tryFixDescription(e.description,o=>{e.description=o},`Item '${e.id}' description`)||this._logIssue(`Item '${e.id}' description is invalid (${n.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=gs(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=ys(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?.trim()||(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 c=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' 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 c=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' 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(Cc.has(e.name.toLowerCase()))if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(c,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(kc.has(e.name.toLowerCase()))if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(c,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' is a reserved system field name. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a reserved system field name.`);let i=e.type??"",a=i.toLowerCase();if(i!==a&&(e.type=a),!t.ALLOWED_FIELD_TYPES.has(a))if(this.newDesign){let c=e.type;a==="globalid"?e.type="guid":a==="oid"?e.type="integer":e.type="string",this._logAutoFix(`Field '${e.name}' had unsupported type '${c}'. Auto-fixed to '${e.type}'.`)}else this._logIssue(`Field '${e.name}' has unsupported type '${e.type}'. Allowed types are: string, integer, double, date.`);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 c=Math.max(...e.choiceList.map(l=>l.length));c>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 ${c} characters. Auto-fixing to ${c}.`),e.length=c):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${c} 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(!Pc(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(Ec.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}},$x=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.")}),um=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.")}),Lx=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(um).describe("User/business fields specific to the solution."),requiredFields:d.array(um).describe("Fields required for solution functionality (e.g., relationship keys).")}),Dx=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(Lx)}),Dl=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($x).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:Dx.describe("Primary feature layer item and its schema/layers/tables details.")}),Fx=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.")}),jx=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(Fx).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),zx=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),Ux=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.")}),qx=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),Bx=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.")}),Kx=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(Bx).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),Wx=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
349
- `):"No validation errors were provided.",Hx=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await ct({promptText:await Ce(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:zx,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:Wx(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},Fl=t=>t in kr,Vx=5,Gx=.8,Jx=.5,Zx="Web Mapping Application",Qx="Embeddings",Si=null,$l=null,Ci=null,ki=null,Yx="Build",vr=Object.assign({"./prompts/assessBuildRequest.md":()=>import("./S26SZJC7.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("./SNA7NRRQ.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("./MBT2S4J5.js").then(t=>t.default)}),Xx=Rx.builderMessages,Z=t=>t?.signal?.aborted??!1,ne=(t,e,r)=>Pi(e)?.builderMessages?.[t]??Xx[t],_m=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},eI=async(t,e,r)=>{if(!t)return null;let n=`type:"${Zx}" AND typekeywords:${Qx} AND group:${t}`;return(await Di({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function tI(t,e,r,n){try{let o=await eI(t,e,r);if(!o||Z(n))return null;let s=new hx({id:o.id});return await s.load(),Z(n)?null:await s.fetchData("json")}catch{return null}}var rI=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${Yx} AND group:${t}`;return(await Di({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},nI=async(t,e,r)=>{try{let n=await oc(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}},Tr=(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},wm=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Vi({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},jl=async t=>{if($l){Object.entries($l).forEach(([i,a])=>{kr[i]&&(kr[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=Am(t),n=xm(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await rI(r,e,n),s={};Z(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 nI(i.id,e,n);if(!l||Z(t))return;let{buildSolution:u,params:p}=l;if(typeof u=="object"&&u!==null&&"solution"in u){let w=u.solution;w.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,w.item=i}let f={...a,buildSolution:u};s[c]=Tr(new Vi(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(u),params:p?structuredClone(p):null}),kr[c]={...a,initialTemplate:s[c]}})),$l=s)},bm=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},Am=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},xm=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},oI=async t=>{await Promise.all([vm(t),jl(t)])},Im=async t=>{let e=bm(t);(!Ci||e&&e!==ki)&&(ki=e??ki,Ci=oI(t).catch(r=>{throw Ci=null,ki=null,r})),await Ci};async function vm(t){if(Si)return Si;let e=Am(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=xm(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new fx(n?{url:n}:void 0).load(),Z(t))return null;let o=bm(t)??void 0,s=await tI(e,o,r,t);return Z(t)?null:s?(Si=s.items,Si):null}var sI=()=>Object.entries(kr).map(([t,e])=>`ID: ${t}
350
- Label: ${e.label}
351
- Description: ${e.description}`).join(`
352
-
353
- `),iI=t=>{let e=t?.configurable?.context?.solutionDesignJson;if(typeof e!="string"||!e.trim())return null;try{let r=JSON.parse(e),n=Tr({response:"",...r},{itemId:r?.solution?.itemId??null}),o=Dl.safeParse(n);if(!o.success)return null;let{response:s,...i}=o.data,a=r.templateId,c=typeof a=="string"&&Fl(a)?a:null;return Tr(i,{sourceBuildSolution:r.sourceBuildSolution,templateId:c,params:r.params??null})}catch{return null}},aI=O.Root({...wi(),templateDescription:O({reducer:(t,e)=>typeof e=="string"||e===null?e:t??null,default:()=>null}),currentDesign:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),assessment:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),selectedTemplate:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),updateAssessment:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),existingMatches:O({reducer:(t=[],e)=>e===void 0?t:e??[],default:()=>[]}),continueBuilding:O({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null})}),lI=(t,e)=>{if(Z(e))return{};let r=iI(e),n=r?.templateId??null,o={};return JSON.stringify(t.currentDesign)!==JSON.stringify(r)&&(o.currentDesign=r),n&&t.selectedTemplate!==n&&(o.selectedTemplate=n),o},cI=async(t,e)=>{if(Z(e))return{};await De({text:ne("understandingRequest",e)},e),await Im(e);let r=t.agentExecutionContext.userRequest,n=sI(),o=t.agentExecutionContext.messages.slice(-11),s=await ct({promptText:await Ce(vr,"assessBuildRequest"),modelTier:"advanced",temperature:0,schema:Kx,messages:o,inputVariables:{query:r,availableTemplates:n}}),i=s.matchedTemplates.filter(p=>Fl(p.templateId)),a={...s,matchedTemplates:i},[c,l]=i,u=c&&c.confidence>=Gx&&(l===void 0||c.confidence-l.confidence>=Jx)?c.templateId:null;return{assessment:a,selectedTemplate:u,existingMatches:[],continueBuilding:null}},uI=t=>{let e=t.assessment?.assistantResponse??"";return{outputMessage:e,summary:e,status:"success"}},dI=async(t,e)=>{if(Z(e))return{};let{currentDesign:r}=t;if(!r)return{updateAssessment:{assistantResponse:"",isValidUpdate:!0}};await De({text:ne("understandingRequest",e)},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);return{updateAssessment:await ct({promptText:await Ce(vr,"assessUpdateRequest"),modelTier:"advanced",temperature:0,schema:Ux,messages:o,inputVariables:{currentDesign:JSON.stringify(Ji(r)),query:n}})}},pI=(t,e)=>{let r=t.updateAssessment?.assistantResponse??ne("applyChangeFailed",e);return{outputMessage:r,summary:r,status:"success"}},mI=(t,e)=>{if(Z(e))return{};let{hitlResponse:r}=e.configurable,n="selectTemplate",o=t.assessment?.matchedTemplates.filter(c=>Fl(c.templateId))??[],s=o.map(c=>`${c.templateDescription}`);if(r?.agentId!=="solutionBuilder"||r.id!==n){let c={agentId:"solutionBuilder",id:n,kind:"singleSelection",message:ne("selectTemplatePrompt",e),metadata:[...s]};throw new ts(c)}let i=String(r.payload??""),a=s.findIndex(c=>c===i);return{selectedTemplate:(a>=0?o[a]:void 0)?.templateId??o[0]?.templateId??null}},fI=async(t,e)=>{if(Z(e))return{};await De({text:ne("searchingExistingSolutions",e)},e);let r=t.agentExecutionContext.userRequest,n=Ox(t.agentExecutionContext.messages)||r,o=await vm(e);if(Z(e))return{};if(!o)return console.warn("Solutions Search: failed to load solution embeddings cache; skipping search."),{existingMatches:[]};if(!o.length)return{existingMatches:[]};let[s]=await sm([n]);if(Z(e))return{};let i=o.map(u=>({solution:u,score:im(s,u.embedding)}));i.sort((u,p)=>p.score-u.score);let a=i.slice(0,Vx);if(!a.length)return{existingMatches:[]};let c=a.map(({solution:u})=>`${u.title}
354
- Snippet: ${u.snippet}
355
- Description: ${u.description}`).join(`
356
-
357
- `),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await ct({promptText:await Ce(vr,"findExistingSolution"),modelTier:"fast",temperature:0,schema:qx,messages:l,inputVariables:{query:r,candidates:c}})).matchedTitles.map(u=>a.find(({solution:p})=>p.title===u)).filter(u=>u!==void 0)}},hI=(t,e)=>{if(Z(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?pm(r[0].solution.id):dm(r);let a=ne("existingSolutionMatch",e),c=[ne("continueBuildingYes",e),ne("continueBuildingNo",e)],l={agentId:"solutionBuilder",id:o,kind:"singleSelection",message:a,metadata:c};throw new ts(l)}let s=String(n.payload??"").trim(),i=ne("continueBuildingNo",e);return{continueBuilding:s!==i}},gI=(t,e)=>{let r=ne("continueBuildingDeclined",e);return{outputMessage:r,summary:r,status:"success"}},Tm=async(t,e)=>{if(Z(e))return{};if(await Im(e),Z(e))return{};let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await De({text:ne("creatingDesign",e)},e);let o=po(t.selectedTemplate);if(o?.initialTemplate||(await jl(e),o=po(t.selectedTemplate)),Z(e))return{};if(!o?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let s=Tr(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 ct({promptText:await Ce(vr,"designSolution"),modelTier:"advanced",temperature:0,schema:Dl,messages:i,inputVariables:{currentDesign:JSON.stringify(Gi(s)),templateInstructions:o.instructions,query:n}});if(await De({text:" of design solution 1"},e),Z(e))return{};let{response:c,featureLayer:l,...u}=a,p=Zi(l,s.featureLayer),f=Tr({...u,featureLayer:p},{itemId:s?.solution?.itemId,sourceBuildSolution:s.sourceBuildSolution,templateId:t.selectedTemplate??null,params:s.params??null}),w=new Ei(f,o.initialTemplate);if(!w.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:w.issues,llmResponse:a}),{outputMessage:ne("createDesignFailed",e)};let x=f.sourceBuildSolution,g=wm(f,x);if(!g.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:g.error,llmResponse:a,design:f});let b=ne("createDesignFailed",e);return{outputMessage:b,summary:b,status:"success"}}return Z(e)?{}:(_m(f),{outputMessage:c,summary:c,status:"success",currentDesign:f})},yI=async(t,e)=>{if(Z(e))return{};let{currentDesign:r}=t;if(!r)return Tm(t,e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);await De({text:ne("updatingDesign",e)},e);let s;try{s=await ct({promptText:await Ce(vr,"updateDesign"),modelTier:"advanced",temperature:0,schema:jx,messages:o,inputVariables:{currentDesign:JSON.stringify(Ji(r)),query:n}})}catch(k){console.warn("[SolutionBuilder] updateDesign structured prompt failed:",k);let q=ne("applyChangeFailed",e);return{outputMessage:q,summary:q,status:"success"}}let{response:i,patches:a}=s;if(!a||a.length===0)return{outputMessage:i,summary:i,status:"success"};let c=k=>{try{return JSON.parse(k)}catch{let q=k.replace(/[\u0000-\u001F]/g,ue=>{switch(ue){case"\b":return"\\b";case"\f":return"\\f";case`
358
- `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+ue.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(q)}catch{return k}}},l=[...a.map(k=>({op:k.op,path:k.path.replace(/\/+$/,""),...k.value!=null&&k.value!==""?{value:c(k.value)}:{},...k.from!=null&&k.from!==""?{from:k.from}:{}}))].sort((k,q)=>k.op!=="remove"||q.op!=="remove"?0:q.path.localeCompare(k.path,void 0,{numeric:!0})),u=structuredClone(Gi(r));try{io(u,l,!0)}catch(k){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:k,llmResponse:s,patches:l,patchTarget:u});let q=ne("applyChangeFailed",e);return{outputMessage:q,summary:q,status:"success"}}let p=Tr({response:"",...u},{itemId:r.solution?.itemId??null}),f=Dl.safeParse(p);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:p});let k=ne("applyChangeFailed",e);return{outputMessage:k,summary:k,status:"success"}}let{response:w,featureLayer:x,...g}=f.data,b=Zi(x,r.featureLayer),S=Tr({...g,featureLayer:b},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),h=po(t.selectedTemplate);if(h?.initialTemplate||(await jl(e),h=po(t.selectedTemplate)),Z(e))return{};if(!h?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let I=new Ei(S,h.initialTemplate,!1);if(!I.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:I.issues,llmResponse:s,patchedDesign:S});let k=await Hx({query:n,validationIssues:I.issues,recentMessages:o,fallbackMessage:ne("applyChangeFailed",e),promptModules:vr});return{outputMessage:k,summary:k,status:"success"}}let E=S.sourceBuildSolution,D=wm(S,E);if(!D.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:D.error,llmResponse:s,design:S});let k=ne("applyChangeFailed",e);return{outputMessage:k,summary:k,status:"success"}}return Z(e)?{}:(_m(S),{outputMessage:i,summary:i,status:"success",currentDesign:S})},_I=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",wI=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",bI=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",AI=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",xI=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",II=()=>new ge(aI).addNode("syncCurrentDesignFromContext",lI).addNode("assessBuildRequest",cI).addNode("assessUpdateRequest",dI).addNode("invalidBuildExit",uI).addNode("invalidUpdateExit",pI).addNode("selectTemplateHIL",mI).addNode("findExistingSolutions",fI).addNode("confirmContinueBuildingHIL",hI).addNode("declineContinueBuildingExit",gI).addNode("designSolution",Tm).addNode("updateDesign",yI).addEdge(he,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",_I,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",wI,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",bI,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",V).addEdge("invalidUpdateExit",V).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",AI,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",xI,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",V).addEdge("designSolution",V).addEdge("updateDesign",V);await Ce(vr,"description");var vI=v.object({tool:v.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:v.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:v.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),Oi=t=>t?.signal?.aborted??!1,zl=Object.assign({"./prompts/assistantResponse.md":()=>import("./4L7TJNAM.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)}),TI=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}},Ul=(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)},Sm=O.Root({...wi(),selectedTool:O({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:O({reducer:(t,e)=>e??null,default:()=>null})}),SI=async(t,e)=>{if(Oi(e))return{};let r=Pi(e);await De({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=TI(e),a=await Ce(zl,"classifyIntent"),c=await ct({promptText:a,modelTier:"advanced",temperature:0,schema:vI,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},CI=async(t,e)=>{if(Oi(e))return{};let r=await Tx().compile().invoke(t,e);return Ul(e,"explorer"),r},kI=async(t,e)=>{if(Oi(e))return{};let r=await II().compile().invoke(t,e);return Ul(e,"builder"),r},EI=async(t,e)=>{if(Oi(e))return{};let r=Pi(e),n=t.agentExecutionContext.userRequest;await De({text:r?.executingSolutionsAssistantAgent},e);let o=await Ce(zl,"assistantResponse"),s=t.agentExecutionContext.messages.slice(-11),i=await om({promptText:o,modelTier:"advanced",temperature:0,messages:s,inputVariables:{query:n}});return Ul(e,"assistant"),{outputMessage:i,summary:i,status:"success"}},PI=t=>t.selectedTool??"other",OI=()=>new ge(Sm).addNode("classifyIntent",SI).addNode("routeToExplorer",CI).addNode("routeToBuilder",kI).addNode("assistantResponse",EI).addEdge(he,"classifyIntent").addConditionalEdges("classifyIntent",PI,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",V).addEdge("routeToBuilder",V).addEdge("assistantResponse",V),MI=await Ce(zl,"description"),RI={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:MI,createGraph:OI,workspace:Sm},$I="https://links.esri.com/solutions/agol-organizational-account",NI="https://links.esri.com/solutions/configure-assistants",Ll=class extends Xl{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=tc({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=Ql(),this._configContextConsumer=Li({context:rc,subscribe:!0,callback:e=>{e?.portalURL&&(Rl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Li({context:nc,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._responseMetadata=new Map,this._pendingResponseAgent=void 0,this._handleAssistantProcessingFinished=e=>{let r=e;if(r.detail?.finished&&this._chatStartTime!==null){let n=r.detail.agent;this._lastResponseAgent=n,this._pendingResponseAgent=n;let o=sc(this._chatStartTime);this._telemetry?.logEvent({category:ao.ASSISTANT,action:"Chat",dimensions:[n],metrics:[o]}),this._chatStartTime=null}},this.closeAssistant=$i(),this.assistantProcessing=$i(),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),i=this._responseMetadata.get(r.id),a=i?.agent??n??"",c=i?.userMessage??i?.userMessage??s??o??"";this._sendFeedback(r.content,c,r.feedback?.positive?"Good":r.feedback?.positive===!1?"Bad":"N/A",a)}),this.listenOn(window,"clearAssistantConversation",()=>{this._clearConversation()})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_lastTurnAgent:16,_lastResponseAgent: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=gx}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(){Rl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(Rl.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||(gm(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 ut`<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??Ni} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return ut`<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">${Oc(this._translations.noPermissionMessage.replace("{{orgUrl}}",$I).replace("{{configAI}}",NI))}</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)]),ut`<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?ut`${!this._isMobile&&ut`<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:ao.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&&ut`<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??Ni} .suggestedPrompts=${e} @arcgisSubmit=${()=>{this._suggestedPrompts=[],e=[],this._hasInteracted=!0,this._chatStartTime=Date.now(),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail&&console.log("arcgis feedback: ",r.detail)}} @arcgisResponse=${()=>{let r=this._pendingResponseAgent??this._lastResponseAgent;if(r){let n=o=>{if(this._captureResponseMetadata(r)){this._pendingResponseAgent=void 0;return}o<3&&requestAnimationFrame(()=>n(o+1))};requestAnimationFrame(()=>n(1))}this.assistantProcessing.emit(!1)}} ${Yl(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:ao.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=${RI} .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&&ut`<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:ao.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._lastResponseAgent=void 0,this._pendingResponseAgent=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._responseMetadata.clear(),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{}}_captureResponseMetadata(e){let r=Array.from(this._assistantRef.value?.messages||[]);for(let n=r.length-1;n>=0;n--){let o=r[n];if(o.role==="assistant"&&!this._responseMetadata.has(o.id)){let s;for(let i=n-1;i>=0;i--){let a=r[i];if(a.role==="user"){s=a.content;break}}return this._responseMetadata.set(o.id,{agent:e,userMessage:s}),!0}}return!1}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],o=[...r].sort((u,p)=>p.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)}};ec("arcgis-solutions-assistant",Ll);return Ll},"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","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,b)