@esri/solutions-components 5.1.14 → 5.1.16

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 (163) hide show
  1. package/dist/cdn/247Q2TXM.js +2 -0
  2. package/dist/cdn/{VCKCRMSD.js → 2C4JBZR3.js} +1 -1
  3. package/dist/cdn/{VW4UJ7IY.js → 2DTIYSOT.js} +1 -1
  4. package/dist/cdn/{JNQB7T54.js → 2QR2IHMG.js} +1 -1
  5. package/dist/cdn/3ODUV7DM.js +2 -0
  6. package/dist/cdn/{CPWYI2FO.js → 3TZRVL3S.js} +1 -1
  7. package/dist/cdn/{IBSFJBIL.js → 447ZMCY3.js} +1 -1
  8. package/dist/cdn/{XRQNNWH3.js → 4JE4ZZEO.js} +1 -1
  9. package/dist/cdn/4O622WUQ.js +2 -0
  10. package/dist/cdn/4OZKMC4H.js +2 -0
  11. package/dist/cdn/{T6F3TWF6.js → 4RPDNW6C.js} +1 -1
  12. package/dist/cdn/{24U5P7WR.js → 4W4LIIXK.js} +1 -1
  13. package/dist/cdn/{SNRLIWGC.js → 56OXNE5M.js} +1 -1
  14. package/dist/cdn/{5DZ55HIG.js → 5E2X2LIC.js} +1 -1
  15. package/dist/cdn/{XL66TA6C.js → 5LSAVYFC.js} +1 -1
  16. package/dist/cdn/5MVOXMG2.js +2 -0
  17. package/dist/cdn/5QGU6U72.js +2 -0
  18. package/dist/cdn/{KN2PNGQX.js → 6HPH3E35.js} +1 -1
  19. package/dist/cdn/{5AGI2QC2.js → 6IWBGRKB.js} +1 -1
  20. package/dist/cdn/6PKGJDEH.js +2 -0
  21. package/dist/cdn/6TGGKMQB.js +2 -0
  22. package/dist/cdn/{BOA6VQK6.js → 75QFNN26.js} +1 -1
  23. package/dist/cdn/{HB56DBBP.js → 7EKT4XZ2.js} +5 -5
  24. package/dist/cdn/{7MJZYDDW.js → 7FGKODSI.js} +1 -1
  25. package/dist/cdn/{BFYYWPZY.js → 7RX3CC2H.js} +1 -1
  26. package/dist/cdn/{KJTTBON2.js → ACR7LXQM.js} +1 -1
  27. package/dist/cdn/{65VKA5R3.js → AIJ5KNSJ.js} +1 -1
  28. package/dist/cdn/AVMD543K.js +2 -0
  29. package/dist/cdn/{JIOMWIMT.js → B33ONN6M.js} +1 -1
  30. package/dist/cdn/{OZVQRDTO.js → BE4N7HFP.js} +1 -1
  31. package/dist/cdn/{Z4LGN5M5.js → BSPAXBDY.js} +1 -1
  32. package/dist/cdn/{DERWSE25.js → C5IHV5FJ.js} +1 -1
  33. package/dist/cdn/{EV55ZAHX.js → C7D3FPWP.js} +1 -1
  34. package/dist/cdn/{2GBCVJXZ.js → D62YOY7Q.js} +1 -1
  35. package/dist/cdn/{4VUQR74S.js → DCNEGYEC.js} +1 -1
  36. package/dist/cdn/DG2BBLXW.js +2 -0
  37. package/dist/cdn/{7GWFZ23D.js → DTXW7GR2.js} +1 -1
  38. package/dist/cdn/DXWCRPU7.js +2 -0
  39. package/dist/cdn/{ABPXUFXN.js → E7CD7GZL.js} +1 -1
  40. package/dist/cdn/EOMG2X5B.js +357 -0
  41. package/dist/cdn/{O4MNHPWI.js → EWCJJNT5.js} +1 -1
  42. package/dist/cdn/{WQUZG2NJ.js → FILRH4BY.js} +1 -1
  43. package/dist/cdn/{OQMMSCLX.js → FUEOEICW.js} +1 -1
  44. package/dist/cdn/{2CIYQPV2.js → FWRCG7QJ.js} +1 -1
  45. package/dist/cdn/{O62JG2Y6.js → FXGWLBJ7.js} +1 -1
  46. package/dist/cdn/{6MQWDLJ6.js → GMAV5T2N.js} +1 -1
  47. package/dist/cdn/{LGJMYSGU.js → GPODLJUL.js} +1 -1
  48. package/dist/cdn/{CNNBPMQT.js → GRFNUGBT.js} +1 -1
  49. package/dist/cdn/{JXERXJF5.js → GTX5TOX6.js} +1 -1
  50. package/dist/cdn/GWKUM5FJ.js +456 -0
  51. package/dist/cdn/{5TNQ4S67.js → H3GN63Y3.js} +1 -1
  52. package/dist/cdn/{T7JWS4CF.js → HIVXXDHM.js} +1 -1
  53. package/dist/cdn/I4WRVQPK.js +2 -0
  54. package/dist/cdn/{36LRAUE4.js → IPQDASPD.js} +1 -1
  55. package/dist/cdn/{RSPNBIIE.js → IWLPFHJF.js} +1 -1
  56. package/dist/cdn/{ZXHMBCGN.js → J4Y2UUE5.js} +1 -1
  57. package/dist/cdn/{YR6F4HW7.js → JDGAPNOB.js} +1 -1
  58. package/dist/cdn/{7SZY3VBD.js → JMFXUBR7.js} +1 -1
  59. package/dist/cdn/{GNX2VU4F.js → JSKYS7P5.js} +1 -1
  60. package/dist/cdn/{AQ2USXUY.js → JY2FA5F3.js} +1 -1
  61. package/dist/cdn/{TRNQ5OTY.js → JYKJLNCR.js} +1 -1
  62. package/dist/cdn/K5DU5RWF.js +2 -0
  63. package/dist/cdn/{N5DZRJNH.js → KH4ZYXHD.js} +1 -1
  64. package/dist/cdn/{DT7GQICF.js → KMKWVYPI.js} +1 -1
  65. package/dist/cdn/{QPMXVWMP.js → L6LA4X2Q.js} +1 -1
  66. package/dist/cdn/{FTWOLF7Y.js → L76QNBH4.js} +1 -1
  67. package/dist/cdn/{SSNO5VHY.js → LC7635YE.js} +1 -1
  68. package/dist/cdn/{COKMQSEA.js → LEZRHZSL.js} +1 -1
  69. package/dist/cdn/{COEHM4BJ.js → LSPJWXOL.js} +1 -1
  70. package/dist/cdn/{PHGSNNMQ.js → LULZPSZK.js} +1 -1
  71. package/dist/cdn/{5O6E2RIA.js → LVFCQS24.js} +1 -1
  72. package/dist/cdn/{QMUSSZL2.js → M3BC47EX.js} +1 -1
  73. package/dist/cdn/{IYZ2PDYK.js → MD2W2CNY.js} +1 -1
  74. package/dist/cdn/{MECI4R4R.js → MH3W3N6T.js} +3 -3
  75. package/dist/cdn/{XOPNEAS5.js → MIC565TO.js} +1 -1
  76. package/dist/cdn/{FJAUOTG7.js → MKGWQ7ED.js} +1 -1
  77. package/dist/cdn/{XSJOQTEM.js → MTGZHZYF.js} +1 -1
  78. package/dist/cdn/{G2OBSHPX.js → N74SSEHF.js} +1 -1
  79. package/dist/cdn/{KOIHVAUY.js → NLXWDQUL.js} +1 -1
  80. package/dist/cdn/{CDZW34JV.js → NWI63TZX.js} +1 -1
  81. package/dist/cdn/{CAPXLC6T.js → O2Y2MGL7.js} +1 -1
  82. package/dist/cdn/{2A7FDE6T.js → O4Q74CU3.js} +1 -1
  83. package/dist/cdn/{SYHEO472.js → O7KEBYBS.js} +1 -1
  84. package/dist/cdn/PB4KDDNX.js +2 -0
  85. package/dist/cdn/{HW4LYJUR.js → PCRICJQB.js} +1 -1
  86. package/dist/cdn/{53YBLXWP.js → PFGAF7W7.js} +1 -1
  87. package/dist/cdn/{IDJHBEJC.js → PJ556LHC.js} +3 -3
  88. package/dist/cdn/{AONULVO2.js → PRBMUEIU.js} +1 -1
  89. package/dist/cdn/{2WXIVPKA.js → PUBYJMMF.js} +1 -1
  90. package/dist/cdn/Q5ALOX6G.js +2 -0
  91. package/dist/cdn/{FLPXST7W.js → QIYUCOCH.js} +1 -1
  92. package/dist/cdn/{RLDOLDG5.js → QT66ATR6.js} +1 -1
  93. package/dist/cdn/{K3ALRIQF.js → R22ZBXMU.js} +1 -1
  94. package/dist/cdn/{6RHFFYNC.js → RBA5LP53.js} +1 -1
  95. package/dist/cdn/{4M55FA2L.js → RJJEDOA5.js} +1 -1
  96. package/dist/cdn/{3JF7PWPA.js → RTHNTV3C.js} +1 -1
  97. package/dist/cdn/{VQ5ZAQUF.js → RWYVVDWD.js} +1 -1
  98. package/dist/cdn/{RPLXKWJA.js → SWZW76QC.js} +1 -1
  99. package/dist/cdn/{AO7XKW2U.js → SY25U3KI.js} +1 -1
  100. package/dist/cdn/T5RT73MF.js +2 -0
  101. package/dist/cdn/{W6GIBBBE.js → TWELRTPF.js} +1 -1
  102. package/dist/cdn/U3D2IIAX.js +2 -0
  103. package/dist/cdn/UAWJNBXB.js +4 -0
  104. package/dist/cdn/{KF64ALRP.js → ULAU7YYD.js} +1 -1
  105. package/dist/cdn/{VZWYFHPJ.js → UPYHIGTA.js} +1 -1
  106. package/dist/cdn/{VHAXJPRY.js → UR2RYZ4Q.js} +1 -1
  107. package/dist/cdn/{L5DQOHD5.js → V3QY6GGE.js} +1 -1
  108. package/dist/cdn/{YGVATVII.js → VEBARNK2.js} +1 -1
  109. package/dist/cdn/VSTISYVL.js +2 -0
  110. package/dist/cdn/{JMY4B4WQ.js → VT35RTGD.js} +1 -1
  111. package/dist/cdn/{RGOUIRT7.js → WFDP33EC.js} +1 -1
  112. package/dist/cdn/{4QGYS5DL.js → WMY3JAPO.js} +1 -1
  113. package/dist/cdn/{CWW74G2W.js → WNSJ26IM.js} +1 -1
  114. package/dist/cdn/{RI7U6FA5.js → WP3FT4MH.js} +1 -1
  115. package/dist/cdn/{AIUJXRA5.js → WSGJL4QG.js} +1 -1
  116. package/dist/cdn/{WVRDKKBC.js → WWRJFSPK.js} +1 -1
  117. package/dist/cdn/XGF4Z7DL.js +2 -0
  118. package/dist/cdn/{67RAW3TG.js → XTMKQTKS.js} +1 -1
  119. package/dist/cdn/{BDVFJJR4.js → XUQJ6TZ4.js} +1 -1
  120. package/dist/cdn/{RD7MZ7SN.js → XWMICWSU.js} +1 -1
  121. package/dist/cdn/{D4HAXELR.js → XZE3UIAE.js} +1 -1
  122. package/dist/cdn/{5OMXJXRL.js → Y376MZ7V.js} +1 -1
  123. package/dist/cdn/{2ZH3GVSR.js → YGHICFBD.js} +1 -1
  124. package/dist/cdn/{GWLE7PJQ.js → YJCJZHBN.js} +1 -1
  125. package/dist/cdn/{VYOCZUVH.js → YP46NHDO.js} +1 -1
  126. package/dist/cdn/{MQQ2SHRV.js → YSZNDZHZ.js} +1 -1
  127. package/dist/cdn/{P3YHSJCB.js → Z7NC4HTS.js} +1 -1
  128. package/dist/cdn/{5DMFGBJJ.js → ZBXJES7E.js} +1 -1
  129. package/dist/cdn/{5USMP4M7.js → ZZIJOG6A.js} +1 -1
  130. package/dist/cdn/index.js +1 -1
  131. package/dist/chunks/runtime.js +1 -1
  132. package/dist/chunks/solution-builder-assistant.js +2 -2
  133. package/dist/components/create-feature/customElement.js +77 -48
  134. package/dist/components/layer-table/customElement.js +2 -2
  135. package/dist/components/map-card/customElement.js +2 -2
  136. package/dist/components/solutions-deploy-app/customElement.js +3 -3
  137. package/dist/docs/api.json +1 -1
  138. package/dist/docs/docs.json +1 -1
  139. package/dist/docs/web-types.json +1 -1
  140. package/dist/solutions-components_commit.txt +7 -7
  141. package/package.json +9 -7
  142. package/dist/cdn/3TAQSXLA.js +0 -2
  143. package/dist/cdn/4ESJPQUS.js +0 -2
  144. package/dist/cdn/64DMFXX3.js +0 -459
  145. package/dist/cdn/7LP2DUHS.js +0 -2
  146. package/dist/cdn/ACTGIDKO.js +0 -4
  147. package/dist/cdn/BA3J7L5N.js +0 -2
  148. package/dist/cdn/BPHZAC66.js +0 -2
  149. package/dist/cdn/ECJQJ4BY.js +0 -2
  150. package/dist/cdn/F5EJPIW4.js +0 -2
  151. package/dist/cdn/FX2C3BL4.js +0 -2
  152. package/dist/cdn/GEEQWXOZ.js +0 -2
  153. package/dist/cdn/H3QX6XOJ.js +0 -2
  154. package/dist/cdn/JRUIRTL7.js +0 -2
  155. package/dist/cdn/JU2Q5KMI.js +0 -358
  156. package/dist/cdn/NF77ALHM.js +0 -2
  157. package/dist/cdn/OJH4NUGT.js +0 -2
  158. package/dist/cdn/SV2XM7U2.js +0 -2
  159. package/dist/cdn/TTXN5R4E.js +0 -2
  160. package/dist/cdn/VM2LS6TR.js +0 -2
  161. package/dist/cdn/VNWIFVKC.js +0 -2
  162. package/dist/cdn/VWNMKVMJ.js +0 -2
  163. package/dist/cdn/X3YWKGD7.js +0 -2
@@ -0,0 +1,357 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
+ import{d as Ro,e as Li,f as Lu,g as ju,h as Du}from"./NQH7ZZWD.js";import{a as Nu}from"./MHMM4RFR.js";import{a as um,b as dm,c as pm,f as dl,g as pl,j as fm}from"./2QR2IHMG.js";import b from"./GRFNUGBT.js";import a from"./MIC565TO.js";import{b as jf,c as Df}from"./2B4SGB3I.js";import{b as vu}from"./RLSY4VUQ.js";import"./SY25U3KI.js";import{a as Lf}from"./2DTIYSOT.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as Ou,Aa as nm,Ba as om,Da as sm,Ea as al,Eb as Ni,Fa as ll,Ga as im,Ha as am,Ia as Po,Ib as cl,J as Uf,Ja as lm,Jb as ul,K as Ke,Ka as p,Kb as He,L as gn,La as H,M as qf,Ma as Ru,N as Wf,Na as Mu,O as Qa,Oa as $u,P as Su,Q as Tu,R as Ya,S as Mi,T as re,U as Eu,V as Y,W as Ar,X as xr,Y as el,Ya as B,Z as Kf,_ as Hf,a as We,aa as tl,b as le,ba as Vf,ca as Gf,da as $i,ea as rl,fa as Jf,g as Bf,ga as Zf,ha as Xf,ia as Qf,j as Gt,ja as nl,k as hn,ka as Yf,la as yn,ma as ku,na as ol,oa as K,pa as T,qa as _n,ra as vr,rb as cm,s as Za,sa as em,ta as sl,ua as tm,va as rm,wa as il,xa as Cu,y as Xa,ya as Co,za as Pu}from"./GWKUM5FJ.js";import"./TEHBW75B.js";import"./IWLPFHJF.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./IPQDASPD.js";import"./VT35RTGD.js";import"./RWYVVDWD.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./6ERMTA3J.js";import"./GF4QELNV.js";import{l as Ff,v as Iu}from"./4OZKMC4H.js";import"./PY6RTQDR.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as Nf}from"./L6LA4X2Q.js";import{F as Rf,G as Mf,H as $f,L as xu,h as Tf,i as br,k as Ef,l as bu,q as Au,t as Of,w as kf,x as Cf,y as Pf}from"./T3EPRHTT.js";import{b as If,c as wu,d as Sf}from"./EXBEKVP5.js";export default $arcgis.t(([hf,GY,ZY,tw,VE,GE,JE,iO,r7,o7,fne,CR,bw,Io,Aw,Jp,Ew,,uO,{addressToLocations:dO},pO,fO,Ow,{createRenderer:mO},{getSchemesByTag:hO,getSchemes:gO},{getBackgroundColorTheme:xw},{createAgeRenderer:yO,createContinuousRenderer:_O},{getSchemesByTag:sf},{createContinuousRenderer:wO},{createRenderer:bO},{getSchemesByTag:AO},{createRenderer:xO},{getSchemesByTag:vO},{createRenderer:IO},{getSchemesByTag:SO},{createRenderer:TO},{getSchemesByTag:EO},{createAgeRenderer:OO,createContinuousRenderer:kO},{createRenderer:CO},{getSchemesByTag:PO},RO,kw,Cw,{formatDateOnly:MO,convertDateFormatToIntlOptions:Gc,formatTimeOnly:$O,formatDate:vw},NO,LO,jO,DO,FO,Pw,,{fetchKnowledgeGraph:Iw,executeQueryStreaming:zO,executeSearchStreaming:BO},UO,{getBindParametersFromCypherQuery:qO},,,,,,,,,,,,,,,,,,,,,,,,,mre,gre,,,,,,,,,,,,,KR,HR,{r:zf},{r:Ri}])=>{var bh=If((te,Ol)=>{"use strict";if(typeof Ol<"u"&&Ol!==globalThis.module&&typeof te<"u"&&Ol.exports===te){Object.defineProperty(te,"__esModule",{value:!0}),te.findX509Credential=te.rememberX509Credential=te.findX509OAuthError=te.rememberX509OAuthError=te.isApprovedX509Client=te.markApprovedX509Client=te.isRetryableX509IssuerError=te.markRetryableX509IssuerError=te.isTransientX509ConnectionError=te.markTransientX509ConnectionError=te.rememberRegisteredX509Transport=te.findRegisteredX509Transport=void 0;let t=new WeakMap,e=new WeakSet,r=new WeakSet,n=new WeakSet,o=new WeakMap,s=new WeakMap;te.findRegisteredX509Transport=WeakMap.prototype.get.bind(t),te.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(t),te.markTransientX509ConnectionError=WeakSet.prototype.add.bind(e),te.isTransientX509ConnectionError=WeakSet.prototype.has.bind(e),te.markRetryableX509IssuerError=WeakSet.prototype.add.bind(r),te.isRetryableX509IssuerError=WeakSet.prototype.has.bind(r),te.markApprovedX509Client=WeakSet.prototype.add.bind(n),te.isApprovedX509Client=WeakSet.prototype.has.bind(n),te.rememberX509OAuthError=WeakMap.prototype.set.bind(o),te.findX509OAuthError=WeakMap.prototype.get.bind(o),te.rememberX509Credential=WeakMap.prototype.set.bind(s),te.findX509Credential=WeakMap.prototype.get.bind(s)}});var X_=If(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.toResponseInputItems=IE;Fc.toResponseInputItem=Z_;function IE(t){let e=[];for(let r of t){let n=Z_(r);n&&e.push(n)}return e}function Z_(t){switch(t.type){case"message":{if(t.role!=="assistant"||!("id"in t)||!Array.isArray(t.content))return dn(t);let e=t.content.map(r=>{if((r.type==="output_text"||r.type==="refusal")&&"parsed"in r){let{parsed:n,...o}=r;return o}return r});return e.every((r,n)=>r===t.content[n])?dn(t):{...dn(t),content:e}}case"function_call":{let e=dn(t);if(!("parsed_arguments"in e))return e;let{parsed_arguments:r,...n}=e;return n}case"additional_tools":return t.role!=="developer"?null:dn(t);case"shell_call_output":{let e=t.output.map(r=>dn(r));return{...dn(t),output:e}}case"computer_call_output":{let{created_by:e,...r}=t;return r.status==="failed"?null:r}case"custom_tool_call_output":{if("status"in t&&t.status!=="completed")return null;let{created_by:e,status:r,...n}=t;return n}case"apply_patch_call":case"apply_patch_call_output":case"code_interpreter_call":case"compaction":case"compaction_trigger":case"computer_call":case"configuration_update":case"custom_tool_call":case"file_search_call":case"function_call_output":case"image_generation_call":case"item_reference":case"local_shell_call":case"local_shell_call_output":case"mcp_approval_request":case"mcp_approval_response":case"mcp_call":case"mcp_list_tools":case"program":case"program_output":case"reasoning":case"shell_call":case"tool_search_call":case"tool_search_output":case"web_search_call":case null:case void 0:return dn(t);default:return SE(t)}}function dn(t){if(!("created_by"in t))return t;let{created_by:e,...r}=t;return r}function SE(t){let e=t.type;throw new TypeError(`Unsupported response item type: ${String(e)}`)}});var ji=class extends Pf{constructor(e){if(super(e),this.it=bu,e.type!==kf.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===bu||e==null)return this._t=void 0,this.it=e;if(e===Ef)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:[]}}};ji.directiveName="unsafeHTML",ji.resultType=1;var mm=Cf(ji);async function Fu(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 Gf(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var fe=async(t,e)=>{await Fu("trace_message",t,e)},Ve=async(t,e)=>{await Fu("graph_ux_suggestion",t,e)};var fb={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},langsmith:{package:"@langchain/openai",className:"ChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},jM=Object.keys(fb);var Wu=Symbol.for("langgraph-zod");Wu in globalThis||(globalThis[Wu]=new WeakSet);function gm(t){let e=globalThis[Wu];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return ul(r,{jsonSchemaExtra:n})},reducer(n,o){return ul(r,{default:ol(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{gm(T.ZodType.prototype),gm(p.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 ym=class extends Zf{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=ol(t);n!=null&&(r.default=n)}return super.add(t,...e)}},yb=new ym(cl);var Cb=T.function().args(T.custom()).returns(T.union([T.boolean(),T.promise(T.boolean())])),Pb=T.function().args(T.custom(),T.custom(),T.custom()).returns(T.union([T.string(),T.promise(T.string())])),Rb=["approve","edit","reject"],Mb=T.enum(Rb),$b=T.object({allowedDecisions:T.array(Mb),description:T.union([T.string(),Pb]).optional(),argsSchema:T.record(T.any()).optional(),when:Cb.optional()}),HL=T.object({interruptOn:T.record(T.union([T.boolean(),$b])).optional(),descriptionPrefix:T.string().default("Tool execution requires approval")});var gl=T.object({maxRetries:T.number().min(0).default(2),retryOn:T.union([T.function().args(T.instanceof(Error)).returns(T.boolean()),T.array(T.custom())]).default(()=>t=>qf(t)??!0),backoffFactor:T.number().min(0).default(2),initialDelayMs:T.number().min(0).default(1e3),maxDelayMs:T.number().min(0).default(6e4),jitter:T.boolean().default(!0)});var jb=`<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 Db=T.function().args(T.array(T.custom())).returns(T.union([T.number(),T.promise(T.number())])),Ju=T.object({fraction:T.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:T.number().positive("Tokens must be greater than 0").optional(),messages:T.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"}),km=T.object({fraction:T.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:T.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:T.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"}),mj=T.object({model:T.custom(),trigger:T.union([Ju,T.array(Ju)]).optional(),keep:km.optional(),tokenCounter:Db.optional(),summaryPrompt:T.string().default(jb),trimTokensToSummarize:T.number().optional(),summaryPrefix:T.string().optional(),maxTokensBeforeSummary:T.number().optional(),messagesToKeep:T.number().optional()});var Tj=T.object({model:T.string().or(T.instanceof(tm)).optional(),systemPrompt:T.string().optional(),maxTools:T.number().optional(),alwaysInclude:T.array(T.string()).optional()});var Mj=T.object({applyToInput:T.boolean().optional(),applyToOutput:T.boolean().optional(),applyToToolResults:T.boolean().optional()});var Dj=T.object({rules:T.record(T.string(),T.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Fb=["continue","error","end"],zb="continue";var Bb=T.enum(Fb).default(zb);T.object({toolName:T.string().optional(),threadLimit:T.number().optional(),runLimit:T.number().optional(),exitBehavior:Bb});var Jj=T.object({threadToolCallCount:T.record(T.string(),T.number()).default({}),runToolCallCount:T.record(T.string(),T.number()).default({})});var Ub=T.enum(["pending","in_progress","completed"]).describe("Status of the todo"),qb=T.object({content:T.string().describe("Content of the todo item"),status:Ub}),nD=T.object({todos:T.array(qb).default([])});var lD=T.object({threadLimit:T.number().optional(),runLimit:T.number().optional(),exitBehavior:T.enum(["error","end"]).optional()}),cD=T.object({threadModelCallCount:T.number().default(0),runModelCallCount:T.number().default(0)});var AD=T.object({onFailure:T.union([T.literal("error"),T.literal("continue"),T.function().args(T.instanceof(Error)).returns(T.string())]).default("continue")}).merge(gl);var kD=T.object({tools:T.array(T.union([T.custom(),T.custom(),T.string()])).optional(),onFailure:T.union([T.literal("error"),T.literal("continue"),T.literal("raise"),T.literal("return_message"),T.function().args(T.instanceof(Error)).returns(T.string())]).default("continue")}).merge(gl);var ZD=T.object({enableCaching:T.boolean().optional(),ttl:T.enum(["5m","1h"]).optional(),minMessagesToCache:T.number().optional(),unsupportedModelBehavior:T.enum(["ignore","warn","raise"]).optional()});var eF=T.object({enableCaching:T.boolean().optional(),ttl:T.enum(["5m","1h"]).optional(),minMessagesToCache:T.number().optional(),unsupportedModelBehavior:T.enum(["ignore","warn","raise"]).optional()});function Di(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 E(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 u(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 _t=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return _t=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 Jt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Fi=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e="cause"in t,r=new Error(t.message,e?{cause:t.cause}:{});return t.stack&&(r.stack=t.stack),e&&!Object.prototype.hasOwnProperty.call(r,"cause")&&(r.cause=t.cause),t.name&&(r.name=t.name),r}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var A=class extends Error{},ee=class t extends A{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 st({message:n,cause:Fi(r)});let s=r?.error;return e===400?new Nt(e,s,n,o):e===401?new Sr(e,s,n,o):e===403?new Tr(e,s,n,o):e===404?new Er(e,s,n,o):e===409?new Or(e,s,n,o):e===422?new kr(e,s,n,o):e===429?new Cr(e,s,n,o):e>=500?new Pr(e,s,n,o):new t(e,s,n,o)}},ie=class extends ee{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},st=class extends ee{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},ce=class extends st{constructor({message:e}={}){super({message:e??"Request timed out."})}},Nt=class extends ee{},Sr=class extends ee{},Tr=class extends ee{},Er=class extends ee{},Or=class extends ee{},kr=class extends ee{},Cr=class extends ee{},Pr=class extends ee{},Rr=class extends A{constructor(){super("Could not parse response content as the length limit was reached")}},Mr=class extends A{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ge=class extends Error{constructor(e){super(e)}},it=class extends ee{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}},bn=class extends A{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var TA=/^[a-z][a-z0-9+.-]*:/i,Rm=t=>TA.test(t),Le=t=>(Le=Array.isArray,Le(t)),Mm=Le;function zi(t){return typeof t!="object"?{}:t??{}}function Qu(t){if(!t)return!0;for(let e in t)return!1;return!0}function N(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Te(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Yu=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new A(`${t} must be an integer`);if(e<0)throw new A(`${t} must be a positive integer`);return e};var $m=t=>{try{return JSON.parse(t)}catch{return}};var $o=(t,...e)=>new Promise((r,n)=>{let o=[...new Set(e.filter(d=>d!=null))],s,i=!1,a=()=>{for(let d of o)try{d.removeEventListener("abort",c)}catch{}},l=d=>{i||(i=!0,s!==void 0&&(clearTimeout(s),s=void 0),a(),d())},c=()=>{l(()=>n())};if(o.some(d=>d.aborted)){c();return}s=setTimeout(()=>{l(r)},t);for(let d of o){if(i)break;try{d.addEventListener("abort",c,{once:!0})}catch(m){l(()=>n(m))}}o.some(d=>d.aborted)&&c()});var No=globalThis,yl=typeof No.FinalizationRegistry=="function"?new No.FinalizationRegistry(t=>{try{t()}catch{}}):void 0,Nm=new WeakMap,Bi=new WeakMap;function EA(t,e,r){let n=Bi.get(t);if(!n){let s=new Set,i=()=>{Bi.delete(t);for(let a of s)r.unregister(a),a.deref()?.();s.clear()};n={callbacks:s,abort:i},t.addEventListener("abort",i,{once:!0}),Bi.set(t,n)}let o=n;return o.callbacks.add(e),()=>{o.callbacks.delete(e),r.unregister(e),o.callbacks.size===0&&(Bi.get(t)===o&&Bi.delete(t),t.removeEventListener("abort",o.abort))}}function OA(t,e,r){t.addEventListener("abort",()=>e.deref()?.delete(r),{once:!0})}function ed(t,e,r){if(typeof No.WeakRef=="function"&&yl&&!r.aborted){let n=Nm.get(t);n||(n=new Set,Nm.set(t,n)),n.add(e),OA(r,new No.WeakRef(n),e)}}function Lm(t,e,r){if(t.aborted)return e(),()=>{};if(typeof No.WeakRef!="function"||!yl)return t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e);let n=new No.WeakRef(e),o=EA(t,n,yl);return yl.register(e,o,n),ed(r,e,r),o}function Ui(){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 td(...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 qi(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return td({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function _l(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 Zt(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 Dm;function Me(t){let e;return(Dm??(e=new globalThis.TextEncoder,Dm=e.encode.bind(e)))(t)}var Fm;function zm(t){let e;return(Fm??(e=new globalThis.TextDecoder,Fm=e.decode.bind(e)))(t)}var rd,_e,ae,me,Lt,An,Um,Wi=64*1024,xn=class{constructor(){rd.add(this),_e.set(this,void 0),ae.set(this,void 0),me.set(this,void 0),Lt.set(this,void 0),An.set(this,void 0),E(this,_e,new Uint8Array,"f"),E(this,ae,0,"f"),E(this,me,0,"f"),E(this,Lt,0,"f"),E(this,An,!1,"f")}decode(e){if(e==null)return[];let r;if(e instanceof ArrayBuffer?r=new Uint8Array(e):typeof e=="string"?r=Me(e):r=e,r.length===0)return[];if(u(this,An,"f")&&(E(this,An,!1,"f"),r[0]===10&&(r=r.subarray(1)),r.length===0))return[];u(this,rd,"m",Um).call(this,r);let n=[],o;for(;(o=kA(u(this,_e,"f"),u(this,Lt,"f"),u(this,me,"f")))!=null;){let s=zm(u(this,_e,"f").subarray(u(this,ae,"f"),o.preceding));n.push(s),E(this,ae,o.index,"f"),o.carriage&&(u(this,ae,"f")<u(this,me,"f")&&u(this,_e,"f")[u(this,ae,"f")]===10?E(this,ae,u(this,ae,"f")+1,"f"):u(this,ae,"f")===u(this,me,"f")&&E(this,An,!0,"f")),E(this,Lt,u(this,ae,"f"),"f")}if(E(this,Lt,u(this,me,"f"),"f"),u(this,ae,"f")===u(this,me,"f"))E(this,ae,0,"f"),E(this,me,0,"f"),E(this,Lt,0,"f"),u(this,_e,"f").length>Wi&&E(this,_e,new Uint8Array,"f");else if(n.length>0&&u(this,_e,"f").length>Wi){let s=u(this,me,"f")-u(this,ae,"f");if(s<=Wi||u(this,_e,"f").length>s*4){let i=s<=Wi?Math.min(Math.max(s*2,256),Wi):s*2,a=new Uint8Array(i);a.set(u(this,_e,"f").subarray(u(this,ae,"f"),u(this,me,"f"))),E(this,_e,a,"f"),E(this,ae,0,"f"),E(this,me,s,"f"),E(this,Lt,s,"f")}}return n}flush(){return E(this,An,!1,"f"),u(this,ae,"f")===u(this,me,"f")?[]:this.decode(`
39
+ `)}};_e=new WeakMap,ae=new WeakMap,me=new WeakMap,Lt=new WeakMap,An=new WeakMap,rd=new WeakSet,Um=function(e){if(u(this,me,"f")+e.length>u(this,_e,"f").length){let r=u(this,me,"f")-u(this,ae,"f");if(u(this,ae,"f")>=u(this,_e,"f").length/2&&r+e.length<=u(this,_e,"f").length)u(this,_e,"f").copyWithin(0,u(this,ae,"f"),u(this,me,"f"));else{let n=Math.max(u(this,_e,"f").length*2,r+e.length,256),o=new Uint8Array(n);o.set(u(this,_e,"f").subarray(u(this,ae,"f"),u(this,me,"f"))),E(this,_e,o,"f")}E(this,Lt,u(this,Lt,"f")-u(this,ae,"f"),"f"),E(this,me,r,"f"),E(this,ae,0,"f")}u(this,_e,"f").set(e,u(this,me,"f")),E(this,me,u(this,me,"f")+e.length,"f")};xn.NEWLINE_CHARS=new Set([`
40
+ `,"\r"]);xn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function kA(t,e,r){for(let s=e;s<r;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function qm(t){for(let e=0;e<t.length-1;e++){let r=Bm(t,e);if(r>0){let n=e+r,o=Bm(t,n);if(o>0)return n+o}}return-1}function Bm(t,e){return t[e]===10?1:t[e]===13?t[e+1]===10?2:1:0}var bl={off:0,error:200,warn:300,info:400,debug:500},nd=(t,e,r)=>{if(t){if(N(bl,t))return t;he(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(bl))}`)}};function Ki(){}function wl(t,e,r){return!e||bl[t]>bl[r]?Ki:e[t].bind(e)}var CA={error:Ki,warn:Ki,info:Ki,debug:Ki},Wm=new WeakMap;function he(t){let e=t.logger,r=t.logLevel??"off";if(!e)return CA;let n=Wm.get(e);if(n&&n[0]===r)return n[1];let o={error:wl("error",e,r),warn:wl("warn",e,r),info:wl("info",e,r),debug:wl("debug",e,r)};return Wm.set(e,[r,o]),o}var Km=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","xamzsecuritytoken","xamzsignature","xamzcredential"]);function Hi(t){let e=t.toLowerCase().replace(/[-_]/gu,"");return Km.has(e)||Km.has(e.replace(/^x/u,""))}var PA=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"]);function xl(t){return PA.has(t.toLowerCase().replace(/_/gu,"-"))||Hi(t)}function Al(t){let e=new URL(t);e.username="",e.password="",e.hash="";for(let r of e.searchParams.keys())Hi(r)&&e.searchParams.set(r,"***");return e.href}var Xt=t=>{if(t.options){if(t.options={...t.options},delete t.options.headers,t.options.path){let e=t.options.path,r=new URL(Al(new URL(e,"https://redacted.invalid").href));t.options.path=r.origin==="https://redacted.invalid"?`${e.startsWith("/")?"/":""}${r.pathname.slice(1)}${r.search}`:r.href}t.options.query&&(t.options.query=Object.fromEntries(Object.entries(t.options.query).map(([e,r])=>[e,Hi(e)?"***":r])))}return t.url&&(t.url=Al(t.url)),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,xl(e)?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t};var vl,Il,Sl,od;function RA(t){return!(t instanceof ee)&&Jt(t)}function Hm(){let t=[],e=0,r=!1;return{get length(){return t.length-e},get canceled(){return r},enqueue(n){r||t.push(n)},dequeue(){if(e===t.length)return;let n=t[e];return t[e]=void 0,e+=1,e===t.length?(t=[],e=0):e>=1024&&e*2>=t.length&&(t=t.slice(e),e=0),n},cancel(){r=!0,t.length=0,e=0}}}var Je=class t{constructor(e,r,n){vl.add(this),Il.set(this,void 0),Sl.set(this,!1),this.iterator=e,this.controller=r,E(this,Il,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,i=n?he(n):console;async function*a(){if(s)throw new A("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1,c=!1,d=$A(e,r),m=d.return.bind(d);d.return=f=>(c||r.abort(),m(f));try{for await(let f of d){if(f.data==="[DONE]"){c=!0;break}if(f.event===null||!f.event.startsWith("thread.")){let g;try{g=JSON.parse(f.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(f.event==="error")throw new ee(void 0,g?.error??g,void 0,e.headers);if(g&&g.error)throw new ee(void 0,g.error,void 0,e.headers);yield o?{event:f.event,data:g}:g}else{let g;try{g=JSON.parse(f.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:f.event,data:g}}}l=!0}catch(f){if(c||RA(f)||r.signal.aborted&&f===r.signal.reason)return;throw f}finally{l||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let a=new xn,l=e.getReader(),c=!1,d,m=()=>{d??(d=l.cancel()),d.catch(()=>{})};r.signal.addEventListener("abort",m,{once:!0});try{if(r.signal.aborted){m();return}for(;;){let{value:f,done:g}=await l.read();if(g){c=!0;break}if(r.signal.aborted)return;for(let b of a.decode(f)){if(r.signal.aborted)return;yield b}}if(r.signal.aborted)return;for(let f of a.flush()){if(r.signal.aborted)return;yield f}}finally{r.signal.removeEventListener("abort",m),c||m(),l.releaseLock()}}async function*i(){if(o)throw new A("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of s())if(l){let c;try{c=JSON.parse(l)}catch(d){throw d instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):d}yield c}a=!0}catch(l){if(r.signal.aborted||Jt(l))return;throw l}finally{a||r.abort()}}return new t(i,r,n)}[(Il=new WeakMap,Sl=new WeakMap,vl=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller:e}=this,r=Hm(),n=Hm(),o=this.iterator(),s=a=>({next:()=>{if(a.canceled)return Promise.resolve({value:void 0,done:!0});if(a.length===0){let l=o.next();r.enqueue(l),n.enqueue(l)}return a.dequeue()},return:async()=>(a.canceled||(a.cancel(),r.canceled&&n.canceled&&await u(this,vl,"m",od).call(this,o,e)),{value:void 0,done:!0})}),i=a=>{let l=new t(()=>s(a),e,u(this,Il,"f"));return E(l,Sl,!0,"f"),l};return[i(r),i(n)]}toReadableStream(){let{controller:e}=this,r,n,o=()=>n??(n=u(this,vl,"m",od).call(this,r,e));return td({start:async()=>{r=this[Symbol.asyncIterator]()},async pull(s){try{let{value:i,done:a}=await r.next();if(a)return s.close();let l=Me(JSON.stringify(i)+`
41
+ `);s.enqueue(l)}catch(i){s.error(i),o().catch(()=>{})}},cancel:o})}};od=async function(e,r){let n=e.return;n&&(u(this,Sl,"f")||r.abort(),await Reflect.apply(n,e,[]))};function MA(t,e){let r=typeof t.getReader=="function"?t.getReader():void 0,n=r?{next:()=>r.read(),return:()=>r.cancel()}:_l(t)[Symbol.asyncIterator](),o={value:void 0,done:!0},s=!1,i=!1,a,l,c=()=>new Promise(g=>{l=g}),d=()=>{if(i||s)return a;i=!0;try{a=Promise.resolve(n.return?.())}catch(g){a=Promise.reject(g)}return a.catch(()=>{}),a},m=()=>{queueMicrotask(()=>{l?.(),d()})};return{iterator:{async next(){if(e.aborted)return o;let g=c().then(()=>o);try{let b=await Promise.race([n.next(),g]);return e.aborted?o:b.done?(s=!0,o):{value:b.value,done:!1}}catch(b){if(e.aborted&&(Jt(b)||b===e.reason))return o;throw b}finally{l=void 0}},async return(){let g=d();if(g&&!e.aborted){let b=c();try{e.aborted||await Promise.race([g,b])}finally{l=void 0}}return o},[Symbol.asyncIterator](){return this}},start(){e.addEventListener("abort",m,{once:!0}),e.aborted&&m()},async cleanup(g){let b;try{e.removeEventListener("abort",m)}catch(_){b=_}if(!s){let _=d();if(_&&!g&&!e.aborted)try{await _}catch(x){b??(b=x)}}if(r)try{r.releaseLock()}catch(_){b??(b=_)}if(b!==void 0&&!g&&!e.aborted)throw b}}}async function*$A(t,e){if(!t.body)throw e.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new A("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 A("Attempted to iterate over a response with no body");let r=new sd,n=new xn,{signal:o}=e,s=MA(t.body,o),i=!1;try{s.start();for await(let l of LA(s.iterator)){if(o.aborted)return;for(let c of n.decode(l)){if(o.aborted)return;let d=r.decode(c);d&&(yield d)}}if(o.aborted)return;for(let l of n.flush()){if(o.aborted)return;let c=r.decode(l);c&&(yield c)}if(o.aborted)return;let a=r.flush();a&&(yield a)}catch(a){if(i=!0,!o.aborted||!Jt(a)&&a!==o.reason)throw a}finally{await s.cleanup(i)}}var NA=3;async function*LA(t){let e=new Uint8Array,r=0,n=0,o=0;for await(let s of t){if(s==null)continue;let i;if(s instanceof ArrayBuffer?i=new Uint8Array(s):typeof s=="string"?i=Me(s):i=s,n+i.length>e.length){let l=n-r;if(r>=e.length/2&&l+i.length<=e.length)e.copyWithin(0,r,n);else{let c=new Uint8Array(Math.max(e.length*2,l+i.length));c.set(e.subarray(r,n)),e=c}o-=r,r=0,n=l}e.set(i,n),n+=i.length;let a;for(;(a=qm(e.subarray(o,n)))!==-1;)a+=o,yield e.slice(r,a),r=a,o=r;o=Math.max(r,n-NA)}n>r&&(yield e.slice(r,n))}var sd=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.slice(0,-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]=jA(e,":"),o=n;return o.startsWith(" ")&&(o=o.slice(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}flush(){return this.decode("")}};function jA(t,e){let r=t.indexOf(e);return r!==-1?[t.slice(0,r),e,t.slice(r+e.length)]:[t,"",""]}async function vn(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return he(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):Je.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(l?.includes("application/json")||l?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.text();if(!f)return;let g=JSON.parse(f);return Vi(g,r)}return await r.text()})().catch(a=>{throw DA(a,e.controller.signal)});return he(t).debug(`[${n}] response parsed`,Xt({retryOfRequestLogID:o,url:r.url,status:r.status,body:i,durationMs:Date.now()-s})),i}function DA(t,e){if(!e.aborted||t!==e.reason||Jt(t))return t;let r="This operation was aborted",n=globalThis.DOMException;return typeof n=="function"?new n(r,"AbortError"):Object.assign(new Error(r),{name:"AbortError"})}function Vi(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 $r="7.17.0";var Zm=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function FA(){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 zA=()=>{let t=FA();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$r,"X-Stainless-OS":Gm(Deno.build.os),"X-Stainless-Arch":Vm(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":$r,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$r,"X-Stainless-OS":Gm(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Vm(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=BA();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$r,"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":$r,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function BA(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/\bEdg(?:e|A|iOS)?\b(?:\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 Vm=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Gm=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"),Jm,Xm=()=>Jm??(Jm=zA());var Gi=new WeakMap;function Qm(t,e){let r=Gi.get(t);return r||(r=new Set,Gi.set(t,r)),r.add(e),()=>{let n=Gi.get(t);n&&(n.delete(e),n.size===0&&Gi.delete(t))}}var Ym=({headers:t,body:e})=>{let r=typeof e=="object"&&e!==null?Gi.get(e):void 0,n;if(!r||r.size===0)n=JSON.stringify(e);else{let o=[...r];n=JSON.stringify(e,function(s,i){let a=i;for(let l of o){let c=l.value(this,s,a);c!==void 0&&(a=c)}return a});for(let s of o)s.complete()}return{bodyHeaders:{"content-type":"application/json"},body:n}};var id="RFC3986",ad=String,ld={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ad},eh="RFC1738";var th,rh=(t,e)=>{let r=th??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return th=r,r(t,e)};var jt=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var cd=1024,nh=(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,a=>"%26%23"+Number.parseInt(a.slice(2),16)+"%3B");let i="";for(let a=0;a<s.length;){let l=Math.min((Math.floor(a/cd)+1)*cd,s.length);l<s.length&&s.codePointAt(l-1)>65535&&(l+=1);let c=s.length>=cd?s.slice(a,l):s,d=[];for(let m=0;m<c.length;++m){let f=c.charCodeAt(m);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||o===eh&&(f===40||f===41)){d[d.length]=c.charAt(m);continue}if(f<128){d[d.length]=jt[f];continue}if(f<2048){d[d.length]=jt[192|f>>6]+jt[128|f&63];continue}if(f<55296||f>=57344){d[d.length]=jt[224|f>>12]+jt[128|f>>6&63]+jt[128|f&63];continue}m+=1,f=65536+((f&1023)<<10|c.charCodeAt(m)&1023),d[d.length]=jt[240|f>>18]+jt[128|f>>12&63]+jt[128|f>>6&63]+jt[128|f&63]}i+=d.join(""),a=l}return i};function oh(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ud(t,e){if(Le(t)){let r=[];for(let n of t)r.push(e(n));return r}return e(t)}var ih={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},ah=function(e,r){Array.prototype.push.apply(e,Le(r)?r:[r])},sh,Ie={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:nh,encodeValuesOnly:!1,format:id,formatter:ad,indices:!1,serializeDate(t){return(sh??(sh=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function qA(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var dd={};function lh(t,e,r,n,o,s,i,a,l,c,d,m,f,g,b,_,x,O){let y=t,S=O,I=0,R=!1;for(;(S=S.get(dd))!==void 0&&!R;){let M=S.get(t);if(I+=1,M!==void 0){if(M===I)throw new RangeError("Cyclic object value");R=!0}S.get(dd)===void 0&&(I=0)}if(typeof c=="function"?y=c(e,y):y instanceof Date?y=f?.(y):r==="comma"&&Le(y)&&(y=ud(y,M=>M instanceof Date?f?.(M):M)),y===null){if(s)return l&&!_?l(e,Ie.encoder,x,"key",g):e;y=""}if(qA(y)||oh(y)){if(l){let M=_?e:l(e,Ie.encoder,x,"key",g);return[b?.(M)+"="+b?.(l(y,Ie.encoder,x,"value",g))]}return[b?.(e)+"="+b?.(String(y))]}let k=[];if(y===void 0)return k;let D;if(r==="comma"&&Le(y))_&&l&&(y=ud(y,l)),D=[{value:y.length>0?y.join(",")||null:void 0}];else if(Le(c))D=c;else{let M=Object.keys(y);d&&M.sort(d),D=M}let $=a?String(e).replace(/\./g,"%2E"):String(e),j=n&&Le(y)&&y.length===1?$+"[]":$;if(o&&Le(y)&&y.length===0)return j+"[]";for(let M of D){let C=typeof M=="object"&&M.value!==void 0?M.value:y[M];if(i&&C===null)continue;let L=m&&a?M.replace(/\./g,"%2E"):M,z;Le(y)?z=typeof r=="function"?r(j,L):j:z=j+(m?"."+L:"["+L+"]"),O.set(t,I);let V=new WeakMap([[dd,O]]);ah(k,lh(C,z,r,n,o,s,i,a,r==="comma"&&_&&Le(y)?null:l,c,d,m,f,g,b,_,x,V))}return k}function WA(t=Ie){if(t.allowEmptyArrays!==void 0&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(t.encodeDotInKeys!==void 0&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&t.encoder!==void 0&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||Ie.charset;if(t.charset!==void 0&&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=id;if(t.format!==void 0){if(!rh(ld,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ld[r],o=Ie.filter;(typeof t.filter=="function"||Le(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in ih?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=Ie.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i;return t.allowDots===void 0?i=t.encodeDotInKeys?!0:Ie.allowDots:i=!!t.allowDots,{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Ie.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Ie.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Ie.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:t.delimiter===void 0?Ie.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Ie.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Ie.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Ie.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Ie.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Ie.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Ie.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Ie.strictNullHandling}}function ch(t,e={}){let r=t,n=WA(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Le(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=ih[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let c=new WeakMap;for(let f of o)n.skipNulls&&r[f]===null||ah(i,lh(r[f],f,a,l,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,c));let d=i.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(m+=n.charset==="iso-8859-1"?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&"),d.length>0?m+d:""}function uh(t){return ch(t,{arrayFormat:"brackets"})}var HA=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"]]);function pd(t){if(t.dataResidency===null||t.dataResidency===void 0)return;if(N(t,"baseURL"))throw new A("The `dataResidency` and `baseURL` options are mutually exclusive.");let e=HA.get(t.dataResidency);if(e===void 0)throw new A("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return e}var Ji,In=class t extends Promise{constructor(e,r,n=vn){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Ji.set(this,void 0),E(this,Ji,e,"f")}_thenUnwrap(e){return new t(u(this,Ji,"f"),this.responsePromise,async(r,n)=>Vi(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(u(this,Ji,"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)}};Ji=new WeakMap;var Tl,Sn=class{constructor(e,r,n,o){Tl.set(this,void 0),E(this,Tl,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 A("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,Tl,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Tl=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Zi=class extends In{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await vn(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Ee=class extends Sn{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}},P=class extends Sn{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:{...zi(this.options.query),after:r}}:null}},J=class extends Sn{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:{...zi(this.options.query),after:e}}:null}},ue=class extends Sn{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:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...zi(this.options.query),after:e}}:null}},Lo=class extends Sn{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:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...zi(this.options.query),page:e}}:null}};var GA={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},JA="urn:ietf:params:oauth:grant-type:token-exchange",ZA=.5;function XA(t,e){if(typeof t!="number"||!Number.isFinite(t)||t<=0)throw new A("Token exchange response has invalid 'expires_in' field");let r=Date.now(),n=r+t*1e3;if(!Number.isSafeInteger(n)||n<=r)throw new A("Token exchange response has invalid 'expires_in' field");let o=n-(performance.now()-e);if(o<=r)throw new A("Workload identity token expired before its exchange completed.");return o}function QA(t,e,r){let n=(r??1200)*1e3,o=Math.min(n,e*1e3*ZA);return t-o}var dh=Response.prototype,YA=dh.arrayBuffer;function ex(t,e){let r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(e===t||typeof r!="function"||Object.getOwnPropertyDescriptor(r,"name")?.value!=="Response"||Object.getOwnPropertyDescriptor(r,"prototype")?.value!==e)return!1;let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);return(n?.value==="Response"||typeof n?.get=="function")&&typeof Object.getOwnPropertyDescriptor(e,"headers")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"ok")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"status")?.get=="function"}function tx(t,e){if(t===e)return!0;let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;return e!==null&&Object.getPrototypeOf(e)===t&&typeof r=="function"&&Object.getOwnPropertyDescriptor(r,"name")?.value==="Body"&&Object.getOwnPropertyDescriptor(r,"prototype")?.value===t}function rx(t){let e=globalThis;return new TextDecoder("utf-8",{ignoreBOM:typeof e.Bun?.version=="string"}).decode(t)}async function nx(t){let e,r=null;for(let o=0,s=t;s!==null&&o<16&&s!==dh;s=Object.getPrototypeOf(s),o+=1){ex(t,s)&&(r=s);let i=Object.getOwnPropertyDescriptor(s,"json");if(!i)continue;if(typeof i.value!="function")break;let a=Object.getOwnPropertyDescriptor(s,"text")?.value;if(typeof a=="function"&&tx(s,r)){e=a;break}return i.value.call(t)}let n=e===void 0?rx(await YA.call(t)):await e.call(t);try{return JSON.parse(n)}catch{throw new SyntaxError("Token exchange response contains invalid JSON")}}function ox(t){return typeof globalThis.Bun?.version=="string"?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(t):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(t)}var El=class t{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl="https://auth.openai.com/oauth/token";let{identityProviderId:n,serviceAccountId:o,clientId:s,refreshBufferSeconds:i,provider:a}=e;this.config={identityProviderId:n,serviceAccountId:o,...s===void 0?{}:{clientId:s},...i===void 0?{}:{refreshBufferSeconds:i},provider:{tokenType:a.tokenType,getToken:a.getToken.bind(a)}},this.fetch=r??Ui()}async getToken(){if(!this.cachedToken||t.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(t.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let r=await this.config.provider.getToken(),n={grant_type:JA,subject_token:r,subject_token_type:GA[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);let o=performance.now(),s=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),redirect:"manual"});if(!s.ok){let d=await s.text(),m;try{m=JSON.parse(d)}catch{}throw s.status===400||s.status===401||s.status===403?new it(s.status,m,s.headers):ee.generate(s.status,m,`Token exchange failed with status ${s.status}`,s.headers)}let i=await nx(s),a=typeof i=="object"&&i!==null&&"access_token"in i?i.access_token:void 0;if(typeof a!="string"||a.trim().length===0||ox(a))throw new A("Token exchange response missing 'access_token' field");let l=i.expires_in??3600,c=XA(l,o);return this.tokenGeneration===e&&(this.cachedToken={token:a,expiresAt:c,refreshAt:QA(c,l,this.config.refreshBufferSeconds)}),a}static isTokenExpired(e){return Date.now()>=e.expiresAt}static needsRefresh(e){return Date.now()>=e.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}};var ph="https://mtls.api.openai.com/v1";function jo(t){let e;try{e=new URL(t)}catch{throw new A("X.509 workload identity requires the approved global mTLS API origin.")}if(e.origin!=="https://mtls.api.openai.com"||e.username||e.password)throw new A("X.509 workload identity requires the approved global mTLS API origin.");for(let r of e.searchParams.keys())if(Hi(r))throw new A("X.509 workload identity cannot send conflicting query authentication credentials.");return e}var fh=Symbol("brand.privateNullableHeaders"),sx=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*ix(t){if(!t)return;if(fh in t){let{values:o,nulls:s}=t;yield*o.entries();for(let i of s)yield[i,null];return}let e=!1,r,n=Symbol.iterator in t?t[Symbol.iterator]:void 0;typeof n=="function"?r={[Symbol.iterator]:()=>n.call(t)}:(e=!0,r=Object.entries(t??{}));for(let o of r){let s=o[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let i=Mm(o[1])?o[1]:[o[1]],a=!1;for(let l of i)l!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,l])}}var v=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,i]of ix(n)){if(!sx.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{[fh]:!0,values:e,nulls:r}};var fd={};wu(fd,{findRegisteredX509Transport:()=>ax,findX509Credential:()=>_x,findX509OAuthError:()=>gx,isApprovedX509Client:()=>mx,isRetryableX509IssuerError:()=>px,isTransientX509ConnectionError:()=>ux,markApprovedX509Client:()=>fx,markRetryableX509IssuerError:()=>dx,markTransientX509ConnectionError:()=>cx,rememberRegisteredX509Transport:()=>lx,rememberX509Credential:()=>yx,rememberX509OAuthError:()=>hx});var mh=new WeakMap,hh=new WeakSet,gh=new WeakSet,yh=new WeakSet,_h=new WeakMap,wh=new WeakMap,ax=WeakMap.prototype.get.bind(mh),lx=WeakMap.prototype.set.bind(mh),cx=WeakSet.prototype.add.bind(hh),ux=WeakSet.prototype.has.bind(hh),dx=WeakSet.prototype.add.bind(gh),px=WeakSet.prototype.has.bind(gh),fx=WeakSet.prototype.add.bind(yh),mx=WeakSet.prototype.has.bind(yh),hx=WeakMap.prototype.set.bind(_h),gx=WeakMap.prototype.get.bind(_h),yx=WeakMap.prototype.set.bind(wh),_x=WeakMap.prototype.get.bind(wh);var md=Sf(bh(),1),wx=typeof md.findRegisteredX509Transport=="function"?md:fd,{findRegisteredX509Transport:Ah,rememberRegisteredX509Transport:b1,markTransientX509ConnectionError:A1,isTransientX509ConnectionError:kl,markRetryableX509IssuerError:x1,isRetryableX509IssuerError:hd,markApprovedX509Client:xh,isApprovedX509Client:bx,rememberX509OAuthError:v1,findX509OAuthError:vh,rememberX509Credential:I1,findX509Credential:Ih}=wx;function Sh(t){if(!t||typeof t!="object")throw new A("X.509 workload identity requires an approved X.509 transport capability.");let e=Ah(t);if(!e)throw new A("X.509 workload identity requires an approved X.509 transport capability.");return e}var Q,Fe,Tn,En,Dt,at,Yt,er,Oe,On,Qt,ct,lt,kh,Pl,Ch,Th,Ph,Rh,Eh,Mh,ne,yd,Ax=["dispatcher","agent","client","tls","proxy"],Do=(t,e)=>Headers.prototype.get.call(t,e),xx=1200*1e3,Oh=1e3,Cl=t=>{let e=new ie;return Object.defineProperty(e,"cause",{value:t.reason,writable:!0,configurable:!0}),e};function gd(t){for(let e of Headers.prototype.keys.call(t)){let r=e.toLowerCase().split("_").join("-");if(r!=="authorization"&&xl(r)||r==="host")throw new A("X.509 workload identity cannot send conflicting authentication credentials.")}}function vx(t,e){let r=new AbortController,n=t===void 0?void 0:setTimeout(()=>r.abort(new ce),t),o=n;typeof o=="object"&&o!==null&&"unref"in o&&typeof o.unref=="function"&&o.unref();let s=()=>r.abort(e?.reason);return e?.addEventListener("abort",s,{once:!0}),e?.aborted&&s(),{signal:r.signal,dispose:()=>{e?.removeEventListener("abort",s),n&&clearTimeout(n)}}}function Ix(t,e){let r,n=new Promise((o,s)=>{r=()=>s(e.reason),e.addEventListener("abort",r,{once:!0}),e.aborted&&r()});return{result:Promise.race([t.promise,n]),dispose:()=>{r&&e.removeEventListener("abort",r)}}}function Rl(t){if(!t||typeof t!="object")return!1;let e=t;for(;e!==null&&e!==Object.prototype;){let n=Object.getOwnPropertyDescriptor(e,"provider");if(n){if(!("value"in n)||n.value!==void 0)return!1;break}e=Object.getPrototypeOf(e)}let r=t;for(;r!==null&&r!==Object.prototype;){let n=Object.getOwnPropertyDescriptor(r,"type");if(n){if(!("value"in n))throw new A("X.509 workload identity type must be a plain data property.");return n.value==="x509"}r=Object.getPrototypeOf(r)}return!1}function _d(t){if(!t)return;for(let r of Ax)if(N(t,r))throw new A("X.509 workload identity cannot override its approved transport capability.");let e=Object.getOwnPropertyDescriptor(t,"redirect")?.value;if(e!==void 0&&e!=="manual")throw new A("X.509 workload identity requests require manual redirects.")}function Xi(t){if(_d(t),t&&["body","headers","method","signal"].some(e=>N(t,e)))throw new A("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}function wd(t){Xi(t);let e={...t};return Xi(e),e}var je=class{constructor(e,r,n,o){if(Q.add(this),Tn.set(this,void 0),En.set(this,void 0),Dt.set(this,void 0),at.set(this,void 0),Yt.set(this,void 0),er.set(this,void 0),Oe.set(this,void 0),On.set(this,void 0),Qt.set(this,void 0),ct.set(this,void 0),lt.set(this,0),E(this,Oe,Sh(r),"f"),E(this,Tn,e.identityProviderId,"f"),E(this,En,e.serviceAccountId,"f"),E(this,Dt,e.refreshBufferMs,"f"),E(this,at,e.refreshBufferSeconds,"f"),E(this,Yt,n,"f"),E(this,er,o,"f"),u(this,Dt,"f")!==void 0&&u(this,at,"f")!==void 0)throw new A("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(u(this,Dt,"f")!==void 0&&(!Number.isSafeInteger(u(this,Dt,"f"))||u(this,Dt,"f")<0))throw new A("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(u(this,at,"f")!==void 0&&(!Number.isSafeInteger(u(this,at,"f"))||u(this,at,"f")<0||!Number.isSafeInteger(u(this,at,"f")*1e3)))throw new A("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");E(this,On,u(this,at,"f")===void 0?u(this,Dt,"f")??xx:u(this,at,"f")*1e3,"f")}identitySnapshot(){return{type:"x509",identityProviderId:u(this,Tn,"f"),serviceAccountId:u(this,En,"f"),...u(this,Dt,"f")===void 0?{}:{refreshBufferMs:u(this,Dt,"f")},...u(this,at,"f")===void 0?{}:{refreshBufferSeconds:u(this,at,"f")}}}static shouldAuthenticate(e,r,n=e.headers){return!v([r,n]).nulls.has("authorization")}snapshotHeaders(e,r){let n=u(this,Q,"m",ne).call(this);return n.defaultHeaders??(n.defaultHeaders=v([e])),n.requestHeaders??(n.requestHeaders=v([r])),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:r}=u(this,Q,"m",ne).call(this);if(!e||!r)throw new A("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders:e,requestHeaders:r}}snapshotTenant(e,r){if(e!==u(this,Yt,"f")||r!==u(this,er,"f"))throw new A("X.509 workload identity cannot override its enrolled organization or project.");let n=u(this,Q,"m",ne).call(this);return n.tenant={organization:e,project:r},n.tenant}tenantSnapshot(){let{tenant:e}=u(this,Q,"m",ne).call(this);if(!e)throw new A("X.509 workload identity requires snapshotted tenant selectors.");return e}snapshotAPIURL(e){jo(e),u(this,Q,"m",ne).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=u(this,Q,"m",ne).call(this);if(e===void 0)throw new A("X.509 workload identity requires a snapshotted API destination.");return e}snapshotRequest(e,r,n){var o;(o=u(this,Q,"m",ne).call(this)).request??(o.request={signal:e,timeout:r,fetchOptions:n})}requestSnapshot(){let{request:e}=u(this,Q,"m",ne).call(this);if(!e)throw new A("X.509 workload identity requires snapshotted request settings.");return e}beginRequestPreparation(){let e=u(this,Q,"m",ne).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){u(this,Q,"m",ne).call(this).phase="planning"}beginRequestNetwork(){let e=u(this,Q,"m",ne).call(this);e.deadlineArmed?e.preparationStartedAt!==void 0&&(e.monotonicStartedAt+=performance.now()-e.preparationStartedAt,e.wallStartedAt+=Date.now()-(e.preparationWallStartedAt??Date.now()),delete e.preparationStartedAt,delete e.preparationWallStartedAt):(e.wallStartedAt=Date.now(),e.monotonicStartedAt=performance.now(),e.deadlineArmed=!0)}isPlanningRequest(){return u(this,Q,"m",ne).call(this).phase==="planning"}authorizePlannedRequest(e,r,n,o=!1){let s=u(this,Q,"m",ne).call(this),i=Object.getOwnPropertyDescriptor(r,"headers"),a=Object.getOwnPropertyDescriptor(r,"body"),l=Object.getOwnPropertyDescriptor(r,"signal"),c=Object.getOwnPropertyDescriptor(r,"redirect");if(s.phase!=="planning"||!i||!(i.value instanceof Headers)||!a&&"body"in r||[a,l,c].some(m=>m&&!("value"in m)))throw new A("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(e),_d(r);try{gd(i.value)}catch{throw new A("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(Do(i.value,"Authorization")!==null)throw new A("X.509 workload identity cannot use caller-supplied authorization credentials.");if(u(this,Q,"m",yd).call(this,i.value),!o&&(l?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new A("X.509 workload identity must preserve its approved request signal.");let d=this.requestSnapshot();s.request={...d,timeout:Math.min(d.timeout,n)},s.phase="authorizing"}ownRequestBody(e,r){e instanceof ReadableStream&&e!==r&&(u(this,Q,"m",ne).call(this).materializedBody=e)}static isStreamingRequestBody(e){return globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream||typeof e=="object"&&e!==null&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")}retireRequestBody(){let e=u(this,Q,"m",ne).call(this),r=e.materializedBody;delete e.materializedBody,r&&u(Fe,Fe,"m",kh).call(Fe,r)}releaseRequestBody(e){let r=u(this,Q,"m",ne).call(this);r.materializedBody===e?delete r.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?u(this,Q,"m",ne).call(this).effectiveSignal=e:delete u(this,Q,"m",ne).call(this).effectiveSignal}effectiveSignal(){let e=u(this,Q,"m",ne).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,r){return u(this,Oe,"f").run(async()=>{let n=u(this,Oe,"f").current();if(!n)throw new A("X.509 workload identity requires an active certificate request scope.");n.owner=this,n.requestOwner=r;try{return await e()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete n.requestOwner,delete n.owner}})}inRequest(e){let r=u(this,Oe,"f").current();return r?.owner===this&&r.requestOwner===e&&r.phase!=="authorizing"}matches(e){return u(this,Oe,"f")===u(e,Oe,"f")&&u(this,Tn,"f")===u(e,Tn,"f")&&u(this,En,"f")===u(e,En,"f")&&u(this,Yt,"f")===u(e,Yt,"f")&&u(this,er,"f")===u(e,er,"f")&&u(this,On,"f")===u(e,On,"f")}continuation(){let{wallStartedAt:e,monotonicStartedAt:r,deadlineArmed:n,request:o,requestOwner:s,effectiveSignal:i}=u(this,Q,"m",ne).call(this),a={wallStartedAt:e,monotonicStartedAt:r,owner:this,...n?{deadlineArmed:n}:{},...o?{request:o}:{},...i?{effectiveSignal:i}:{},...s?{requestOwner:s}:{}};return l=>u(this,Oe,"f").resume(a,async()=>{try{return await l()}finally{this.releaseRequestCredentials(),delete a.requestOwner,delete a.owner}})}releaseRequestCredentials(){let e=u(this,Q,"m",ne).call(this);delete e.request,delete e.phase,delete e.deadlineArmed,delete e.preparationStartedAt,delete e.preparationWallStartedAt,delete e.effectiveSignal,delete e.materializedBody,delete e.apiURL,delete e.tenant,delete e.token,delete e.defaultHeaders,delete e.requestHeaders,delete e.tokenGeneration,delete e.headers,delete e.authorization}requestStartedAt(e){return u(this,Oe,"f").current()?.wallStartedAt}usedWorkloadToken(e){return u(this,Oe,"f").current()?.token!==void 0}remainingTimeout(e,r){let n=u(this,Oe,"f").current();if(n===void 0)return r;let o=r-(performance.now()-n.monotonicStartedAt);if(o<=0)throw new ce;return o}async waitForRetry(e,r){try{await u(this,Oe,"f").sleep(e,r)}catch(n){throw r?.aborted?Cl(r):n}}static isRetryableFailure(e){return typeof e=="object"&&e!==null&&(kl(e)||hd(e))}static retryHeaders(e){if(!e||typeof e!="object"||!hd(e))return;let r=Object.getOwnPropertyDescriptor(e,"headers")?.value;return r instanceof Headers?r:void 0}async getToken(e,r){let n=r?r.signal:e?.signal;if(n?.aborted)throw Cl(n);e&&Xi(r?r.fetchOptions:e.fetchOptions),u(this,Q,"m",Mh).call(this,r);let o=e?u(this,Q,"m",ne).call(this):void 0,s=u(this,Qt,"f");if(s&&performance.now()<s.refreshAt&&Date.now()<s.wallRefreshAt)return u(Fe,Fe,"m",Pl).call(Fe,o,s);let i=r&&e?this.remainingTimeout(e,r.timeout):r?.timeout,{signal:a,dispose:l}=vx(i,n);if(n?.aborted)throw l(),Cl(n);let c=u(this,ct,"f")??u(this,Q,"m",Rh).call(this);c.waiters+=1;let d=Ix(c,a);try{let m=await d.result,f=u(this,Qt,"f");if(!f||f.accessToken!==m.accessToken)throw new ie;return u(Fe,Fe,"m",Pl).call(Fe,o,f)}catch(m){return await u(this,Q,"m",Ch).call(this,m,c,s,o,e,r)}finally{d.dispose(),l(),c.waiters-=1,u(this,Q,"m",Ph).call(this,c)}}invalidateToken(){let e=u(this,Oe,"f").current();if(!e?.token||u(this,Qt,"f")?.accessToken!==e.token||u(this,Qt,"f").generation!==e.tokenGeneration)return;E(this,lt,u(this,lt,"f")+1,"f"),E(this,Qt,void 0,"f");let r=u(this,ct,"f");E(this,ct,void 0,"f"),r?.controller.abort(new ie)}bindRequest(e,r,n){if(!(r.headers instanceof Headers))throw new A("X.509 workload identity requires the original workload authorization headers.");let o=u(this,Q,"m",ne).call(this),{token:s}=o,i=e.__security??{bearerAuth:!0},a=s?`Bearer ${s}`:null;!s&&i.adminAPIKeyAuth&&n!==null&&Do(r.headers,"Authorization")!==null&&(a=new Headers({Authorization:`Bearer ${n}`}).get("Authorization")),o.headers=r.headers,o.authorization=a,this.assertRequest(r)}adoptRequestHeaders(e){let r=u(this,Q,"m",ne).call(this),n=r.headers;if(!(n instanceof Headers)||!(e.headers instanceof Headers))throw new A("X.509 workload identity must preserve its issued workload authorization.");r.headers=e.headers;try{this.assertRequest(e)}catch(o){throw r.headers=n,o}}assertRequest(e){let{headers:r}=e;if(!(r instanceof Headers))throw new A("X.509 workload identity must preserve its issued workload authorization.");let n=u(this,Oe,"f").current();if(!n||n.headers!==r||n.authorization===void 0||Do(r,"Authorization")!==n.authorization)throw new A("X.509 workload identity must preserve its issued workload authorization.");u(this,Q,"m",yd).call(this,r),gd(r)}fetch(){return async(e,r={})=>{let n=jo(typeof e=="string"||e instanceof URL?e:e.url);_d(r),this.assertRequest(r);let o=r.headers;if(!(o instanceof Headers))throw new A("X.509 workload identity must preserve its issued workload authorization.");let s=new Headers([...Headers.prototype.entries.call(o)]);return gd(s),r.headers=s,r.redirect="manual",await u(this,Oe,"f").dispatch(n,r)}}};Fe=je,Tn=new WeakMap,En=new WeakMap,Dt=new WeakMap,at=new WeakMap,Yt=new WeakMap,er=new WeakMap,Oe=new WeakMap,On=new WeakMap,Qt=new WeakMap,ct=new WeakMap,lt=new WeakMap,Q=new WeakSet,kh=async function(e){try{await Zt(e)}catch{}},Pl=function(e,r){return e&&(e.token=r.accessToken,e.tokenGeneration=r.generation),r.accessToken},Ch=async function(e,r,n,o,s,i){let a=i?i.signal:s?.signal;if(a?.aborted)throw Cl(a);if(r.controller.signal.aborted&&r.generation!==u(this,lt,"f"))return await this.getToken(s,i);let l=u(this,Q,"m",Th).call(this,e,n,o);if(l!==void 0)return l;if(e&&typeof e=="object"&&!(e instanceof it)){let c=vh(e);if(c)throw new it(c.status,c.error,c.headers)}throw e},Th=function(e,r,n){if(!r||r!==u(this,Qt,"f")||performance.now()>=r.expiresAt||Date.now()>=r.wallExpiresAt||!Fe.isRetryableFailure(e))return;let o=Fe.retryHeaders(e),s=o?.get("retry-after-ms"),i=s?Number(s):void 0,a=o?.get("retry-after");if(a&&(i===void 0||Number.isNaN(i))){let c=Number(a);i=Number.isNaN(c)?Date.parse(a)-Date.now():c*1e3}let l=i!==void 0&&Number.isFinite(i)&&i>=0&&i<=6e4?Math.max(Oh,i):Oh;return r.refreshAt=Math.min(r.expiresAt,performance.now()+l),r.wallRefreshAt=Math.min(r.wallExpiresAt,Date.now()+l),u(Fe,Fe,"m",Pl).call(Fe,n,r)},Ph=function(e){e.waiters!==0||u(this,ct,"f")!==e||queueMicrotask(()=>{e.waiters===0&&u(this,ct,"f")===e&&(E(this,ct,void 0,"f"),E(this,lt,u(this,lt,"f")+1,"f"),e.controller.abort(new ie))})},Rh=function(){let e=new AbortController,r=u(this,lt,"f"),n={controller:e,generation:r,waiters:0,promise:u(this,Q,"m",Eh).call(this,e,r)};return E(this,ct,n,"f"),n},Eh=async function(e,r){let n=performance.now(),o=Date.now();try{let s=await u(this,Oe,"f").exchange(u(this,Tn,"f"),u(this,En,"f"),e.signal),i=s.expiresIn*1e3,a=n+i,l=o+i;if(performance.now()>=a||Date.now()>=l)throw new A("X.509 workload identity token expired before its exchange completed.");if(u(this,lt,"f")!==r||e.signal.aborted||u(this,ct,"f")?.controller!==e)throw new ie;return E(this,lt,u(this,lt,"f")+1,"f"),E(this,Qt,{accessToken:s.accessToken,generation:u(this,lt,"f"),expiresAt:a,refreshAt:a-Math.min(u(this,On,"f"),i/2),wallExpiresAt:l,wallRefreshAt:l-Math.min(u(this,On,"f"),i/2)},"f"),s}finally{u(this,ct,"f")?.controller===e&&E(this,ct,void 0,"f")}},Mh=function(e){if(!e)return;if(e.organization!==u(this,Yt,"f")||e.project!==u(this,er,"f"))throw new A("X.509 workload identity cannot override its enrolled organization or project.");jo(e.apiURL);let r=v([e.defaultHeaders,e.requestHeaders]);if(u(this,Yt,"f")!==null&&r.nulls.has("openai-organization")||u(this,er,"f")!==null&&r.nulls.has("openai-project"))throw new A("X.509 workload identity cannot omit its enrolled organization or project.");for(let n of r.values.keys()){let o=n.toLowerCase().split("_").join("-");if((o==="openai-organization"||o==="openai-project")&&(n!==o||Do(r.values,n)!==(o==="openai-organization"?e.organization:e.project)))throw new A("X.509 workload identity cannot override its enrolled organization or project.");if(xl(o)||o==="host")throw new A("X.509 workload identity cannot use caller-supplied authentication credentials.")}},ne=function(){let e=u(this,Oe,"f").current();if(!e||e.owner!==this)throw new A("X.509 workload identity requires an active certificate request scope.");return e},yd=function(e){if(Do(e,"OpenAI-Organization")!==u(this,Yt,"f")||Do(e,"OpenAI-Project")!==u(this,er,"f"))throw new A("X.509 workload identity cannot override its enrolled organization or project.");for(let r of Headers.prototype.keys.call(e)){let n=r.toLowerCase().split("_").join("-");if((n==="openai-organization"||n==="openai-project")&&r!==n)throw new A("X.509 workload identity cannot override its enrolled organization or project.")}};function $h(t){let{credential:e}=t;if(e===void 0)return{credential:e,options:t};let r=Ih(e);if(!r)throw new A("An X.509 credential must be created by the SDK authentication helper.");let n=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter(o=>{let s=t[o];return s!=null});if(n.length>0)throw new A(`The \`credential\` option cannot be combined with ${n.map(o=>`\`${o}\``).join(", ")}.`);return{credential:e,options:{...t,apiKey:null,adminAPIKey:null,baseURL:t.baseURL??null,organization:t.organization??null,project:t.project??null,workloadIdentity:r.identity,x509Transport:r.transport}}}function Sx({apiKey:t,adminAPIKey:e}){return t!=null||e!=null}function Tx(t,e){let r=t.provider,n=e.credential??e.workloadIdentity,o=e.provider??(n?void 0:r);return o!==r&&(delete t.baseURL,delete t.organization,delete t.project,delete t.defaultHeaders,delete t.defaultQuery,delete t.fetchOptions,delete t.fetch),o&&(delete t.apiKey,delete t.adminAPIKey,delete t.credential,delete t.workloadIdentity,delete t.x509Transport,delete t.baseURL),o}function Nh(t,e,r,n){let o=N(e,"workloadIdentity")?e.workloadIdentity:t.workloadIdentity,s=r!==void 0&&(Sx(e)&&e.workloadIdentity===void 0||e.provider!==void 0);r!==void 0&&N(e,"workloadIdentity")&&delete t.x509Transport;let i=r!==void 0&&!s&&e.credential===void 0&&!N(e,"workloadIdentity")&&!N(e,"x509Transport")?r:void 0,a=e.credential===void 0?i:e.credential,l=a!==void 0||!s&&Rl(o);return n!==l&&(delete t.fetch,delete t.baseURL,delete t.organization,delete t.project,delete t.defaultHeaders,delete t.defaultQuery,delete t.fetchOptions,l?t.apiKey=null:(delete t.x509Transport,s&&delete t.workloadIdentity)),a!==void 0&&(delete t.apiKey,delete t.adminAPIKey,delete t.workloadIdentity,delete t.x509Transport,t.credential=a,e.credential!==void 0&&(delete t.organization,delete t.project,delete t.defaultHeaders,delete t.defaultQuery,delete t.fetchOptions)),{credential:a,provider:Tx(t,e)}}var jh=Symbol("brand.privateStreamingFile");function $l(t,e,r){if(typeof e!="string"||!e)throw new TypeError("toStreamingFile requires a non-empty file name");let n=r?.type;return n&&Uh(n),{[jh]:!0,data:t,name:e,...n?{type:n}:{}}}var Id=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&Number.parseInt(t.versions.node.split("."),10)<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function tr(t,e,r){return Id(),new File(t,e??"unknown_file",r)}function kn(t,e){if(typeof t!="object"||t===null)return;let r="name"in t?t.name:void 0,n=r&&String(r)||"filename"in t&&t.filename&&String(t.filename);if(n)return e?.stripFilename===!1?Dh(n):Qi(n);let o="url"in t&&t.url&&String(t.url);if(o)try{return Qi(new URL(o).pathname)}catch{return Qi(o)}let s="path"in t&&t.path&&String(t.path);return s?Qi(s):void 0}function Qi(t){return t.split(/[\\/]/).pop()||void 0}function Dh(t){let e=t.replace(/\\/g,"/");if(e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.split("/").includes(".."))throw new TypeError("Upload file name must be a safe relative path without parent directory segments");return e}var Ex=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;function Sd(t){try{return Ex?.call(t)!==void 0}catch{return!1}}var Fo=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Nr=async(t,e,r)=>Ad(t.body)?Ml(t.body)?zh(t,r):{...t,body:await Fh(t.body,e,r)}:t,we=async(t,e,r)=>Ml(t.body)?zh(t,r):{...t,body:await Fh(t.body,e,r)},Lh=new WeakMap;function Ox(t){let e=typeof t=="function"?t:t.fetch,r=Lh.get(e);if(r)return r;let n=(async()=>{try{let o;if("Response"in e)o=e.Response;else{let i=await e("data:,");await i.arrayBuffer(),o=i.constructor}let s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return Lh.set(e,n),n}var Fh=async(t,e,r={})=>{if(!await Ox(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([o,s])=>vd(n,o,s,r))),n},Nl=t=>t instanceof Blob,Td=t=>typeof t=="object"&&t!==null&&"getReader"in t&&typeof t.getReader=="function",ea=t=>typeof t=="object"&&t!==null&&jh in t,Ll=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Fo(t)||Td(t)||ea(t)||Nl(t)),Ml=t=>{if(ea(t)||Fo(t)||Td(t))return!0;if(Array.isArray(t))return t.some(Ml);if(t&&typeof t=="object"&&!Nl(t)&&!(t instanceof Response)){for(let e of Object.keys(t))if(Ml(t[e]))return!0}return!1},Ad=t=>{if(Ll(t))return!0;if(Array.isArray(t))return t.some(Ad);if(t&&typeof t=="object"){for(let e of Object.keys(t))if(Ad(t[e]))return!0}return!1},kx=(t,e)=>{let r=[];for(let n of t)Ll(n.value)&&!e.has(n.value)&&e.set(n.value,Bh(n.value,{stripFilenames:!1})),r.push(n);return r},zh=(t,e={})=>{let r=Px(t.body),n=e.stripFilenames===!1?new WeakMap:void 0,o=n?kx(r,n):r,s=`openai-${Math.random().toString(36).slice(2)}`,i=qi(Cx(o,s,e,n));return{...t,body:i,headers:v([{"content-type":`multipart/form-data; boundary=${s}`},t.headers])}};async function*Cx(t,e,r,n){for await(let{key:o,value:s}of t){if(Ll(s)){let i=n?.get(s)??Bh(s,r),a=Rx(s);yield Me(`--${e}\r
43
+ `),yield Me(`Content-Disposition: form-data; name="${bd(o)}"; filename="${bd(i)}"\r
44
+ Content-Type: ${a}\r
45
+ \r
46
+ `),yield*Yi(Mx(s))}else yield Me(`--${e}\r
47
+ `),yield Me(`Content-Disposition: form-data; name="${bd(o)}"\r
48
+ \r
49
+ ${String(s)}`);yield Me(`\r
50
+ `)}yield Me(`--${e}--\r
51
+ `)}function*Px(t){if(!(!t||typeof t!="object"))for(let[e,r]of Object.entries(t))yield*xd(e,r)}function*xd(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"||Ll(e))yield{key:t,value:e};else if(Array.isArray(e))for(let r of e)yield*xd(t+"[]",r);else if(typeof e=="object")for(let[r,n]of Object.entries(e))yield*xd(`${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 Bh(t,e){if(ea(t)){let{name:r}=t;if(typeof r!="string"||!r)throw new TypeError("Streaming upload file name must be a non-empty string");return e.stripFilenames===!1?Dh(r):Qi(r)??"unknown_file"}return kn(t,{stripFilename:e.stripFilenames})??"unknown_file"}function Rx(t){let e;return ea(t)||Nl(t)?{type:e}=t:t instanceof Response&&(e=t.headers.get("content-type")??void 0),Uh(e||"application/octet-stream")}function Uh(t){if(typeof t!="string")throw new TypeError("Streaming upload content type must be a string");for(let e=0;e<t.length;e+=1){let r=t.codePointAt(e)??0;if(r<=31||r===127)throw new TypeError("Streaming upload content type must not contain control characters")}return t}function Mx(t){return ea(t)?t.data:t}async function*Yi(t){if(typeof t=="string")yield Me(t);else if(ArrayBuffer.isView(t))yield new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(Sd(t))yield new Uint8Array(t);else if(t instanceof Response)yield*Yi(t.body||await t.blob());else if(t instanceof Blob)typeof t.stream=="function"?yield*Yi(t.stream()):yield new Uint8Array(await t.arrayBuffer());else if(Td(t))for await(let e of _l(t))yield*Yi(e);else if(Fo(t))for await(let e of t)yield*Yi(e);else throw new TypeError(`Invalid streaming file chunk: ${String(t)}`)}function bd(t){return Array.from(t,e=>{let r=e.codePointAt(0)??0;return r<=31||r===127||e==='"'||e==="\\"?encodeURIComponent(e):e}).join("")}var vd=async(t,e,r,n)=>{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){let o=await r.blob();t.append(e,tr([o],kn(r,{stripFilename:n.stripFilenames}),{type:o.type}))}else if(Fo(r))t.append(e,tr([await new Response(qi(r)).blob()],kn(r,{stripFilename:n.stripFilenames})));else if(Nl(r)){let o=kn(r,{stripFilename:n.stripFilenames});o===void 0?t.append(e,r):t.append(e,r,o)}else if(Array.isArray(r)){let o=await Promise.all(r.map(async s=>{let i=new FormData;return await vd(i,e+"[]",s,n),i}));for(let s of o)if(s)for(let[i,a]of s.entries())t.append(i,a)}else if(typeof r=="object")await Promise.all(Object.entries(r).map(([o,s])=>vd(t,`${e}[${o}]`,s,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var qh=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",$x=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&qh(t),Nx=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Lx=(t,e)=>e?.type!=null&&e.type!==t.type||e?.lastModified!=null&&e.lastModified!==t.lastModified||e?.endings!=null,jx=(t,e,r)=>(e==null||e===t.name)&&!Lx(t,r);async function ta(t,e,r){if(Id(),t=await t,$x(t)){let o={...r,type:r?.type??t.type,lastModified:r?.lastModified??t.lastModified};return t instanceof File?jx(t,e,r)?t:tr([t],e??t.name,o):tr([await t.arrayBuffer()],e??t.name,o)}if(Nx(t)){let o=await t.blob();e??(e=kn(t));let s=r?.type===void 0&&o.type?{...r,type:o.type}:r;return tr(await Ed(o),e,s)}let n=await Ed(t);if(e??(e=kn(t)),r?.type===void 0){let o=n.find(s=>typeof s=="object"&&"type"in s&&!!s.type);o&&(r={...r,type:o.type})}return tr(n,e,r)}async function Ed(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||Sd(t))e.push(t);else if(qh(t))e.push(t instanceof Blob?t:new Blob([await t.arrayBuffer()],{type:t.type}));else if(Fo(t))for await(let r of t)e.push(...await Ed(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Dx(t)}`)}return e}function Dx(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var w=class{constructor(e){this._client=e}};function Kh(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Wh=Object.freeze(Object.create(null)),zx=(t=Kh)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i="";for(let d=0;d<r.length;d+=1)if(d in r){let m=r[d];/[?#]/.test(m)&&(o=!0);let f=n[d],g=(o?encodeURIComponent:t)(""+f);d!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Wh)??Wh)?.toString)&&(g=f+"",s.push({start:i.length+m.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),i+=m+(d===n.length?"":g)}let a=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)s.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(s.sort((d,m)=>d.start-m.start),s.length>0){let d=0,m="";for(let f of s){let g=" ".repeat(f.start-d),b="^".repeat(f.length);d=f.start+f.length,m+=g+b}throw new A(`Path parameters result in path with invalid segments:
52
+ ${s.map(f=>f.error).join(`
53
+ `)}
54
+ ${i}
55
+ ${m}`)}return i},h=zx(Kh);var Cn=class extends w{list(e,r={},n){return this._client.getAPIList(h`/chat/completions/${e}/messages`,P,{query:r,...n,__security:{bearerAuth:!0}})}};function Ft(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Hh(t,e){let r={...t,type:"json_schema"};return r.json_schema={...r.json_schema},delete r.toJSON,delete r.json_schema.toJSON,Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Ux(t){return t?.$brand==="auto-parseable-response-format"}function zt(t){return Ux(t)||t?.type==="json_schema"}function wt(t,e){if(!zt(t))return null;if(typeof t=="object"&&t!==null&&"$parseRaw"in t&&typeof t.$parseRaw=="function")return t.$parseRaw(e);try{return JSON.parse(e)}catch(r){throw r instanceof SyntaxError?new SyntaxError("Error reading response: invalid structured output JSON."):r}}function bt(t){return t?.$brand==="auto-parseable-tool"}function Vh(t,e){return!e||!kd(e)?{...t,choices:t.choices.map(r=>({...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:ra(t,e)}function ra(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new Rr;if(n.finish_reason==="content_filter")throw new Mr;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Wx(e,o))??void 0}:void 0,parsed:n.message.content!==null&&n.message.content!==void 0&&!n.message.refusal&&(n.message.content!==""||!n.message.tool_calls?.length&&!n.message.function_call)?qx(e,n.message.content):null}}});return{...t,choices:r}}function qx(t,e){return wt(t.response_format,e)}function Wx(t,e){if(e.type==="custom")return e;if(e.type!=="function"){let o=e.type;throw new A(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${o}\``)}let r=t.tools?.find(o=>Ft(o)&&o.function?.name===e.function.name),n=null;return bt(r)?n=r.$parseRaw(e.function.arguments):r?.function.strict&&(n=wt({type:"json_schema",$parseRaw:void 0},e.function.arguments)),{...e,function:{...e.function,parsed_arguments:n}}}function jl(t,e){if(!t||!("tools"in t)||!t.tools||e.type!=="function")return!1;let r=t.tools?.find(n=>Ft(n)&&n.function?.name===e.function?.name);return Ft(r)&&(bt(r)||r?.function.strict||!1)}function kd(t){return zt(t.response_format)?!0:t.tools?.some(e=>bt(e)||e.type==="function"&&e.function.strict===!0)??!1}function Gh(t){for(let e of t??[])if(e.type!=="custom"){if(e.type!=="function"){let r=e.type;throw new A(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${r}\``)}if(e.function.strict!==!0)throw new A(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var rr=t=>t?.role==="assistant",na=t=>t?.role==="tool";var Ze,zl,Bl,la,sa,Ul,ca,ut,ua,da,ia,zo,Lr,Pn,Wl,Kl,Bo,Rn,Nd,tg,Ld,rg,jd,ql,ng,Jh=4096,aa=8*1024*1024,Kx=4096,pa=256,Hx=JSON.stringify,Vx=JSON.parse,Cd=new WeakSet,Gx=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,Jx=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,Zx=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,Zh=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,Xx=Date.prototype.getTime,Qx=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,Yx=typeof SharedArrayBuffer=="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,oa=Object.getOwnPropertyDescriptor(new Error("native stack descriptor"),"stack"),Bt=Function.prototype.toString,ev=Object.prototype.toString,Dl=Object.getOwnPropertyDescriptor(Error,"isError"),Xh=Dl&&"value"in Dl&&typeof Dl.value=="function"?Dl.value:void 0,tv=Bt.call(Error),rv=Bt.call(Date),nv=Bt.call(Function),Hl=new Set([st.prototype,ce.prototype,ee.prototype,A.prototype,ie.prototype,Sr.prototype,Nt.prototype,Or.prototype,Mr.prototype,Pr.prototype,Ge.prototype,Rr.prototype,Er.prototype,it.prototype,Tr.prototype,Cr.prototype,bn.prototype,kr.prototype]),og=new Set,sg=new Map,Qh=new WeakMap;function ov(){if(!(typeof process>"u"))try{let t=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!t||!("value"in t)||typeof t.value!="function")return;let e=Reflect.apply(t.value,process,["node:util"]);if(typeof e!="object"||e===null)return;let r=Object.getOwnPropertyDescriptor(e,"types");if(!r||!("value"in r)||typeof r.value!="object"||r.value===null)return;let n=Object.getOwnPropertyDescriptor(r.value,"isProxy");return!n||!("value"in n)||typeof n.value!="function"?void 0:n.value}catch{return}}var sv=ov();function Vl(t){if(typeof t!="function")return;let e=Object.getOwnPropertyDescriptor(t,"prototype");if(!e||!("value"in e)||typeof e.value!="object"&&typeof e.value!="function")return;Hl.add(e.value);let r=Bt.call(t);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(r)&&e.configurable===!1&&e.writable===!1){og.add(r);let n=new Map;for(let o of Reflect.ownKeys(e.value)){let s=Object.getOwnPropertyDescriptor(e.value,o);s&&n.set(o,s)}sg.set(r,n)}}for(let t of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])Vl(t);for(let t of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let e=Object.getOwnPropertyDescriptor(globalThis,t);e&&"value"in e&&Vl(e.value)}var Pd=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");Pd&&"value"in Pd&&Vl(Pd.value);typeof Buffer=="function"&&Vl(Buffer);var iv=(()=>{if(typeof Blob=="function")try{let t=new Blob([]);for(let e of Object.getOwnPropertySymbols(t)){let r=Object.getOwnPropertyDescriptor(t,e);if(r&&"value"in r&&typeof r.value=="object"&&r.value)return Object.getPrototypeOf(r.value)}}catch{return}})(),av=Map.prototype.entries,lv=Set.prototype.values,Fl=typeof Headers=="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,Yh=Fl&&"value"in Fl&&typeof Fl.value=="function"?Fl.value:void 0,cv=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function Gl(t){let e=Object.getOwnPropertyDescriptor(t,"constructor");if(!e||!("value"in e)||typeof e.value!="function")return;let r=e.value,n=Bt.call(r),o=sg.get(n);if(!og.has(n)||!o)return;let s=Object.getOwnPropertyDescriptor(r,"prototype");if(!(!s||!("value"in s)||s.value!==t||s.configurable!==!1||s.writable!==!1))return{constructor:r,descriptors:o,functionPrototype:Object.getPrototypeOf(r)}}function uv(t){return Hl.has(t)||Gl(t)!==void 0}function Rd(t,e,r){if(e===void 0)return t===void 0;if(typeof t!="function"||typeof e!="function")return!1;let n=Bt.call(e);if(Bt.call(t)!==n)return!1;let o=Object.getPrototypeOf(t);if(o===r)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n))return!1;let s=Gl(o);return s!==void 0&&Bt.call(s.constructor)===nv}function dv(t,e,r){return!e||t.configurable!==e.configurable||t.enumerable!==e.enumerable||"value"in t!="value"in e?!1:"value"in t&&"value"in e?t.writable!==e.writable?!1:typeof e.value=="function"?Rd(t.value,e.value,r):e.value!==null&&typeof e.value=="object"?!1:Object.is(t.value,e.value):Rd(t.get,e.get,r)&&Rd(t.set,e.set,r)}function eg(t){if(Xh)return Xh.call(Error,t);let e=t;for(let r=0;e!==null&&r<pa;r+=1){if(Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))return!1;e=Object.getPrototypeOf(e)}return e===null&&ev.call(t)==="[object Error]"}function pv(t,e){if(typeof e.get!="function"||typeof e.set!="function")return;let r=Object.getPrototypeOf(t);for(let n=0;r!==null&&n<pa;n+=1){let o=Object.getOwnPropertyDescriptor(r,"constructor");if(o&&"value"in o&&typeof o.value=="function"){let s=o.value;if(Bt.call(s)===tv&&uv(r)){let i=Object.getPrototypeOf(s);return Object.getPrototypeOf(e.get)===i&&Object.getPrototypeOf(e.set)===i?{constructor:s,prototype:r}:void 0}}r=Object.getPrototypeOf(r)}}function fv(t,e){if(!eg(t))return!1;if(oa&&!("value"in oa)&&typeof oa.get=="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,t)&&e.get===oa.get&&e.set===oa.set)return!0;let r=pv(t,e);if(!r)return!1;let n=Qh.get(r.prototype);if(!n){let o=Reflect.construct(r.constructor,[]);if(typeof o!="object"||o===null||!eg(o)||Object.getPrototypeOf(o)!==r.prototype||(n=Object.getOwnPropertyDescriptor(o,"stack"),!n||"value"in n||typeof n.get!="function"||typeof n.set!="function"))return!1;Qh.set(r.prototype,n)}return e.get===n.get&&e.set===n.set}function Md(){let t=[],e=0;return{get length(){return t.length-e},enqueue(r){t.push(r)},dequeue(){if(e===t.length)return;let r=t[e];return t[e]=void 0,e+=1,e===t.length?(t=[],e=0):e>=1024&&e*2>=t.length&&(t=t.slice(e),e=0),r},clear(){t=[],e=0}}}function mv(t){let e=Object.getPrototypeOf(t);for(let r=0;e!==null&&r<pa;r+=1){if(e===Date.prototype)return"Date";if(!Hl.has(e)){let o=Object.getOwnPropertyDescriptor(e,"constructor");if(o&&"value"in o&&typeof o.value=="function"&&Bt.call(o.value)===rv&&Gl(e))return"Date"}let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);if(n&&"value"in n&&typeof n.value=="string"&&cv.has(n.value))return n.value;e=Object.getPrototypeOf(e)}}function hv(t,e,r){if(ArrayBuffer.isView(t)){let a,l="typed-array";try{a=Gx?.call(t)}catch{l="data-view",a=Zx?.call(t)}return typeof a!="object"||a===null?{bytes:Number.POSITIVE_INFINITY,kind:l}:(e(a,r+1),{bytes:0,kind:l})}let n=mv(t);if(!n)return;let o,s="buffer";switch(n){case"ArrayBuffer":{o=Qx;break}case"SharedArrayBuffer":{o=Yx;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(Xx,t,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let i=o?.call(t);return{bytes:typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?i:Number.POSITIVE_INFINITY,kind:s}}function gv(t,e,r){if(e==="map"){for(let[n,o]of av.call(t))if(!r(n,8)||!r(o,8))return!1}if(e==="set"){for(let n of lv.call(t))if(!r(n,8))return!1}if(e==="headers"){if(!Yh)return!1;for(let[n,o]of Yh.call(t))if(!r(n,8)||!r(o,8))return!1}return!0}function yv(t,e,r){if(Array.isArray(t)){let o=Object.getOwnPropertyDescriptor(t,"length"),s=o&&"value"in o?o.value:void 0;if(typeof s!="number"||!Number.isSafeInteger(s)||s<0||s>Math.floor(r/16))return}if(e!=="typed-array")return Reflect.ownKeys(t);let n=Jx?.call(t);if(!(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>Kx))return Reflect.ownKeys(t).filter(o=>{if(typeof o!="string")return!0;let s=Number(o);return!Number.isInteger(s)||s<0||s>=n||String(s)!==o})}function ig(t,e,r,n,o,s){let i=yv(t,e,n());if(i===void 0)return!1;for(let a of i){if(!o(typeof a=="string"?a.length*2+8:8))return!1;typeof a=="symbol"&&s(a,r+1);let l=Object.getOwnPropertyDescriptor(t,a);if(!l)return!1;if(!("value"in l)){if(a==="stack"&&fv(t,l))continue;return!1}s(l.value,r+1,e==="blob")}return!0}function _v(t,e,r,n,o,s,i,a){let l=Object.getPrototypeOf(t);for(let c=e+1;l!==null;c+=1){if(c>=pa)return!1;if(Hl.has(l)||r&&l===iv)return!0;if(n.has(l))return i(l,c),o()>=0;n.add(l);let d=l;if(!a(d,()=>{if(!s(16))return!1;let f=Gl(d);if(!f)return ig(d,void 0,c,o,s,i);for(let g of Reflect.ownKeys(d)){let b=Object.getOwnPropertyDescriptor(d,g);if(!b)return!1;if(!dv(b,f.descriptors.get(g),f.functionPrototype)){if(!s(typeof g=="string"?g.length*2+8:8)||!("value"in b))return!1;typeof g=="symbol"&&i(g,c+1),i(b.value,c+1)}}return o()>=0}))return!1;l=Object.getPrototypeOf(d)}return!0}var wv=32,bv=32,ag=8,lg=16,Av=128*1024;function $d(t,e){let r=0,n=0,o=new WeakSet,s=new Set,i=new Set,a=new Map,l,c=()=>e-r,d=_=>!Number.isSafeInteger(_)||_<0?(r=e+1,!1):(r+=_,l?l.bytes+=_:n+=_,r<=e),m=_=>{l?l.edges.add(_):i.add(_)},f=(_,x)=>{m(_);let O={bytes:0,edges:new Set};a.set(_,O);let y=l;l=O;try{return x()}finally{l=y}},g=_=>{if(s.has(_)){m(_),d(8);return}s.add(_),f(_,()=>{if(!Zh)return!1;let x=Reflect.apply(Zh,_,[]);return d(8+(x?.length??0)*2)})||(r=e+1)},b=(_,x,O=!1)=>{if(!(r>e)){if(typeof _=="string"){d(_.length*2);return}if(typeof _=="symbol"){g(_);return}if(typeof _=="function"){r=e+1;return}if(_===null||typeof _!="object"){d(8);return}if(sv?.(_)){r=e+1;return}if(x>=pa){r=e+1;return}if(o.has(_)){m(_),d(8);return}o.add(_),f(_,()=>{if(!d(16))return!1;let y=hv(_,b,x);return!_v(_,x,O,o,c,d,b,f)||y!==void 0&&!d(y.bytes)||!gv(_,y?.kind,(S,I)=>d(I)?(b(S,x+1),r<=e):!1)?!1:ig(_,y?.kind,x,c,d,b)})||(r=e+1)}};try{b(t,0)}catch{return}return r<=e?{scalarBytes:n,roots:i,nodes:a}:void 0}function xv(t,e){if(t.size!==e.size)return!1;for(let r of t)if(!e.has(r))return!1;return!0}function Dd(t,e){return t.bytes+bv+t.edges.size*ag+e*lg}function Fd(t){return wv+t.scalarBytes+t.roots.size*ag}function vv(t,e,r,n){let o=new Set,s=[...t];for(;s.length;){if(n.remaining-=1,n.remaining<0)return;let i=s.pop();if(o.has(i))continue;let a=e.get(i)??r.get(i);if(!a)return;o.add(i);for(let l of a.edges)s.push(l)}return o}function zd(t,e,r,n,o){let s=n.get(t);if(s)return o&&(s.node=o),s;let i=o??e.nodes.get(t)??r.get(t);if(!i)return;let a={node:i,ownerDelta:0};return n.set(t,a),a}function Iv(t,e,r,n,o){let s=new Set([t]);for(let[i,a]of e.nodes){if(o.remaining-=1,o.remaining<0)return;let l=r.get(i);if(!l)continue;let c=!xv(l.edges,a.edges);if((l.bytes!==a.bytes||c)&&zd(i,e,r,n,a),!!c)for(let d of l.owners){if(o.remaining-=1,o.remaining<0)return;s.add(d)}}return s}function Sv(t,e,r,n,o,s){for(let i of t.identities){if(s.remaining-=1,s.remaining<0)return!1;if(!e.has(i)){let a=zd(i,r,n,o);if(!a)return!1;a.ownerDelta-=1}}for(let i of e){if(s.remaining-=1,s.remaining<0)return!1;if(!t.identities.has(i)){let a=zd(i,r,n,o);if(!a)return!1;a.ownerDelta+=1}}return!0}function Tv(t,e,r,n,o,s){let i=new Map;for(let a of r){let l=a===t?e.roots:a.roots,c=vv(l,e.nodes,n,s);if(!c||!Sv(a,c,e,n,o,s))return;i.set(a,c)}return i}function Ev(t,e,r,n,o,s){let i=t-(n?0:Fd(e))+Fd(r);for(let[a,l]of o){let c=s.get(a),d=(c?.owners.size??0)+l.ownerDelta;if(d<0)return;c&&(i-=Dd(c,c.owners.size)),d&&(i+=Dd(l.node,d))}return Number.isSafeInteger(i)&&i>=0&&i<=aa?i:void 0}function Ov(t,e,r){for(let[n,o]of e){let s=t.get(n);(s?.owners.size??0)+o.ownerDelta&&(s?(s.bytes=o.node.bytes,s.edges=o.node.edges):t.set(n,{bytes:o.node.bytes,edges:o.node.edges,owners:new Set}))}for(let[n,o]of r){for(let s of n.identities)o.has(s)||t.get(s)?.owners.delete(n);for(let s of o)n.identities.has(s)||t.get(s).owners.add(n);n.identities=o}for(let n of e.keys())t.get(n)?.owners.size===0&&t.delete(n)}function kv(){let t=new Map,e=0,r=(o,s,i)=>{let a={remaining:Av},l=new Map,c=Iv(o,s,t,l,a);if(!c)return!1;let d=Tv(o,s,c,t,l,a);if(!d)return!1;let m=Ev(e,o,s,i,l,t);return m===void 0?!1:(Ov(t,l,d),o.scalarBytes=s.scalarBytes,o.roots=s.roots,e=m,!0)};return{retain(o){let s={scalarBytes:0,roots:new Set,identities:new Set};return r(s,o,!0)?s:void 0},refresh(o,s){return r(o,s,!1)},release:o=>{e-=Fd(o);for(let s of o.identities){let i=t.get(s);i?.owners.delete(o)&&(e-=lg,i.owners.size===0&&(e-=Dd(i,0),t.delete(s)))}o.identities.clear()},clear(){t.clear(),e=0}}}var jr=class{constructor(){Ze.add(this),this.controller=new AbortController,zl.set(this,void 0),Bl.set(this,()=>{}),la.set(this,()=>{}),sa.set(this,void 0),Ul.set(this,()=>{}),ca.set(this,()=>{}),ut.set(this,Object.create(null)),ua.set(this,[]),da.set(this,new WeakMap),ia.set(this,new Set),zo.set(this,new Set),Lr.set(this,0),Pn.set(this,!1),Wl.set(this,!1),Kl.set(this,!1),Bo.set(this,!1),Rn.set(this,void 0),E(this,zl,new Promise((e,r)=>{E(this,Bl,e,"f"),E(this,la,r,"f")}),"f"),E(this,sa,new Promise((e,r)=>{E(this,Ul,e,"f"),E(this,ca,r,"f")}),"f"),u(this,zl,"f").catch(()=>{}),u(this,sa,"f").catch(()=>{})}_run(e){setTimeout(()=>{let r=!1;Promise.resolve().then(e).catch(n=>{r=!0,u(this,Ze,"m",ql).call(this,n)}).then(()=>{if(!r){try{this._emitFinal()}catch(n){u(this,Ze,"m",ql).call(this,n);return}this._emit("end")}})},0)}_connected(){this.ended||(u(this,Bl,"f").call(this),this._emit("connect"))}get ended(){return u(this,Pn,"f")}get errored(){return u(this,Wl,"f")}get aborted(){return u(this,Kl,"f")}abort(){this.controller.abort()}_userAbortError(){let e=new ie;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){u(this,Ze,"m",Nd).call(this,e);return}if(u(this,ua,"f").some(n=>n.signal===e))return;let r=()=>u(this,Ze,"m",Nd).call(this,e);e.addEventListener("abort",r,{once:!0}),u(this,ua,"f").push({signal:e,listener:r})}on(e,r){var n;return((n=u(this,ut,"f"))[e]||(n[e]=[])).push({listener:r}),this}off(e,r){let n=u(this,ut,"f")[e];if(!n)return this;let o=u(this,da,"f").get(r);if(o?.event===e&&!o.registration.removed&&!o.registration.detached)return u(this,Ze,"m",rg).call(this,e,o.registration),this;let s=n.findIndex(i=>!i.removed&&i.listener===r);return s!==-1&&n.splice(s,1),this}once(e,r){var n;return((n=u(this,ut,"f"))[e]||(n[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{E(this,Bo,!0,"f");let o=i=>{this.off(e,s),n(i)},s=(...i)=>{e!=="error"&&this.off("error",o),r(i.length>1?i:i[0])};e!=="error"&&u(this,Ze,"m",Ld).call(this,"error",o),u(this,Ze,"m",Ld).call(this,e,s)})}events(e){return this._createIterator(r=>{let n=(...o)=>{Cd.add(o);try{r(o)}finally{Cd.delete(o)}};return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!=="error",rejectOnAbort:e!=="abort"})}_createIterator(e,{rejectOnError:r=!0,rejectOnAbort:n=!0,onReturn:o}={}){let s=Md(),i=Md(),a=Md(),l=kv(),c=this.ended,d,m=!1,f=()=>{},g=()=>({value:void 0,done:!0}),b=()=>{for(;a.length;)a.dequeue().resolve(g())},_=()=>{!d||m||!a.length||(m=!0,a.dequeue().reject(d))},x=()=>{f(),this.off("end",D),r&&this.off("error",R),n&&this.off("abort",R)},O=$=>{$.active=!1,$.check&&(u(this,zo,"f").delete($.check),$.check=void 0)},y=($=!1)=>{if($){for(;i.length;)O(i.dequeue());s.clear(),l.clear()}let j=new A(`Event stream iterator buffer limit exceeded (${Jh} events or ${aa} bytes); consume events as they arrive.`);try{u(this,Ze,"m",ql).call(this,j)}finally{this.controller.abort()}return j},S=($,j)=>{if(!j.active||u(this,Pn,"f"))return;let M=$d($,aa);(!M||!l.refresh(j.retention,M))&&y(!0)},I=$=>{if(c)return;let j=a.dequeue();if(j)j.resolve({value:$,done:!1});else{if(s.length>=Jh){y();return}let M=$d($,aa),C=M&&l.retain(M);if(!C){y();return}if(typeof $=="object"&&$!==null&&Cd.has($)){let V=$;for(let Ne=0;Ne<V.length;Ne+=1){let Z=V[Ne];typeof Z=="string"&&(V[Ne]=Vx(Hx(Z)))}}let L={retention:C,active:!0,check:void 0};s.enqueue($),i.enqueue(L);let z=()=>{L.check=void 0,S($,L)};L.check=z,u(this,zo,"f").add(z)}},R=$=>{d=$,s.length||_()},k=()=>{if(d)return;let $=u(this,Rn,"f");$&&($.kind==="error"?r:n)&&(d=$.error)},D=()=>{c=!0,k(),x(),s.length||(_(),b())};return c||(f=e(I),this.on("end",D),r&&this.on("error",R),n&&this.on("abort",R)),{next:()=>{if(s.length){let $=s.dequeue(),j=i.dequeue();O(j);let M=$d($,aa);if(!M||!l.refresh(j.retention,M)){let C=y(!0);return m=!0,Promise.reject(C)}return l.release(j.retention),Promise.resolve({value:$,done:!1})}return(c||this.ended)&&k(),d&&!m?(m=!0,Promise.reject(d)):c?Promise.resolve(g()):new Promise(($,j)=>{a.enqueue({resolve:$,reject:j})})},return:()=>{for(c=!0,m=!0;i.length;)O(i.dequeue());return s.clear(),l.clear(),x(),b(),o&&(this.done().catch(()=>{}),o()),Promise.resolve(g())},[Symbol.asyncIterator](){return this}}}async done(){E(this,Bo,!0,"f"),await u(this,sa,"f")}_hasListeners(e){return!!u(this,ut,"f")[e]?.some(r=>!r.removed)}_emit(e,...r){if(u(this,Pn,"f"))return;e==="end"&&(u(this,Ze,"m",tg).call(this),E(this,Pn,!0,"f"),u(this,Ul,"f").call(this));let n=u(this,ut,"f")[e],o,s=!1;try{if(n){u(this,ut,"f")[e]=n.filter(i=>(i.once&&(i.detached=!0),!i.once&&!i.removed)),E(this,Lr,u(this,Lr,"f")+1,"f");try{for(let i of n)if(!i.removed){let{listener:a}=i;a(...r)}}finally{if(E(this,Lr,u(this,Lr,"f")-1,"f"),u(this,Lr,"f")===0){u(this,Ze,"m",jd).call(this);for(let i of u(this,zo,"f"))u(this,zo,"f").delete(i),u(this,Pn,"f")||i()}}}}catch(i){o=i,s=!0}try{u(this,Ze,"m",ng).call(this,e,r,!!n?.length)}catch(i){s||(o=i,s=!0)}if(s)throw o}_emitFinal(){}};zl=new WeakMap,Bl=new WeakMap,la=new WeakMap,sa=new WeakMap,Ul=new WeakMap,ca=new WeakMap,ut=new WeakMap,ua=new WeakMap,da=new WeakMap,ia=new WeakMap,zo=new WeakMap,Lr=new WeakMap,Pn=new WeakMap,Wl=new WeakMap,Kl=new WeakMap,Bo=new WeakMap,Rn=new WeakMap,Ze=new WeakSet,Nd=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},tg=function(){for(let{signal:e,listener:r}of u(this,ua,"f").splice(0))e.removeEventListener("abort",r)},Ld=function(e,r){let n=u(this,ut,"f")[e],o=n?.length??0;this.once(e,r);let s=u(this,ut,"f")[e],[i]=s?.slice(-1)??[];(n===void 0||s===n)&&s?.length===o+1&&i?.listener===r&&i.once&&u(this,da,"f").set(r,{event:e,registration:i})},rg=function(e,r){r.removed||(r.removed=!0,u(this,da,"f").delete(r.listener),u(this,ia,"f").add(e),u(this,Lr,"f")===0&&u(this,Ze,"m",jd).call(this))},jd=function(){for(let e of u(this,ia,"f")){let r=e,n=u(this,ut,"f")[r];n&&(u(this,ut,"f")[r]=n.filter(o=>!o.removed))}u(this,ia,"f").clear()},ql=function(e){if(E(this,Wl,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=this._userAbortError()),e instanceof ie)return E(this,Kl,!0,"f"),this._emit("abort",e);if(e instanceof A)return this._emit("error",e);if(e instanceof Error){let r=new A(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new A(String(e)))},ng=function(e,r,n){if(e==="abort"){let o=r[0];E(this,Rn,u(this,Rn,"f")??{kind:"abort",error:o},"f"),!u(this,Bo,"f")&&!n&&Promise.reject(o),u(this,la,"f").call(this,o),u(this,ca,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];E(this,Rn,u(this,Rn,"f")??{kind:"error",error:o},"f"),!u(this,Bo,"f")&&!n&&Promise.reject(o),u(this,la,"f").call(this,o),u(this,ca,"f").call(this,o),this._emit("end")}};function cg(t){return typeof t.parse=="function"}var ze,Mn,Jl,Zl,Bd,Xl,Ud,qd,Wd,Kd,ug,dg,Cv=10;function Pv(t){for(let e of t.choices)for(let r of e.message.tool_calls??[])r.id||(r.id=`call_${_t()}`)}function Rv(t){if(!rr(t))return t;let e={role:"assistant"};return t.audio!=null&&(e.audio={id:t.audio.id}),t.content!==void 0&&(e.content=t.content),t.function_call!=null&&(e.function_call=t.function_call),t.name!==void 0&&(e.name=t.name),t.refusal!=null&&(e.refusal=t.refusal),t.tool_calls!==void 0&&(e.tool_calls=t.tool_calls.map(r=>r.type==="custom"?{id:r.id,type:r.type,custom:{input:r.custom.input,name:r.custom.name}}:{id:r.id,type:r.type,function:{arguments:r.function.arguments,name:r.function.name}})),e}var $n=class extends jr{constructor(){super(...arguments),ze.add(this),this._chatCompletions=[],Jl.set(this,!1),Zl.set(this,!1),this.messages=[]}_addChatCompletion(e){E(this,Jl,!this.controller.signal.aborted,"f"),Pv(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,n=!0){if(n&&!("content"in e)&&(e.content=null),this.messages.push(e),r){if(this._emit("message",e),na(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(rr(e)&&e.tool_calls)for(let o of e.tool_calls)o.type==="function"&&this._emit("functionToolCall",o.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new A("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,ze,"m",Bd).call(this)}async finalMessage(){return await this.done(),u(this,ze,"m",Xl).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,ze,"m",Ud).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,ze,"m",qd).call(this)}async totalUsage(){return await this.done(),u(this,ze,"m",Wd).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){u(this,Zl,"f")&&u(this,ze,"m",Kd).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=u(this,ze,"m",Xl).call(this);r&&this._emit("finalMessage",r);let n=u(this,ze,"m",Bd).call(this);n&&this._emit("finalContent",n);let o=u(this,ze,"m",Ud).call(this);o&&this._emit("finalFunctionToolCall",o);let s=u(this,ze,"m",qd).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",u(this,ze,"m",Wd).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),u(Mn,Mn,"m",ug).call(Mn,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ra(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:i="auto",stream:a,toolContext:l,...c}=r,d=l,m=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=Cv,afterCompletion:g}=o||{},b=async I=>{g!=null&&(E(this,Zl,!0,"f"),await g(I,n),u(this,ze,"m",Kd).call(this))},_=r.tools.map(I=>{if(bt(I)){if(!I.$callback)throw new A("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:I.$callback,name:I.function.name,description:I.function.description||"",parameters:I.function.parameters,parse:I.$parseRaw,strict:!0}}}return I}),x=Object.create(null);for(let I of _)I.type==="function"&&(x[I.function.name||I.function.function.name]=I.function);let O="tools"in r?_.map(I=>I.type==="function"?{type:"function",function:{name:I.function.name||I.function.function.name,parameters:I.function.parameters,description:I.function.description,strict:I.function.strict}}:I):void 0;for(let I of r.messages)this._addMessage(I,!1,!1);let y=!1,S=async I=>{let R=y;if(y=!1,I.type!=="function")return{message:void 0,functionCalled:!1};let k=I.id,{name:D,arguments:$}=I.function,j=x[D];if(!j){let L=`Invalid tool_call: ${JSON.stringify(D)}. Available options are: ${Object.keys(x).map(z=>JSON.stringify(z)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:k,content:L},functionCalled:!1}}if(m&&m!==D){let L=`Invalid tool_call: ${JSON.stringify(D)}. ${JSON.stringify(m)} requested. Please try again`;return{message:{role:s,tool_call_id:k,content:L},functionCalled:!1}}let M;if(cg(j)){let L;try{L=await j.parse($)}catch(z){if(this.controller.signal.aborted)throw this._userAbortError();let V=z instanceof Error?z.message:String(z);return{message:{role:s,tool_call_id:k,content:V},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{M=await j.function(L,n,d)}catch(z){throw this.controller.signal.aborted&&Object.is(z,this.controller.signal.reason)?this._userAbortError():z}}else{if(this.controller.signal.aborted&&!R)throw this._userAbortError();try{M=await j.function($,n,d)}catch(L){throw this.controller.signal.aborted&&Object.is(L,this.controller.signal.reason)?this._userAbortError():L}}let C=u(Mn,Mn,"m",dg).call(Mn,M);return{message:{role:s,tool_call_id:k,content:C},functionCalled:!0}};for(let I=0;I<f;++I){let R=await this._createChatCompletion(e,{...c,tool_choice:i,tools:O,messages:this.messages.map(Rv)},o);y=this.controller.signal.aborted&&u(this,Jl,"f");let k=R.choices[0]?.message;if(!k)throw new A("missing message in ChatCompletion response");if(!k.tool_calls?.length){await b(R);return}if(m||r.parallel_tool_calls===!1)for(let D of k.tool_calls){let $=await S(D);if($.message&&this._addMessage($.message),this.controller.signal.aborted)throw this._userAbortError();if(m&&$.functionCalled){await b(R);return}}else{let D=await Promise.allSettled(k.tool_calls.map(S));if(!this.controller.signal.aborted){for(let $ of D)if($.status==="rejected")throw $.reason}for(let $ of D)$.status==="fulfilled"&&$.value.message&&this._addMessage($.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await b(R)}}};Mn=$n,Jl=new WeakMap,Zl=new WeakMap,ze=new WeakSet,Bd=function(){return u(this,ze,"m",Xl).call(this).content??null},Xl=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(rr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new A("stream ended without producing a ChatCompletionMessage with role=assistant")},Ud=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(rr(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}}},qd=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(na(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}},Wd=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},Kd=function(){if(this.controller.signal.aborted)throw this._userAbortError()},ug=function(e){if(e.n!=null&&e.n>1)throw new A("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},dg=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var fa=class t extends $n{static runTools(e,r,n){let o=new t,s={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0,n=!0){super._addMessage(e,r,n),r&&rr(e)&&e.content&&this._emit("content",e.content)}};var ke={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},Hd=class extends Error{},ma=class extends Error{};function Mv(t,e=ke.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return $v(t.trim(),e)}var $v=(t,e)=>{let r=t.length,n=0,o=f=>{throw new Hd(`${f} at position ${n}`)},s=f=>{throw new ma(`${f} at position ${n}`)},i=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?l():t[n]==="["?c():t.substring(n,n+4)==="null"||ke.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ke.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ke.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ke.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ke.MINUS_INFINITY&e&&r-n>1&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ke.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,Number.NaN):d()),a=()=>{let f=n,g=!1;for(n++;n<r&&(t[n]!=='"'||g&&t[n-1]==="\\");)g=t[n]==="\\"?!g:!1,n++;if(t.charAt(n)==='"')try{return JSON.parse(t.substring(f,++n-Number(g)))}catch(b){s(String(b))}else if(ke.STR&e)try{return JSON.parse(t.substring(f,n-Number(g))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},l=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&ke.OBJ&e)return f;let g=a();m(),n++;try{let b=i();Object.defineProperty(f,g,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(ke.OBJ&e)return f;throw b}m(),t[n]===","&&n++}}catch{if(ke.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},c=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(i()),m(),t[n]===","&&n++}catch{if(ke.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},d=()=>{if(n===0){t==="-"&&ke.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(b){if(ke.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(b))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n===r&&!(ke.NUM&e)&&o("Unterminated number literal");let g=t.substring(f,n);try{return JSON.parse(g)}catch{g==="-"&&ke.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(g.substring(0,g.lastIndexOf("e")))}catch(b){s(String(b))}}},m=()=>{for(;n<r&&`
56
+ \r `.includes(t[n]);)n++};return i()},pg=t=>Mv(t,ke.ALL^ke.NUM);var oe,be,Ql,Dr,Nn,Be,dt,et,Vd,Uo,Gd,Jd,Zd,qo,ha,fg;function mg(t){try{return pg(t)}catch(e){if(e instanceof ma||e instanceof SyntaxError)return wt({type:"json_schema",$parseRaw:void 0},t);throw e}}var ap="chat.completion.chunk.message:";function bg(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:`${ap}${JSON.stringify(n)}`}}function Nv(t){return"type"in t&&t.type==="message"&&"message"in t||"object"in t&&typeof t.object=="string"&&t.object.startsWith(ap)}function Lv(t){return"type"in t?t:JSON.parse(t.object.slice(ap.length))}var Yl=128,Fr=128,jv=16*1024*1024,Dv=65536,lp=128,Ag=64*1024*1024,hg=1024;function np(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function op(t,e,r,n){if(e.fragments>=Dv)throw new A("Chat completion stream exceeded its structured JSON fragment limit");let o=0,{depth:s,escaped:i,has_non_whitespace:a,in_string:l}=t,c=!1,d=!0;for(let f of r){let g=o,b=f.codePointAt(0);if(d&&t.pending_high_surrogate&&b>=56320&&b<=57343||b<=127?o+=1:b<=2047?o+=2:b<=65535?o+=3:o+=4,d=!1,e.bytes+o>jv)throw new A("Chat completion stream exceeded its structured JSON byte limit");if(n&&n.work+o>Ag)throw n.work+=g,new A("Chat completion stream exceeded its structured JSON parse-work limit");if(f!==" "&&f!==`
57
+ `&&f!=="\r"&&f!==" "&&(a=!0),l){i?i=!1:f==="\\"?i=!0:f==='"'&&(l=!1,c||(c=s===0));continue}if(f==='"')l=!0;else if(f==="{"||f==="["){if(s+=1,s>lp)throw new A("Chat completion stream exceeded its structured JSON nesting depth limit")}else(f==="}"||f==="]")&&s>0&&(s-=1,c||(c=s===0))}if(t.bytes+=o,t.fragments+=1,t.depth=s,t.escaped=i,t.has_non_whitespace=a,t.in_string=l,r.length>0){let f=r.codePointAt(r.length-1)??0;t.pending_high_surrogate=f>=55296&&f<=56319}if(e.bytes+=o,e.fragments+=1,n&&(n.work+=o),!a||o===0)return!1;let m=Math.max(hg,Math.floor(t.last_parsed_bytes/2));return!(t.bytes>hg&&!c&&t.bytes-t.last_parsed_bytes<m)}function sp(t,e){return e.work+t.bytes>Ag?!1:(e.work+=t.bytes,t.work+=t.bytes,t.last_parsed_bytes=t.bytes,!0)}function pt(t,e){let r=Object.getOwnPropertyDescriptor(t,e);if(!r){let n=Object.getPrototypeOf(t);for(let o=0;n!==null;o+=1){if(o>=lp||Object.getOwnPropertyDescriptor(n,e))throw new A("Chat completion stream contains an unsafe structured JSON snapshot");n=Object.getPrototypeOf(n)}return}if(!("value"in r)||typeof r.value!="string"&&r.value!==null&&r.value!==void 0)throw new A("Chat completion stream contains an unsafe structured JSON snapshot");return r.value}function ga(t){let e=Object.getOwnPropertyDescriptor(t,"message");if(!e||!("value"in e)||typeof e.value!="object"||e.value===null)throw new A("Chat completion stream contains an unsafe structured JSON snapshot");return e.value}function gg(t,e,r,n){let o=Object.getOwnPropertyDescriptor(t,e);if(!o){let i=Object.getPrototypeOf(t);for(let a=0;i!==null;a+=1){if(a>=lp||Object.getOwnPropertyDescriptor(i,e))throw new A(`Chat completion stream contains an unsafe snapshot ${n} collection`);i=Object.getPrototypeOf(i)}return}if(!("value"in o)||!Array.isArray(o.value))throw new A(`Chat completion stream contains an unsafe snapshot ${n} collection`);let s=Object.getOwnPropertyDescriptor(o.value,"length");if(!s||!("value"in s)||!Number.isSafeInteger(s.value)||s.value>r)throw new A(`Chat completion stream exceeded its snapshot ${n} limit`);return o.value}function Xd(t,e){let r=Object.getOwnPropertyDescriptor(t,e);if(r){if(!("value"in r))throw new A("Chat completion stream contains an unsafe structured JSON snapshot");return r.value}}function yg(t,e,r,n){let o=Object.getOwnPropertyDescriptor(t,"length"),s=o&&"value"in o?o.value:void 0;if(typeof s!="number"||!Number.isSafeInteger(s)||s<0||s>e)throw new A(`Chat completion stream exceeded its snapshot ${r} limit`);let i=[];i.length=s;for(let a=0;a<s;a+=1){let l=Object.getOwnPropertyDescriptor(t,a);if(l){if(!("value"in l))throw new A("Chat completion stream contains an unsafe structured JSON snapshot");i[a]=n(l.value,a)}}return i}function Ln(t,e,r){let n=np(),o=e??{bytes:0,fragments:0,work:0};if(op(n,o,t,r),!sp(n,o))throw new A("Chat completion stream exceeded its structured JSON parse-work limit");return t}function ec(t){let e=Object.getOwnPropertyDescriptor(t,"type"),r=Object.getOwnPropertyDescriptor(t,"function");if(!e||!("value"in e)||e.value!=="function"||!r||!("value"in r)||typeof r.value!="object"||r.value===null)return;let n=Object.getOwnPropertyDescriptor(r.value,"name");if(!(!n||!("value"in n)||typeof n.value!="string"||n.value.length===0))return{type:"function",name:n.value}}function Qd(t,e){let r=ec(t);if(!r||r.name!==e.name||r.type!==e.type)throw new A("Chat completion stream contains a changed tool call identity")}function ya(t,e){return Object.prototype.propertyIsEnumerable.call(e,"__proto__")&&!N(t,"__proto__")&&Object.defineProperty(t,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(t,e)}function _a(t,e=[]){let r=Object.getOwnPropertyDescriptors(t);for(let n of e){let o=r[n];!o&&!(n in t)||(r[n]={value:o&&"value"in o?o.value:Reflect.get(t,n,t),enumerable:o?.enumerable??!1,configurable:o?.configurable??!0,writable:o&&"writable"in o?o.writable:!1})}return Object.create(Object.getPrototypeOf(t),r)}function Fv(t){let e=_a(t);if(t.tools){let r=[],n=Object.getOwnPropertyDescriptor(t.tools,"length"),o=n&&"value"in n?n.value:void 0,s=typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?Math.min(o,Fr):0;for(let i=0;i<s;i+=1){let a=Object.getOwnPropertyDescriptor(t.tools,String(i));if(!a||!("value"in a)){r.length=i+1;continue}let l=a.value,c=_a(l,["type","$brand","$parseRaw","$callback","function"]),d=Object.getOwnPropertyDescriptors(c);if(Ft(c)){let m=d.function;d.function={...m&&"value"in m?m:{configurable:!0,enumerable:!0,writable:!0},value:_a(c.function,["name","strict"])}}r[i]=Object.create(Object.getPrototypeOf(l),d)}e.tools=r}return t.response_format&&(e.response_format=_a(t.response_format,["type","$brand","$parseRaw"])),e}var Yd=4096,ep=JSON.stringify,zv=1024*1024,Bv=64,tp=Symbol("omitted serialized parser value"),Ce=Symbol("unsafe serialized parser value");function xg(t,e){let r=new WeakSet,n=s=>!Number.isSafeInteger(s)||s<0||e.bytes+s>zv?!1:(e.bytes+=s,!0),o=(s,i)=>{if(i>Bv||e.nodes>=Yd)return Ce;if(e.nodes+=1,s===void 0||typeof s=="function"||typeof s=="symbol")return tp;if(typeof s=="bigint")return Ce;if(s===null||typeof s=="boolean"||typeof s=="number"){let c=ep(s);return typeof c=="string"&&n(c.length)?c:Ce}if(typeof s=="string")return n(s.length*6+2)?ep(s):Ce;if(typeof s!="object"||r.has(s))return Ce;let a=Array.isArray(s),l=Object.getPrototypeOf(s);if(a&&l!==Array.prototype||!a&&l!==null&&l!==Object.prototype)return Ce;for(let c=s;c!==null;c=Object.getPrototypeOf(c)){let d=Object.getOwnPropertyDescriptor(c,"toJSON");if(d){if(!("value"in d)||typeof d.value=="function")return Ce;break}}r.add(s);try{if(!n(2))return Ce;if(a){let f=Object.getOwnPropertyDescriptor(s,"length"),g=f&&"value"in f?f.value:void 0;if(typeof g!="number"||!Number.isSafeInteger(g)||g<0||g>Yd-e.nodes)return Ce;let b=[];for(let _=0;_<g;_+=1){let x=String(_),O=Object.getOwnPropertyDescriptor(s,x);if(!O){if(Object.getOwnPropertyDescriptor(Array.prototype,x)||Object.getOwnPropertyDescriptor(Object.prototype,x)||(e.nodes+=1,!n(4)))return Ce;b.push("null");continue}if(!("value"in O))return Ce;let y=o(O.value,i+1);if(y===Ce)return y;b.push(y===tp?"null":y)}return`[${b.join(",")}]`}let c=Reflect.ownKeys(s);if(c.length>Yd-e.nodes)return Ce;let d=[];for(let f of c){if(typeof f!="string")continue;let g=Object.getOwnPropertyDescriptor(s,f);if(!g)return Ce;if(g.enumerable){if(!("value"in g))return Ce;d.push([f,g.value])}}d.sort(([f],[g])=>f===g?0:f<g?-1:1);let m=[];for(let[f,g]of d){let b=o(g,i+1);if(b===Ce)return b;if(b!==tp){if(!n(f.length*6+3))return Ce;m.push(`${ep(f)}:${b}`)}}return`{${m.join(",")}}`}finally{r.delete(s)}};try{let s=o(t,0);return typeof s=="string"?s:void 0}catch{return}}function _g(t,e,r,n){let o=Object.getOwnPropertyDescriptor(e,"$parseRaw"),s=Object.getOwnPropertyDescriptor(r,n);if(!o||!("value"in o)||typeof o.value!="function"||!s||!("value"in s))return;let i=xg(s.value,{nodes:0,bytes:0});i!==void 0&&t.set(e,i)}function wg(t,e,r,n,o){let s=e&&t.get(e),i=Object.getOwnPropertyDescriptor(r,n);return s!==void 0&&i!==void 0&&"value"in i&&xg(o,{nodes:0,bytes:0})===s}function Wo(t,e){return t&&"value"in t?{...t,value:e}:{configurable:!0,enumerable:!0,writable:!0,value:e}}function ip(t,e,r){for(let n of r){let o=t[n];!o&&!(n in e)||(t[n]=o&&"value"in o?{...o,value:void 0}:{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:!1,value:void 0})}}function Uv(t){let e=t.source??{type:t.type,...t.type==="function"?{function:{}}:{}},r=Object.getOwnPropertyDescriptors(e);if(r.type=Wo(r.type,t.type),t.type!=="function"||!t.function)return r.function&&(r.function=Wo(r.function,void 0)),ip(r,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),r);let n=r.function,o=n&&"value"in n&&typeof n.value=="object"&&n.value!==null?n.value:{},s=Object.getOwnPropertyDescriptors(o);return s.name=Wo(s.name,t.function.name),s.strict=Wo(s.strict,t.function.strict),r.function=Wo(n,Object.create(Object.getPrototypeOf(o),s)),t.function.schemaMatches||ip(r,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),r)}function qv(t){let e=t.source??{type:t.type},r=Object.getOwnPropertyDescriptors(e);return r.type=Wo(r.type,t.type),(t.type!=="json_schema"||!t.source||!t.schemaMatches)&&ip(r,e,["$brand","$parseRaw"]),Object.create(Object.getPrototypeOf(e),r)}function rp(t,e){let r=Object.getOwnPropertyDescriptor(t,e);if(!r||!("value"in r))return;let{value:n}=r;return typeof n=="object"&&n!==null?n:void 0}function Wv(t,e,r){let n=new WeakMap,o=new WeakMap;if(t.tools)for(let g=0;g<t.tools.length&&g<Fr;g+=1){let b=rp(t.tools,String(g)),_=e.tools?.[g];if(b&&_){n.set(b,_);let x=rp(_,"function");x&&_g(o,_,x,"parameters")}}e.response_format&&_g(o,e.response_format,e.response_format,"json_schema");let s,i,a,l,c=[],d=new WeakMap,m=new Map,f=new WeakMap;return Qm(t,{value(g,b,_){if(!s&&b===""&&typeof _=="object"&&_!==null){s=_,i=void 0,a=void 0,l=void 0,c=[],d=new WeakMap,m=new Map,f=new WeakMap;return}if(g===s&&b==="response_format"){typeof _=="object"&&_!==null&&(a=_,l={source:rp(g,b)===t.response_format?e.response_format:void 0,schemaMatches:!1});return}if(g===s&&b==="tools")return Array.isArray(_)?(i=new Proxy(_,{get(y,S){let I=Reflect.get(y,S,y);if(typeof S=="string"){let R=Number(S);Number.isSafeInteger(R)&&R>=0&&R<Fr&&String(R)===S&&m.set(R,typeof I=="object"&&I!==null?I:void 0)}return I}}),i):void 0;if(g===i){let y=Number(b);if(!Number.isSafeInteger(y)||y<0||y>=Fr||typeof _!="object"||_===null)return;let S=m.get(y),R={source:S?n.get(S):void 0};c[y]=R,d.set(_,R);return}let x=d.get(g);if(x){if(b==="type"&&typeof _=="string")x.type=_;else if(b==="function"&&typeof _=="object"&&_!==null){let y={source:x.source,schemaMatches:!1};x.function=y,f.set(_,y)}return}if(g===a&&l){b==="type"&&typeof _=="string"?l.type=_:b==="json_schema"&&(l.schemaMatches=wg(o,l.source,g,b,_));return}let O=f.get(g);O&&(b==="name"&&typeof _=="string"?O.name=_:b==="strict"&&typeof _=="boolean"?O.strict=_:b==="parameters"&&(O.schemaMatches=wg(o,O.source,g,b,_)))},complete(){if(!s)return;let g=_a(e);if(i){let b=[];for(let _=0;_<c.length;_+=1){let x=c[_];x&&(b[_]=Uv(x))}g.tools=b}else delete g.tools;l?g.response_format=qv(l):delete g.response_format,r(g),s=void 0,i=void 0,a=void 0,l=void 0,c=[],d=new WeakMap,m=new Map,f=new WeakMap}})}var jn=class t extends $n{constructor(e){super(),oe.add(this),be.set(this,void 0),Ql.set(this,!1),Dr.set(this,void 0),Nn.set(this,void 0),Be.set(this,void 0),dt.set(this,void 0),et.set(this,void 0),E(this,be,e,"f"),E(this,Dr,new Set,"f"),E(this,Nn,[],"f"),E(this,dt,!1,"f");let r=e?.tools,n=r&&Object.getOwnPropertyDescriptor(r,"length"),o=n&&"value"in n?n.value:void 0;if(r&&typeof o=="number"&&Number.isSafeInteger(o)&&o>=0)for(let s=0;s<Math.min(o,Fr);s+=1){let i=Object.getOwnPropertyDescriptor(r,String(s));if(!i||!("value"in i))continue;let a=i.value;if(Ft(a)&&(bt(a)||a.function.strict===!0)){E(this,dt,!0,"f");break}}E(this,et,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return u(this,Be,"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,__metadata:{...n?.__metadata,helperMethod:"stream"}})),o}_runTools(e,r,n,o){return E(this,Ql,!0,"f"),super._runTools(e,r,n,o)}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0};E(this,be,o,"f"),u(this,oe,"m",Vd).call(this);let s=Fv(o);E(this,be,s,"f"),E(this,dt,s.tools?.some(l=>Ft(l)&&(bt(l)||l.function.strict===!0))??!1,"f");let i=o.tools||o.response_format?Wv(o,s,l=>{E(this,be,l,"f"),E(this,dt,l.tools?.some(c=>Ft(c)&&(bt(c)||c.function.strict===!0))??!1,"f")}):void 0,a=await e.chat.completions.create(o,{...n,signal:this.controller.signal}).finally(i);this._connected();for await(let l of a)u(this,oe,"m",Gd).call(this,l);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(u(this,oe,"m",ha).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),u(this,oe,"m",Vd).call(this),this._connected();let n=Je.fromReadableStream(e,this.controller),o;for await(let i of n){if("error"in i&&N(i,"error")&&typeof i.error=="object"&&i.error!==null)throw new ee(void 0,i.error,void 0,void 0);if(Nv(i)){let l=Lv(i);if(u(this,Be,"f")){let c=u(this,Be,"f").choices[0]?.message.tool_calls;for(let[d,m]of l.tool_call_ids?.entries()??[]){let f=c?.[d];f&&m&&(f.id=m)}this._addChatCompletion(u(this,oe,"m",ha).call(this)),o=void 0}this._addMessage(l.message);continue}let a=i;o&&a.id&&o!==a.id&&this._addChatCompletion(u(this,oe,"m",ha).call(this)),u(this,oe,"m",Gd).call(this,a),a.id&&(o=a.id)}if(n.controller.signal?.aborted)throw this._userAbortError();if(u(this,Be,"f"))return this._addChatCompletion(u(this,oe,"m",ha).call(this));let s=this._chatCompletions[this._chatCompletions.length-1];if(s)return s;throw new A("request ended without sending any chunks")}[(be=new WeakMap,Ql=new WeakMap,Dr=new WeakMap,Nn=new WeakMap,Be=new WeakMap,dt=new WeakMap,et=new WeakMap,oe=new WeakSet,Vd=function(){this.ended||(E(this,Dr,new Set,"f"),E(this,Be,void 0,"f"),E(this,et,{bytes:0,fragments:0,work:0},"f"))},Uo=function(r){let n=u(this,Nn,"f")[r.index];return n||(n={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},u(this,Nn,"f")[r.index]=n,n)},Gd=function(r){if(this.ended)return;let n=new WeakMap,o=u(this,oe,"m",fg).call(this,r,n);this._emit("chunk",r,o);for(let s of r.choices){let i=n.get(s),a=o.choices[i?.index??s.index],l=i?.tool_calls??[],{delta:c}=s,d=zt(u(this,be,"f")?.response_format),m=d||u(this,dt,"f"),f=m?ga(a):a.message,g=m?pt(f,"refusal"):f.refusal,_=!g&&d?pt(f,"content"):f.content;c?.content!=null&&f.role==="assistant"&&_&&(this._emit("content",c.content,_),this._emit("content.delta",{delta:c.content,snapshot:_,parsed:f.parsed})),c?.refusal!=null&&f.role==="assistant"&&g&&this._emit("refusal.delta",{delta:c.refusal,snapshot:g}),s.logprobs?.content!=null&&f.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:a.logprobs?.content??[]}),s.logprobs?.refusal!=null&&f.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});let x=u(this,oe,"m",Uo).call(this,a);a.finish_reason&&(u(this,oe,"m",Zd).call(this,a),x.current_tool_call_index!=null&&u(this,oe,"m",Jd).call(this,a,x.current_tool_call_index));for(let O of l)x.current_tool_call_index!==O.index&&(u(this,oe,"m",Zd).call(this,a),x.current_tool_call_index!=null&&u(this,oe,"m",Jd).call(this,a,x.current_tool_call_index)),x.current_tool_call_index=O.index;for(let O of l){let y=f.tool_calls?.[O.index];if(y?.type)if(y.type==="function"){let S=x.tool_call_identities.get(O.index),I;if(S?.parseable){let R=pt(y.function,"arguments");if(typeof R!="string")throw new A("Chat completion stream contains an unsafe structured JSON snapshot");I=R}else I=y.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:y.function.name,index:O.index,arguments:I,parsed_arguments:y.function.parsed_arguments,arguments_delta:O.arguments_delta})}else y.type!=="custom"&&y}}},Jd=function(r,n){let o=u(this,oe,"m",Uo).call(this,r);if(o.done_tool_calls.has(n))return;let i=(u(this,dt,"f")?ga(r):r.message).tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");let a=o.tool_call_identities.get(n);if(a&&Qd(i,a),!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let l=u(this,be,"f")?.tools?.find(f=>Ft(f)&&f.function.name===i.function.name),c=null,d=bt(l)||l?.function.strict===!0,m;if(d){u(this,Be,"f")&&u(this,oe,"m",qo).call(this,u(this,Be,"f"));let f=pt(i.function,"arguments");if(typeof f!="string")throw new A("Chat completion stream contains an unsafe structured JSON snapshot");m=f}else m=i.function.arguments;bt(l)?c=l.$parseRaw(Ln(m)):l?.function.strict&&(c=wt({type:"json_schema",$parseRaw:void 0},Ln(m))),r.finish_reason&&o.done_tool_calls.add(n),this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:n,arguments:m,parsed_arguments:c})}else i.type!=="custom"&&i},Zd=function(r){let n=u(this,oe,"m",Uo).call(this,r),o=zt(u(this,be,"f")?.response_format),s=o||u(this,dt,"f"),i=s?ga(r):r.message,a=s?pt(i,"refusal"):i.refusal,l=!a&&o,c=l?pt(i,"content"):i.content;c!=null&&(c!==""||!a&&!i.tool_calls?.length&&!i.function_call)&&!n.content_done&&(l&&u(this,Be,"f")&&u(this,oe,"m",qo).call(this,u(this,Be,"f")),n.content_done=!0,this._emit("content.done",{content:c,parsed:a?null:wt(u(this,be,"f")?.response_format,l?Ln(c):c)})),a&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:a})),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}))},qo=function(r){let n={bytes:0,fragments:0,work:0},o=zt(u(this,be,"f")?.response_format),s=new WeakMap,i=gg(r,"choices",Yl,"choice");if(!i)throw new A("Chat completion stream contains an unsafe snapshot choice collection");for(let a=0;a<i.length;a+=1){let l=Xd(i,a);if(!l)continue;let c=ga(l),d=pt(c,"refusal"),m=pt(c,"content"),f=new Map,g=gg(c,"tool_calls",Fr,"tool-call");s.set(l,Object.freeze({message:c,content:m,refusal:d,toolCallCollection:g,toolCalls:f}));let b=u(this,Nn,"f")[l.index];o&&!d&&typeof m=="string"&&Ln(m,n,u(this,et,"f"));for(let[_,x]of b?.tool_call_identities??[]){let O=g&&Xd(g,_);if(!O)throw new A("Chat completion stream contains a changed tool call identity");Qd(O,x)}if(u(this,dt,"f"))for(let _=0;_<(g?.length??0);_+=1){let x=Xd(g,_);if(!x)continue;let O=ec(x);if(!O){let R=Object.getOwnPropertyDescriptor(x,"type");if(R&&!("value"in R))throw new A("Chat completion stream contains an unsafe structured JSON snapshot");if(R?.value!=="function")continue;let k=Object.getOwnPropertyDescriptor(x,"function");if(k&&!("value"in k))throw new A("Chat completion stream contains an unsafe structured JSON snapshot");if(k&&typeof k.value=="object"&&k.value!==null){let D=Object.getOwnPropertyDescriptor(k.value,"name");if(D&&!("value"in D))throw new A("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!jl(u(this,be,"f"),{type:O.type,function:{name:O.name}}))continue;let y=Object.getOwnPropertyDescriptor(x,"function");if(!y||!("value"in y))throw new A("Chat completion stream contains an unsafe structured JSON snapshot");let S=y.value,I=pt(S,"arguments");if(typeof I!="string")throw new A("Chat completion stream contains an unsafe structured JSON snapshot");Ln(I,n,u(this,et,"f")),f.set(_,Object.freeze({tool:x,function:S,type:O.type,name:O.name,arguments:I}))}}return s},ha=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let r=u(this,Be,"f");if(!r)throw new A("request ended without sending any chunks");let n=u(this,oe,"m",qo).call(this,r),o=u(this,Dr,"f");return E(this,Dr,new Set,"f"),E(this,Be,void 0,"f"),E(this,Nn,[],"f"),Kv(r,u(this,be,"f"),o,n)},fg=function(r,n){var o,s,i,a,l;let c=u(this,Be,"f"),{choices:d,obfuscation:m,...f}=r;if(c)r.id&&ya(c,f);else{let _={...f,choices:[]};E(this,Be,_,"f"),c=_}let g=u(this,be,"f")?.n,b=typeof g=="number"&&Number.isSafeInteger(g)&&g>0?Math.min(g,Yl):Yl;for(let _ of r.choices){let{delta:x,finish_reason:O,index:y,logprobs:S=null,...I}=_,R=[];if(n.set(_,Object.freeze({index:y,tool_calls:R})),!Number.isSafeInteger(y)||y<0||y>=b)throw new A(`Chat completion stream contains an invalid choice index: ${y}`);let k=c.choices[y];if(!k){let Z={finish_reason:O,index:y,message:{},logprobs:null,...I};c.choices[y]=Z,k=Z}if((zt(u(this,be,"f")?.response_format)||u(this,dt,"f"))&&pt(ga(k),"refusal"),S)if(k.logprobs){let{content:Z,refusal:Rt,...ge}=S;ya(k.logprobs,ge),Z&&((o=k.logprobs).content??(o.content=[]),k.logprobs.content.push(...Z)),Rt&&((s=k.logprobs).refusal??(s.refusal=[]),k.logprobs.refusal.push(...Rt))}else k.logprobs={...S},S.content&&(k.logprobs.content=[...S.content]),S.refusal&&(k.logprobs.refusal=[...S.refusal]);if(O&&(k.finish_reason=O,u(this,be,"f")&&(u(this,Ql,"f")||kd(u(this,be,"f"))))){if(O==="length")throw new Rr;if(O==="content_filter")throw new Mr}if(ya(k,I),!x){Object.freeze(R);continue}u(this,Dr,"f").delete(y);let{audio:D,content:$,refusal:j,function_call:M,role:C,...L}=x,{tool_calls:z,...V}=L,Ne=N(L,"tool_calls")?z:x.tool_calls;if(ya(k.message,V),D?.expires_at!=null&&D.id==null&&D.data==null&&D.transcript==null&&$==null&&j==null&&M==null&&C==null&&Ne==null&&Object.keys(V).length===0&&u(this,Dr,"f").add(y),j&&(k.message.refusal=(k.message.refusal||"")+j),C&&(k.message.role=C),D){let Z=(i=k.message).audio??(i.audio={});D.id!=null&&(Z.id=D.id),D.data!=null&&(Z.data=(Z.data??"")+D.data),D.transcript!=null&&(Z.transcript=(Z.transcript??"")+D.transcript),D.expires_at!=null&&(Z.expires_at=D.expires_at)}if(M&&(k.message.function_call?(M.name&&(k.message.function_call.name=M.name),M.arguments&&((a=k.message.function_call).arguments??(a.arguments=""),k.message.function_call.arguments+=M.arguments)):k.message.function_call=M),$!=null)if(!k.message.refusal&&zt(u(this,be,"f")?.response_format)){let Z=u(this,oe,"m",Uo).call(this,k),Rt=Z.content_parse_state??(Z.content_parse_state=np()),ge=op(Rt,u(this,et,"f"),$);k.message.content=(pt(k.message,"content")||"")+$,Rt.has_non_whitespace?ge&&sp(Rt,u(this,et,"f"))?(u(this,oe,"m",qo).call(this,c),k.message.parsed=mg(Ln(k.message.content))):$.length>0&&(k.message.parsed=null):k.message.parsed=null}else k.message.content=(k.message.content||"")+$;if(Ne){let Z=(l=k.message).tool_calls??(l.tool_calls=[]);for(let Rt of Ne){let{index:ge,id:Ja,type:Oo,function:ko,custom:Vt,...yu}=Rt;if(!Number.isSafeInteger(ge)||ge<0||ge>=Fr)throw new A(`Chat completion stream contains an invalid tool call index: ${ge}`);let rt="",ve=Z[ge]??(Z[ge]={}),yt=ko?.name,Mt=u(this,dt,"f")?u(this,oe,"m",Uo).call(this,k):void 0,nt=Mt?.tool_call_identities.get(ge);if(nt&&(Qd(ve,nt),Oo!==void 0&&Oo!==nt.type||yt!==void 0&&yt!==nt.name))throw new A("Chat completion stream contains a changed tool call identity");if(ya(ve,yu),Ja&&(ve.id=Ja),Oo&&(ve.type=Oo),Vt){let qe=ve.custom??(ve.custom={name:Vt.name??"",input:""});Vt.name&&(qe.name=Vt.name),Vt.input&&(qe.input+=Vt.input)}if(ko){let qe=ve.function??(ve.function={name:yt??"",arguments:""});if(yt&&(qe.name=yt),Mt&&!nt){let ot=ec(ve),_u=ot&&u(this,be,"f")?.tools?.find($t=>Ft($t)&&$t.function.name===ot.name);if(ot&&(nt={...ot,parseable:_u!==void 0&&jl(u(this,be,"f"),{type:ot.type,function:{name:ot.name}})},Mt.tool_call_identities.set(ge,nt),!nt.parseable)){let $t=Mt.tool_call_parse_states.get(ge);$t&&(u(this,et,"f").bytes-=$t.bytes,u(this,et,"f").fragments-=$t.fragments,u(this,et,"f").work-=$t.work,Mt.tool_call_parse_states.delete(ge))}}let wr=ko.arguments;if(wr!=null)if(rt=wr,Mt&&nt?.parseable!==!1){let ot=Mt.tool_call_parse_states.get(ge);ot||(ot=np(),Mt.tool_call_parse_states.set(ge,ot));let _u=op(ot,u(this,et,"f"),wr),$t=pt(qe,"arguments");if(typeof $t!="string")throw new A("Chat completion stream contains an unsafe structured JSON snapshot");qe.arguments=$t+wr,_u&&nt?.parseable===!0&&sp(ot,u(this,et,"f"))?(u(this,oe,"m",qo).call(this,c),qe.parsed_arguments=mg(Ln(qe.arguments))):wr.length>0&&N(qe,"parsed_arguments")&&(qe.parsed_arguments=void 0)}else qe.arguments+=wr}R.push(Object.freeze({index:ge,arguments_delta:rt}))}}Object.freeze(R)}return c},Symbol.asyncIterator)](){return this._createIterator(e=>{let r=n=>e(n);return this.on("chunk",r),()=>this.off("chunk",r)},{onReturn:()=>this.abort()})}toReadableStream(){return new Je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Kv(t,e,r,n){let{id:o,choices:s,created:i,model:a,system_fingerprint:l,...c}=t,d={...c,id:o,choices:yg(s,Yl,"choice",m=>{let f=n.get(m);if(!f)throw new A("Chat completion stream contains an unsafe structured JSON snapshot");let g=new Proxy(m,{get(L,z,V){return z==="message"?f.message:Reflect.get(L,z,V)}}),{message:b,finish_reason:_,index:x,logprobs:O,...y}=g,S=new Proxy(b,{get(L,z,V){return z==="content"?f.content:z==="refusal"?f.refusal:z==="tool_calls"?f.toolCallCollection:Reflect.get(L,z,V)}}),{content:I=null,function_call:R,tool_calls:k,audio:D,...$}=S,j=_??(r.has(x)&&Hv(D)?"stop":null);if(!j)throw new A(`missing finish_reason for choice ${x}`);let M=D?{audio:D}:{},C=S.role;if(!C)throw new A(`missing role for choice ${x}`);if(R){let{arguments:L,name:z}=R;if(L==null)throw new A(`missing function_call.arguments for choice ${x}`);if(!z)throw new A(`missing function_call.name for choice ${x}`);return{...y,message:{...M,content:I,function_call:{arguments:L,name:z},role:C,refusal:S.refusal??null},finish_reason:j,index:x,logprobs:O}}return k?{...y,index:x,finish_reason:j,logprobs:O,message:{...$,...M,role:C,content:I,refusal:S.refusal??null,tool_calls:yg(k,Fr,"tool-call",(L,z)=>{let V=f.toolCalls.get(z);if(!V){let rt=ec(L);if(rt&&jl(e,{type:rt.type,function:{name:rt.name}}))throw new A("Chat completion stream contains an unsafe structured JSON snapshot")}if(V&&V.tool!==L)throw new A("Chat completion stream contains a changed tool call identity");let Ne=V&&new Proxy(V.function,{get(rt,ve,yt){return ve==="arguments"?V.arguments:ve==="name"?V.name:Reflect.get(rt,ve,yt)}}),Z=V&&Ne?new Proxy(L,{get(rt,ve,yt){return ve==="type"?V.type:ve==="function"?Ne:Reflect.get(rt,ve,yt)}}):L;if(Z.type==null)throw new A(`missing choices[${x}].tool_calls[${z}].type`);if(Z.type==="custom"){let{custom:rt,type:ve,id:yt,...Mt}=Z,{input:nt="",name:qe,...wr}=rt||{};if(qe==null)throw new A(`missing choices[${x}].tool_calls[${z}].custom.name`);return{...Mt,id:yt||`call_${_t()}`,type:ve,custom:{...wr,name:qe,input:nt}}}let{function:Rt,type:ge,id:Ja,...Oo}=Z,{arguments:ko,name:Vt,...yu}=Rt||{};if(Vt==null)throw new A(`missing choices[${x}].tool_calls[${z}].function.name`);if(ko==null)throw new A(`missing choices[${x}].tool_calls[${z}].function.arguments`);return{...Oo,id:Ja||`call_${_t()}`,type:ge,function:{...yu,name:Vt,arguments:ko}}})}}:{...y,message:{...$,...M,content:I,role:C,refusal:S.refusal??null},finish_reason:j,index:x,logprobs:O}}),created:i,model:a,object:"chat.completion",...l?{system_fingerprint:l}:{}};return Vh(d,e)}function Hv(t){return t?.id!=null&&t.data!=null&&t.transcript!=null&&t.expires_at!=null}var wa=class t extends jn{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}toReadableStream(){let e,r,n=this._createIterator(s=>{let i=l=>{e=l,s(l)},a=l=>{if(rr(l)){r=l.tool_calls?.map(c=>c.id);return}if(na(l)){if(!e)throw new A("cannot serialize a tool message before receiving any chunks");s(bg(e,l,r)),r=void 0}};return this.on("chunk",i),this.on("message",a),()=>{this.off("chunk",i),this.off("message",a)}},{onReturn:()=>this.abort()});return new Je(()=>n,this.controller).toReadableStream()}static runTools(e,r,n){let o=new t(r),s={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var nr=class extends w{constructor(){super(...arguments),this.messages=new Cn(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(h`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",P,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return Gh(e.tools),this._client.chat.completions.create(e,{...r,__metadata:{...r?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap(n=>ra(n,e))}runTools(e,r){return e.stream?wa.runTools(this._client,e,r):fa.runTools(this._client,e,r)}stream(e,r){return jn.createChatCompletion(this._client,e,r)}};nr.Messages=Cn;var zr=class extends w{constructor(){super(...arguments),this.completions=new nr(this._client)}};zr.Completions=nr;var Ko=class extends w{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(h`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",P,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ho=class extends w{list(e={},r){return this._client.getAPIList("/organization/audit_logs",J,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Vo=class extends w{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(h`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/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(h`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",Ee,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",Ee,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Go=class extends w{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 Jo=class extends w{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(h`/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(h`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Zo=class extends w{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(h`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",ue,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Xo=class extends w{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(h`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/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(h`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qo=class extends w{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/spend_limit",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var Yo=class extends w{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 es=class extends w{create(e,r,n){return this._client.post(h`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(h`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/organization/groups/${e}/roles`,ue,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(h`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ts=class extends w{create(e,r,n){return this._client.post(h`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(h`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/organization/groups/${e}/users`,ue,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(h`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends w{constructor(){super(...arguments),this.users=new ts(this._client),this.roles=new es(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(h`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",ue,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Br.Users=ts;Br.Roles=es;var rs=class extends w{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(h`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/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(h`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var ns=class extends w{list(e,r={},n){return this._client.getAPIList(h`/organization/projects/${e}/certificates`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(h`/organization/projects/${e}/certificates/activate`,Ee,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(h`/organization/projects/${e}/certificates/deactivate`,Ee,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var os=class extends w{retrieve(e,r){return this._client.get(h`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var ss=class extends w{retrieve(e,r){return this._client.get(h`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var is=class extends w{retrieve(e,r){return this._client.get(h`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var as=class extends w{listRateLimits(e,r={},n){return this._client.getAPIList(h`/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(h`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var ls=class extends w{create(e,r,n){return this._client.post(h`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(h`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/projects/${e}/roles`,ue,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(h`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var cs=class extends w{create(e,r,n){return this._client.post(h`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(h`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/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(h`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var us=class extends w{retrieve(e,r){return this._client.get(h`/organization/projects/${e}/spend_limit`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/organization/projects/${e}/spend_limit`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/projects/${e}/spend_limit`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ds=class extends w{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/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(h`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(h`/projects/${o}/groups/${e}/roles`,ue,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(h`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Dn=class extends w{constructor(){super(...arguments),this.roles=new ds(this._client)}create(e,r,n){return this._client.post(h`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(h`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/organization/projects/${e}/groups`,ue,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(h`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Dn.Roles=ds;var ps=class extends w{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/organization/projects/${o}/service_accounts/${e}/api_keys`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var Fn=class extends w{constructor(){super(...arguments),this.apiKeys=new ps(this._client)}create(e,r,n){return this._client.post(h`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(h`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/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(h`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Fn.APIKeys=ps;var fs=class extends w{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/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(h`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(h`/projects/${o}/users/${e}/roles`,ue,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(h`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var zn=class extends w{constructor(){super(...arguments),this.roles=new fs(this._client)}create(e,r,n){return this._client.post(h`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(h`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(h`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/organization/projects/${e}/users`,J,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(h`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};zn.Roles=fs;var Pe=class extends w{constructor(){super(...arguments),this.users=new zn(this._client),this.serviceAccounts=new Fn(this._client),this.apiKeys=new rs(this._client),this.rateLimits=new as(this._client),this.modelPermissions=new is(this._client),this.hostedToolPermissions=new ss(this._client),this.groups=new Dn(this._client),this.roles=new ls(this._client),this.dataRetention=new os(this._client),this.spendLimit=new us(this._client),this.spendAlerts=new cs(this._client),this.certificates=new ns(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(h`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/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(h`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};Pe.Users=zn;Pe.ServiceAccounts=Fn;Pe.APIKeys=rs;Pe.RateLimits=as;Pe.ModelPermissions=is;Pe.HostedToolPermissions=ss;Pe.Groups=Dn;Pe.Roles=ls;Pe.DataRetention=os;Pe.SpendLimit=us;Pe.SpendAlerts=cs;Pe.Certificates=ns;var ms=class extends w{create(e,r,n){return this._client.post(h`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(h`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/organization/users/${e}/roles`,ue,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(h`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Bn=class extends w{constructor(){super(...arguments),this.roles=new ms(this._client)}retrieve(e,r){return this._client.get(h`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(h`/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(h`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Bn.Roles=ms;var Re=class extends w{constructor(){super(...arguments),this.auditLogs=new Ho(this._client),this.adminAPIKeys=new Ko(this._client),this.usage=new Yo(this._client),this.invites=new Jo(this._client),this.users=new Bn(this._client),this.groups=new Br(this._client),this.roles=new Zo(this._client),this.dataRetention=new Go(this._client),this.spendLimit=new Qo(this._client),this.spendAlerts=new Xo(this._client),this.certificates=new Vo(this._client),this.projects=new Pe(this._client)}};Re.AuditLogs=Ho;Re.AdminAPIKeys=Ko;Re.Usage=Yo;Re.Invites=Jo;Re.Users=Bn;Re.Groups=Br;Re.Roles=Zo;Re.DataRetention=Go;Re.SpendLimit=Qo;Re.SpendAlerts=Xo;Re.Certificates=Vo;Re.Projects=Pe;var Ur=class extends w{constructor(){super(...arguments),this.organization=new Re(this._client)}};Ur.Organization=Re;var hs=class extends w{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:v([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var gs=class extends w{create(e,r){return this._client.post("/audio/transcriptions",we({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var ys=class extends w{create(e,r){return this._client.post("/audio/translations",we({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Ut=class extends w{constructor(){super(...arguments),this.transcriptions=new gs(this._client),this.translations=new ys(this._client),this.speech=new hs(this._client)}};Ut.Transcriptions=gs;Ut.Translations=ys;Ut.Speech=hs;var Un=class extends w{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",P,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(h`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var _s=class extends w{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/assistants/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/assistants/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",P,{query:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/assistants/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var ws=class extends w{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var bs=class extends w{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var qr=class extends w{constructor(){super(...arguments),this.sessions=new ws(this._client),this.transcriptionSessions=new bs(this._client)}};qr.Sessions=ws;qr.TranscriptionSessions=bs;var As=class extends w{create(e,r,n){return this._client.post(h`/agents/environments/${e}/files`,{body:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/agents/environments/${e}/files`,Lo,{query:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var xs=class extends w{create(e={},r){return this._client.post("/agents/environments/templates",{body:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/agents/environments/templates/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r={},n){return this._client.post(h`/agents/environments/templates/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/agents/environments/templates",P,{query:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/agents/environments/templates/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Wr=class extends w{constructor(){super(...arguments),this.files=new As(this._client),this.templates=new xs(this._client)}retrieve(e,r){return this._client.get(h`/agents/environments/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}};Wr.Files=As;Wr.Templates=xs;var vs,tc,qn,rc,nc=class{constructor(){vs.set(this,void 0),tc.set(this,!1),qn.set(this,new Set),rc.set(this,new Set)}accept(e){if(u(this,qn,"f").has(e.event_id))return!1;if(u(this,qn,"f").size===1024){let r=u(this,qn,"f").values().next();r.done||u(this,qn,"f").delete(r.value)}return u(this,qn,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&u(this,vs,"f")===void 0&&E(this,vs,e.turn_id,"f"),(e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&u(this,vs,"f")!==void 0&&e.turn_id===u(this,vs,"f")&&E(this,tc,!0,"f"),!0}terminal(e){return e.type==="agent.session.failed"||e.type==="agent.session.idle"&&u(this,tc,"f")}call(e){if(e.type!=="agent.session.turn.item.added"||e.item.type!=="function_call")return;let r=e.item,n=JSON.stringify([r.turn_id,r.call_id]);if(!u(this,rc,"f").has(n))return u(this,rc,"f").add(n),r}};vs=new WeakMap,tc=new WeakMap,qn=new WeakMap,rc=new WeakMap;var Ae,oc,Is,sc,ic,Wn,Kn,ac,lc,Ss,ba,Sg,vg,At,cp,up,Ig;function NI(t){if(!Te(t))return!1;let e=t,r;if(e.type==="input_text")r="text";else if(e.type==="input_image")r="image_url";else return!1;return N(e,"type")&&N(e,r)&&typeof e[r]=="string"}function LI(t){if(t===null)return null;if(typeof t=="string"||Array.isArray(t)&&t.every(NI))return t;throw new A("Tool output must be text, content, a JSON object, or null")}function jI(t,e){let r=Te(e)?JSON.stringify(e):e,n=JSON.stringify(r);if(n===void 0)throw new A("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:t.turn_id,call_id:t.call_id,success:!0,output:LI(typeof r=="string"?r:JSON.parse(n))}}async function DI(t){try{await t?.body?.cancel()}catch{}}var cc=class{constructor(e,r,n,o){Ae.add(this),this.controller=new AbortController,oc.set(this,!1),Is.set(this,void 0),sc.set(this,void 0),ic.set(this,!1),Wn.set(this,void 0),Kn.set(this,void 0),ac.set(this,void 0),lc.set(this,void 0),Ss.set(this,void 0),ba.set(this,void 0);let s=typeof n.input=="string"?[{role:"user",content:[{type:"input_text",text:n.input}]}]:n.input;if(n.input.length===0)throw new A("input must not be empty");E(this,Wn,e,"f"),E(this,Kn,r,"f"),E(this,ac,{type:"agent.session.input.message",input:s},"f"),E(this,lc,new Map(Object.entries(n.toolHandlers??{})),"f");let i=v([o?.headers]);E(this,Ss,i.nulls.has("idempotency-key")?void 0:i.values.get("idempotency-key")??n.idempotencyKey??o?.idempotencyKey??_t(),"f"),i.values.delete("idempotency-key"),i.nulls.delete("idempotency-key");let{idempotencyKey:a,...l}=o??{};E(this,ba,{...l,headers:i},"f")}abort(e){this.controller.abort(e),u(this,Is,"f")?.controller.abort(this.controller.signal.reason),u(this,ic,"f")||DI(u(this,sc,"f"))}[(oc=new WeakMap,Is=new WeakMap,sc=new WeakMap,ic=new WeakMap,Wn=new WeakMap,Kn=new WeakMap,ac=new WeakMap,lc=new WeakMap,Ss=new WeakMap,ba=new WeakMap,Ae=new WeakSet,Symbol.asyncIterator)](){if(u(this,oc,"f"))throw new A("An AgentSessionStream can only be consumed once");return E(this,oc,!0,"f"),u(this,Ae,"m",Sg).call(this)}};Sg=async function*(){let e=u(this,ba,"f").signal,r=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener("abort",r,{once:!0}),this.controller.signal.addEventListener("abort",r,{once:!0});let n={...u(this,ba,"f"),signal:this.controller.signal},o=new nc;try{if(e?.aborted&&this.abort(e.reason),u(this,Ae,"m",At).call(this),(await u(this,Wn,"f").retrieve(u(this,Kn,"f"),n)).status!=="idle")throw new A("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let i=await u(this,Wn,"f").events.stream(u(this,Kn,"f"),n).withResponse();E(this,Is,i.data,"f"),E(this,sc,i.response,"f"),u(this,Ae,"m",At).call(this),await u(this,Wn,"f").events.create(u(this,Kn,"f"),{events:[u(this,ac,"f")],...u(this,Ss,"f")===void 0?{}:{"Idempotency-Key":u(this,Ss,"f")}},{...n,headers:v([n.headers,{"Idempotency-Key":u(this,Ss,"f")??null}])}),u(this,Ae,"m",At).call(this),E(this,ic,!0,"f");for await(let a of u(this,Is,"f")){if(u(this,Ae,"m",At).call(this),!o.accept(a))continue;let l=o.terminal(a),c=o.call(a),d=c&&u(this,lc,"f").get(c.name),m=c&&d?structuredClone(c):void 0;if(l&&u(this,Is,"f").controller.abort(),yield a,l)return;if(u(this,Ae,"m",At).call(this),!m||!d)continue;let f=await u(this,Ae,"m",vg).call(this,m,d);u(this,Ae,"m",At).call(this),await u(this,Ae,"m",Ig).call(this,f,n)}throw u(this,Ae,"m",At).call(this),new A("Session event stream ended before the turn reached idle or failed")}finally{e?.removeEventListener("abort",r),this.controller.signal.removeEventListener("abort",r),this.abort()}},vg=async function(e,r){try{let n=typeof e.arguments=="string"?JSON.parse(e.arguments):e.arguments;if(!Te(n))throw new A("Function arguments must be a JSON object");return jI(e,await u(this,Ae,"m",up).call(this,()=>r(n)))}catch{return u(this,Ae,"m",At).call(this),{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!1,error:"Tool handler failed."}}},At=function(){if(this.controller.signal.aborted)throw u(this,Ae,"m",cp).call(this)},cp=function(){let e=new ie;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},up=async function(e){let r,n=new Promise((o,s)=>{r=()=>s(u(this,Ae,"m",cp).call(this)),this.controller.signal.addEventListener("abort",r,{once:!0})});try{u(this,Ae,"m",At).call(this);let o=async()=>await e();return await Promise.race([o(),n])}finally{r&&this.controller.signal.removeEventListener("abort",r)}},Ig=async function t(e,r,n=_t(),o=0){u(this,Ae,"m",At).call(this);try{await u(this,Wn,"f").events.create(u(this,Kn,"f"),{events:[e],"Idempotency-Key":n},r)}catch(s){let i=[100,300,600][o];if(i===void 0||!(s instanceof Nt)||s.code!=="invalid_request_error"||!s.error||!("message"in s.error)||s.error.message!==`Unknown pending tool call: ${e.call_id}`)throw s;let a;try{await u(this,Ae,"m",up).call(this,()=>new Promise(l=>{a=setTimeout(l,i)}))}finally{a!==void 0&&clearTimeout(a)}await u(this,Ae,"m",t).call(this,e,r,n,o+1)}};var Ts=class extends w{retrieve(e,r,n){let{session_id:o}=r;return this._client.get(h`/agents/sessions/${o}/artifacts/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/agents/sessions/${e}/artifacts`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{session_id:o}=r;return this._client.delete(h`/agents/sessions/${o}/artifacts/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}content(e,r,n){let{session_id:o}=r;return this._client.get(h`/agents/sessions/${o}/artifacts/${e}/content`,{...n,headers:v([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Es=class extends w{create(e,r,n){let{"Idempotency-Key":o,...s}=r;return this._client.post(h`/agents/sessions/${e}/events`,{body:s,...n,headers:v([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...o!=null?{"Idempotency-Key":o}:void 0},n?.headers]),__security:{bearerAuth:!0}})}stream(e,r){return this._client.get(h`/agents/sessions/${e}/events`,{...r,headers:v([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},r?.headers]),stream:!0,__security:{bearerAuth:!0}})}};var Os=class extends w{list(e,r={},n){return this._client.getAPIList(h`/agents/sessions/${e}/items`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var ks=class extends w{retrieve(e,r,n){let{session_id:o}=r;return this._client.get(h`/agents/sessions/${o}/turns/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/agents/sessions/${e}/turns`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Cs=class extends w{list(e,r,n){let{session_id:o,...s}=r;return this._client.getAPIList(h`/agents/sessions/${o}/subagents/${e}/items`,P,{query:s,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Ps=class extends w{list(e,r,n){let{session_id:o,subagent_id:s,...i}=r;return this._client.getAPIList(h`/agents/sessions/${o}/subagents/${s}/turns/${e}/items`,P,{query:i,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Hn=class extends w{constructor(){super(...arguments),this.items=new Ps(this._client)}retrieve(e,r,n){let{session_id:o,subagent_id:s}=r;return this._client.get(h`/agents/sessions/${o}/subagents/${s}/turns/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{session_id:o,...s}=r;return this._client.getAPIList(h`/agents/sessions/${o}/subagents/${e}/turns`,P,{query:s,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};Hn.Items=Ps;var Kr=class extends w{constructor(){super(...arguments),this.items=new Cs(this._client),this.turns=new Hn(this._client)}retrieve(e,r,n){let{session_id:o}=r;return this._client.get(h`/agents/sessions/${o}/subagents/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/agents/sessions/${e}/subagents`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};Kr.Items=Cs;Kr.Turns=Hn;var xt=class extends w{constructor(){super(...arguments),this.subagents=new Kr(this._client),this.artifacts=new Ts(this._client),this.items=new Os(this._client),this.events=new Es(this._client),this.turns=new ks(this._client)}stream(e,r,n){return new cc(this,e,r,n)}create(e,r){return this._client.post("/agents/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/agents/sessions/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r={},n){return this._client.post(h`/agents/sessions/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/agents/sessions",P,{query:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/agents/sessions/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}};xt.Subagents=Kr;xt.Artifacts=Ts;xt.Items=Os;xt.Events=Es;xt.Turns=ks;var Rs=class extends w{create(e,r,n){return this._client.post(h`/vaults/${e}/credentials`,{body:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vault_id:o}=r;return this._client.get(h`/vaults/${o}/credentials/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vault_id:o,...s}=r;return this._client.post(h`/vaults/${o}/credentials/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/vaults/${e}/credentials`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vault_id:o}=r;return this._client.delete(h`/vaults/${o}/credentials/${e}`,{...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Vn=class extends w{constructor(){super(...arguments),this.credentials=new Rs(this._client)}create(e={},r){return this._client.post("/vaults",{body:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/vaults/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vaults",P,{query:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/vaults/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}};Vn.Credentials=Rs;var or=class extends w{constructor(){super(...arguments),this.environments=new Wr(this._client),this.vaults=new Vn(this._client),this.sessions=new xt(this._client)}create(e,r){return this._client.post("/agents",{body:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/agents/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r={},n){return this._client.post(h`/agents/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/agents",P,{query:e,...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/agents/${e}`,{...r,headers:v([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}};or.Environments=Wr;or.Vaults=Vn;or.Sessions=xt;var Ms=class extends w{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(h`/chatkit/sessions/${e}/cancel`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var $s=class extends w{retrieve(e,r){return this._client.get(h`/chatkit/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",J,{query:e,...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/chatkit/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(h`/chatkit/threads/${e}/items`,J,{query:r,...n,headers:v([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Hr=class extends w{constructor(){super(...arguments),this.sessions=new Ms(this._client),this.threads=new $s(this._client)}};Hr.Sessions=Ms;Hr.Threads=$s;var Ns=class extends w{list(e,r={},n){let{betas:o,...s}=r??{};return this._client.getAPIList(h`/responses/${e}/input_items?beta=true`,P,{query:s,...n,headers:v([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};var Ls=class extends w{count(e={},r){let{betas:n,...o}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:o,...r,headers:v([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var Vr=class extends w{constructor(){super(...arguments),this.inputItems=new Ns(this._client),this.inputTokens=new Ls(this._client)}create(e,r){let{betas:n,...o}=e;return this._client.post("/responses?beta=true",{body:o,...r,headers:v([{...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(h`/responses/${e}?beta=true`,{query:s,...n,headers:v([{...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(h`/responses/${e}?beta=true`,{...n,headers:v([{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(h`/responses/${e}/cancel?beta=true`,{...n,headers:v([{...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:v([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};Vr.InputItems=Ns;Vr.InputTokens=Ls;var js=class extends w{create(e,r,n){return this._client.post(h`/threads/${e}/messages`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(h`/threads/${o}/messages/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(h`/threads/${o}/messages/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/threads/${e}/messages`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(h`/threads/${o}/messages/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ds=class extends w{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(h`/threads/${o}/runs/${s}/steps/${e}`,{query:i,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(h`/threads/${o}/runs/${e}/steps`,P,{query:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var uc=t=>{if(typeof globalThis.Buffer<"u"){let e=globalThis.Buffer.from(t,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof atob<"u"){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}throw new A("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Tg=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");if(e.length%Float32Array.BYTES_PER_ELEMENT!==0)throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");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 ft=t=>{try{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}catch{return}};var Og=1024,sS=65536;function iS(t){switch(t){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return t;default:return"unknown"}}var Aa=new WeakMap,Gr=new WeakSet;function kg(t){return{arrays:new Map,cacheArrays:t,records:new WeakMap}}function Cg(t){for(let[e,r]of t.arrays)r.cacheable&&!Gr.has(e)?Aa.set(e,{length:r.length,ownEntryCount:r.ownEntryCount}):Aa.delete(e)}function Eg(t){return typeof t=="string"||typeof t=="number"}function Pg(t,e){return e.every(Eg)&&t.every(Eg)}function aS(t){let e=0;for(let r of Object.keys(t)){let n=Number(r);Number.isSafeInteger(n)&&n>=0&&n<t.length&&String(n)===r&&(e+=1)}return e}function lS(t,e,r){return e?r?.length===t.length?r.ownEntryCount:aS(t):0}function cS(t,e,r){let{index:n}=t;if(e==="array"&&n==null)throw new Error("Expected array delta entry to have an `index` property");if(e==="array"&&typeof n!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(n)||n<0||n>=r+Og||n>=sS){let o=typeof n=="number"?n:"unknown";throw new A(`Assistant stream delta contains an invalid ${e} index: ${o}`)}return n}function Rg(t,e,r,n,o){let s=n.arrays.get(t);if(!s){let i=n.cacheArrays&&!Gr.has(t),a=i?Aa.get(t):void 0;s={baselineLength:t.length,cacheable:i,enforceSparseHoleBudget:i,entries:new Map,length:t.length,ownEntryCount:lS(t,i,a)},n.arrays.set(t,s)}for(let i of e){if(!Te(i))throw new Error("Expected array delta entry to be an object but got an invalid value");let a=cS(i,r,s.baselineLength),l;s.entries.has(a)?l=s.entries.get(a):N(t,a)?(l=t[a],l==null&&s.entries.set(a,i)):(s.entries.set(a,i),s.ownEntryCount+=1);let c=Math.max(s.length,a+1);if(s.enforceSparseHoleBudget&&c-s.ownEntryCount>Og)throw new A(`Assistant stream delta contains an invalid ${r} index: ${a}`);Te(l)&&o(l,i,n),s.length=c}}function dc(t,e,r){let n=r.records.get(t);for(let[o,s]of Object.entries(e)){if(o==="index"||o==="type")continue;let i;if(n?.has(o)?i=n.get(o):N(t,o)&&(i=t[o]),i==null){n||(n=new Map,r.records.set(t,n)),n.set(o,s);continue}Te(i)&&Te(s)?dc(i,s,r):Array.isArray(i)&&Array.isArray(s)&&!Pg(i,s)&&Rg(i,s,"array",r,dc)}}function pc(t){return(Te(t)||Array.isArray(t))&&Gr.has(t)}function vt(t){if(!(!Te(t)&&!Array.isArray(t)||Gr.has(t))){Gr.add(t),Array.isArray(t)&&Aa.delete(t);for(let e of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,e);r&&"value"in r&&vt(r.value)}}}function pp(t,e,r){Gr.has(t)&&vt(r),Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0})}function uS(t){let{index:e}=t;if(e==null)throw new Error("Expected array delta entry to have an `index` property");if(typeof e!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return e}function dS(t,e,r){if(Pg(t,e)){t.push(...e),Aa.delete(t);return}for(let n of e){if(!Te(n))throw new Error("Expected array delta entry to be an object but got an invalid value");let o=uS(n);if(N(t,o)){let s=t[o];s==null?(Gr.has(t)&&vt(n),t[o]=n):t[o]=r(s,n)}else pp(t,o,n)}}function dp(t,e){let r=Gr.has(t);for(let[n,o]of Object.entries(e)){if(n==="__proto__"||n==="constructor"||n==="prototype")throw new A(`Assistant stream delta contains an unsafe property: ${n}`);if(!N(t,n)){r&&vt(o),t[n]=o;continue}let s=t[n];if(s==null){r&&vt(o),t[n]=o;continue}if(n==="index"||n==="type"){t[n]=o;continue}if(typeof s=="string"&&typeof o=="string")s+=o;else if(typeof s=="number"&&typeof o=="number")s+=o;else if(Te(s)&&Te(o))s=dp(s,o);else if(Array.isArray(s)&&Array.isArray(o)){dS(s,o,dp);continue}else throw new TypeError(`Unhandled record type: ${iS(n)}`);t[n]=s}return t}function xa(t){if(!(!Te(t)&&!Array.isArray(t)))for(let[e,r]of Object.entries(t)){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new A(`Assistant stream delta contains an unsafe property: ${e}`);xa(r)}}function fc(t,e,r=!1){xa(e);let n=t,o=e,s=kg(r&&!pc(t));return dc(n,o,s),dp(n,o),Cg(s),t}function Mg(t,e,r,n=!0){xa(e);let o=kg(n&&!pc(t));return Rg(t,e,r,o,dc),()=>Cg(o)}var q,Ue,Jr,mt,Bs,zs,De,sr,Jn,Zr,ir,Gn,Xe,Ia,Sa,Xr,Ta,Ea,$g,Fs,Ng,va,Lg,jg,xe,Dg,Fg,zg,Bg,Ug;function pS(t){let e=Object.getOwnPropertyDescriptor(t,"event"),r=Object.getOwnPropertyDescriptor(t,"data"),n=Reflect.get(t,"event",t),o=Reflect.get(t,"data",t),s=o;if(n==="thread.message.created"||n==="thread.message.in_progress"||n==="thread.message.delta"||n==="thread.message.completed"||n==="thread.message.incomplete"||n==="thread.run.step.created"||n==="thread.run.step.in_progress"||n==="thread.run.step.delta"||n==="thread.run.step.completed"||n==="thread.run.step.failed"||n==="thread.run.step.cancelled"||n==="thread.run.step.expired"){let l=Object.getOwnPropertyDescriptor(o,"id");if(l&&"value"in l&&o.id!==l.value){let c=l.value;s=new Proxy(o,{get(d,m){return m==="id"?c:Reflect.get(d,m,d)}})}}let i=Object.freeze({event:n,data:s}),a=e!==void 0&&"value"in e&&e.value===n&&r!==void 0&&"value"in r&&r.value===o&&s===o;return{event:i,exposedEvent:a?t:{event:n,data:s}}}var Qr=class t extends jr{constructor(){super(...arguments),q.add(this),Ue.set(this,Object.create(null)),Jr.set(this,new Map),mt.set(this,void 0),Bs.set(this,Object.create(null)),zs.set(this,new Map),De.set(this,void 0),sr.set(this,void 0),Jn.set(this,void 0),Zr.set(this,void 0),ir.set(this,void 0),Gn.set(this,void 0),Xe.set(this,void 0),Ia.set(this,void 0),Sa.set(this,void 0),Xr.set(this,void 0)}[(Ue=new WeakMap,Jr=new WeakMap,mt=new WeakMap,Bs=new WeakMap,zs=new WeakMap,De=new WeakMap,sr=new WeakMap,Jn=new WeakMap,Zr=new WeakMap,ir=new WeakMap,Gn=new WeakMap,Xe=new WeakMap,Ia=new WeakMap,Sa=new WeakMap,Xr=new WeakMap,q=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let r=n=>e(structuredClone(n));return this.on("event",r),()=>this.off("event",r)},{onReturn:()=>this.abort()})}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=Je.fromReadableStream(e,this.controller);for await(let o of n)u(this,q,"m",Ta).call(this,o);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,q,"m",Ea).call(this))}toReadableStream(){return new Je(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new t;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,__metadata:{...o?.__metadata,helperMethod:"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)u(this,q,"m",Ta).call(this,a);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,q,"m",Ea).call(this))}static createThreadAssistantStream(e,r,n){let o=new t;return o._run(()=>o._threadAssistantStream(e,r,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new t;return s._run(()=>s._runAssistantStream(e,r,n,{...o,__metadata:{...o?.__metadata,helperMethod:"stream"}})),s}currentEvent(){return vt(u(this,Ia,"f")),u(this,Ia,"f")}currentRun(){return vt(u(this,Sa,"f")),u(this,Sa,"f")}currentMessageSnapshot(){return vt(u(this,De,"f")),u(this,De,"f")}currentRunStepSnapshot(){return vt(u(this,Xr,"f")),u(this,Xr,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,Ue,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,Bs,"f"))}async finalRun(){if(await this.done(),!u(this,Jn,"f"))throw new Error("Final run was not received.");return u(this,Jn,"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)u(this,q,"m",Ta).call(this,i);if(s.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,q,"m",Ea).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)u(this,q,"m",Ta).call(this,a);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,q,"m",Ea).call(this))}static accumulateDelta(e,r){return fc(e,r)}_addRun(e){return u(this,q,"m",xe).call(this,"run",e),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)}};Ta=function(e){if(this.ended)return;let{event:r,exposedEvent:n}=pS(e),o,s,i,a;switch(r.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{o=u(this,q,"m",Ng).call(this,r),s=r.data;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":{i=u(this,q,"m",$g).call(this,r),a=r.data;break}}switch(E(this,Ia,n,"f"),u(this,q,"m",Dg).call(this,n),o!==void 0&&s!==void 0&&u(this,q,"m",va).call(this,s,o),i!==void 0&&a!==void 0&&u(this,q,"m",Fs).call(this,a,i),i===void 0&&u(this,mt,"f")!==void 0&&u(this,Xr,"f")&&u(this,q,"m",Fs).call(this,u(this,Xr,"f"),u(this,mt,"f")),r.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":{u(this,q,"m",Ug).call(this,r);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":{if(i===void 0)throw new A("Received assistant run-step event without a canonical run-step ID");let l=u(this,Ue,"f")[i];l&&u(this,q,"m",Fs).call(this,l,i),u(this,q,"m",jg).call(this,r,i),u(this,q,"m",Fs).call(this,r.data,i);let c=u(this,Ue,"f")[i];c&&u(this,q,"m",Fs).call(this,c,i);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(o!==void 0&&u(this,De,"f")&&u(this,q,"m",va).call(this,u(this,De,"f"),o),u(this,q,"m",Lg).call(this,r),o!==void 0){u(this,q,"m",va).call(this,r.data,o);let l=u(this,Bs,"f")[o];l&&u(this,q,"m",va).call(this,l,o)}break}case"error":throw new ee(void 0,r.data,void 0,void 0);default:}},Ea=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");if(!u(this,Jn,"f"))throw new Error("Final run has not been received");return u(this,Jn,"f")},$g=function(e){let r=Object.getOwnPropertyDescriptor(e.data,"id"),n=r&&"value"in r?r.value:void 0;if(typeof n!="string"||n.length===0)throw new A("Received assistant run-step event with an invalid run-step ID");if(e.event==="thread.run.step.delta"){let o=e.data.delta;if(o&&N(o,"id"))throw new A("Run-step deltas must not contain an id field")}if(e.event==="thread.run.step.created"){if(u(this,mt,"f")!==void 0)throw new A(`Received run-step creation for "${n}" before the active run step "${u(this,mt,"f")}" reached a terminal state`);if(N(u(this,Ue,"f"),n)||u(this,Jr,"f").has(n))throw new A(`Received run-step creation for run step "${n}", which has already been created`);return E(this,mt,n,"f"),u(this,Jr,"f").set(n,n),n}if(u(this,mt,"f")!==void 0){if(n!==u(this,mt,"f"))throw new A(`Received ${e.event} for run step "${n}", which does not match the active run step "${u(this,mt,"f")}"`);return n}if(e.event==="thread.run.step.delta")throw N(u(this,Ue,"f"),n)?new A(`Received run-step delta for "${n}" with no active run step`):new A("Received a RunStepDelta before creation of a snapshot");if(N(u(this,Ue,"f"),n)||u(this,Jr,"f").has(n))throw new A(`Received run-step event for run step "${n}", which has already been created`);return u(this,Jr,"f").set(n,n),e.event==="thread.run.step.in_progress"&&E(this,mt,n,"f"),n},Fs=function(e,r){let n=Object.getOwnPropertyDescriptor(e,"id"),o=n&&"value"in n?n.value:void 0;if(typeof o!="string"||o.length===0)throw new A("Received assistant run-step event with an invalid run-step ID");let s=u(this,Jr,"f").get(o);if(s!==void 0&&s!==r)throw new A(`Received run-step creation for run step "${o}", which has already been created`);u(this,Jr,"f").set(o,r)},Ng=function(e){let r=Object.getOwnPropertyDescriptor(e.data,"id"),n=r&&"value"in r?r.value:void 0;if(typeof n!="string"||n.length===0)throw new A("Received assistant message event with an invalid message ID");if(e.event==="thread.message.created"){if(u(this,De,"f"))throw new A(`Received message creation for "${n}" before the active message "${u(this,sr,"f")}" reached a terminal state`);if(N(u(this,Bs,"f"),n)||u(this,zs,"f").has(n))throw new A(`Received message creation for message "${n}", which has already been created`);return E(this,sr,n,"f"),u(this,zs,"f").set(n,n),n}if(!u(this,De,"f"))throw e.event==="thread.message.delta"?new A("Received a delta with no existing snapshot (there should be one from message creation)"):new A("Received thread message event with no existing snapshot");if(n!==u(this,sr,"f"))throw new A(`Received ${e.event} for message "${n}", which does not match the active message "${u(this,sr,"f")}"`);return n},va=function(e,r){let n=Object.getOwnPropertyDescriptor(e,"id"),o=n&&"value"in n?n.value:void 0;if(typeof o!="string"||o.length===0)throw new A("Received assistant message event with an invalid message ID");let s=u(this,zs,"f").get(o);if(s!==void 0&&s!==r)throw new A(`Received message creation for message "${o}", which has already been created`);u(this,zs,"f").set(o,r)},Lg=function(e){let[r,n]=u(this,q,"m",zg).call(this,e,u(this,De,"f"));if(E(this,De,r,"f"),!u(this,sr,"f"))throw new A("Received thread message event with no active message ID");u(this,Bs,"f")[u(this,sr,"f")]=r;for(let o of n){let s=r.content[o.index];s?.type==="text"&&u(this,q,"m",xe).call(this,"textCreated",s.text)}switch(e.event){case"thread.message.created":{E(this,Zr,void 0,"f"),E(this,ir,void 0,"f"),u(this,q,"m",xe).call(this,"messageCreated",e.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(u(this,q,"m",xe).call(this,"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")u(this,q,"m",xe).call(this,"textDelta",s,i.text);else throw new Error("The snapshot associated with this text delta is not text or missing")}if(o.index!==u(this,Zr,"f")){if(u(this,ir,"f"))switch(u(this,ir,"f").type){case"text":{u(this,q,"m",xe).call(this,"textDone",u(this,ir,"f").text,u(this,De,"f"));break}case"image_file":{u(this,q,"m",xe).call(this,"imageFileDone",u(this,ir,"f").image_file,u(this,De,"f"));break}}E(this,Zr,o.index,"f")}E(this,ir,r.content[o.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(u(this,Zr,"f")!==void 0){let o=e.data.content[u(this,Zr,"f")];if(o)switch(o.type){case"image_file":{u(this,q,"m",xe).call(this,"imageFileDone",o.image_file,u(this,De,"f"));break}case"text":{u(this,q,"m",xe).call(this,"textDone",o.text,u(this,De,"f"));break}}}u(this,De,"f")&&u(this,q,"m",xe).call(this,"messageDone",e.data),E(this,Zr,void 0,"f"),E(this,ir,void 0,"f"),E(this,De,void 0,"f"),E(this,sr,void 0,"f")}}},jg=function(e,r){let n=u(this,q,"m",Fg).call(this,e,r);switch(E(this,Xr,n,"f"),e.event){case"thread.run.step.created":{E(this,Gn,void 0,"f"),E(this,Xe,void 0,"f"),u(this,q,"m",xe).call(this,"runStepCreated",e.data);break}case"thread.run.step.delta":{let o=e.data.delta;if(o.step_details&&o.step_details.type==="tool_calls"&&o.step_details.tool_calls&&n.step_details.type==="tool_calls")for(let s of o.step_details.tool_calls)s.index===u(this,Gn,"f")?u(this,q,"m",xe).call(this,"toolCallDelta",s,n.step_details.tool_calls[s.index]):(u(this,Xe,"f")&&u(this,q,"m",xe).call(this,"toolCallDone",u(this,Xe,"f")),E(this,Gn,s.index,"f"),E(this,Xe,n.step_details.tool_calls[s.index],"f"),u(this,Xe,"f")&&u(this,q,"m",xe).call(this,"toolCallCreated",u(this,Xe,"f")));u(this,q,"m",xe).call(this,"runStepDelta",e.data.delta,n);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{E(this,Xr,void 0,"f"),E(this,mt,void 0,"f"),e.data.step_details.type==="tool_calls"&&u(this,Xe,"f")&&u(this,q,"m",xe).call(this,"toolCallDone",u(this,Xe,"f")),u(this,q,"m",xe).call(this,"runStepDone",e.data,n),E(this,Gn,void 0,"f"),E(this,Xe,void 0,"f");break}case"thread.run.step.in_progress":break}},xe=function(e,...r){if(this._hasListeners(e))for(let n of r)vt(n);this._emit(e,...r)},Dg=function(e){u(this,q,"m",xe).call(this,"event",e)},Fg=function(e,r){switch(e.event){case"thread.run.step.created":return u(this,Ue,"f")[r]=e.data,e.data;case"thread.run.step.delta":{let n=u(this,Ue,"f")[r];if(!n)throw new Error("Received a RunStepDelta before creation of a snapshot");let o=e.data.delta;if(o){if(N(o,"id"))throw new A("Run-step deltas must not contain an id field");let s=fc(n,o,!0);u(this,Ue,"f")[r]=s}return u(this,Ue,"f")[r]}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":{u(this,Ue,"f")[r]=e.data;break}}if(u(this,Ue,"f")[r])return u(this,Ue,"f")[r];throw new Error("No snapshot available")},zg=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":{if(!r)throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content){xa(o.delta);let s=!pc(r),i=Mg(r.content,o.delta.content,"content",s);for(let a of o.delta.content)if(N(r.content,a.index)){let l=r.content[a.index];r.content[a.index]=u(this,q,"m",Bg).call(this,a,l,s)}else pp(r.content,a.index,a),n.push(a);i()}return[r,n]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":{if(r)return[e.event==="thread.message.in_progress"?r:e.data,n];throw new Error("Received thread message event with no existing snapshot")}}throw new Error("Tried to accumulate a non-message event")},Bg=function(e,r,n){return fc(r,e,n)},Ug=function(e){switch(E(this,Sa,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":{E(this,Jn,e.data,"f"),u(this,Xe,"f")&&u(this,q,"m",xe).call(this,"toolCallDone",u(this,Xe,"f")),E(this,Gn,void 0,"f"),E(this,Xe,void 0,"f");break}case"thread.run.cancelling":break}};function fS(t,e){return new Promise((r,n)=>{let o,s,i=!1,a=d=>{try{e.removeEventListener("abort",d)}catch{}},l=()=>{if(o!==void 0&&(clearTimeout(o),o=void 0),s){let d=s;s=void 0,a(d)}},c=()=>{if(!i){i=!0,l();try{let d=new ie;Object.defineProperty(d,"cause",{value:e.reason,writable:!0,configurable:!0}),n(d)}catch(d){n(d)}}};if(e.aborted){c();return}o=setTimeout(()=>{i||(i=!0,l(),r())},t),s=c;try{e.addEventListener("abort",c,{once:!0}),i?a(c):e.aborted&&c()}catch(d){i?a(c):(i=!0,l(),n(d))}})}async function Oa(t,e,r,n){let o=v([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await t(o).withResponse(),{status:a}=s;if(e.includes(a)){let l=5e3,c=n?.pollIntervalMs;if(c||c===0)l=c;else{let m=i.headers.get("openai-poll-after-ms");if(m){let f=Number.parseInt(m);Number.isNaN(f)||(l=f)}}let d=n&&Object.prototype.propertyIsEnumerable.call(n,"signal")?n.signal:void 0;await(d?fS(l,d):$o(l))}else if(r.includes(a))return s}}function qg(t,e,r,n){return Oa(o=>t.retrieve(e,r,{...n,headers:{...n?.headers,...o}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],n)}var Zn=class extends w{constructor(){super(...arguments),this.steps=new Ds(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(h`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:v([{"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(h`/threads/${o}/runs/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(h`/threads/${o}/runs/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/threads/${e}/runs`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(h`/threads/${o}/runs/${e}/cancel`,{...n,headers:v([{"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 Qr.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){return await qg(this,e,r,n)}stream(e,r,n){return Qr.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(h`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:v([{"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 Qr.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Zn.Steps=Ds;var Yr=class extends w{constructor(){super(...arguments),this.runs=new Zn(this._client),this.messages=new js(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/threads/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/threads/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:v([{"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 Qr.createThreadAssistantStream(e,this._client.beta.threads,r)}};Yr.Runs=Zn;Yr.Messages=js;var tt=class extends w{constructor(){super(...arguments),this.realtime=new qr(this._client),this.agents=new or(this._client),this.responses=new Vr(this._client),this.chatkit=new Hr(this._client),this.assistants=new _s(this._client),this.threads=new Yr(this._client)}};tt.Realtime=qr;tt.Agents=or;tt.Responses=Vr;tt.ChatKit=Hr;tt.Assistants=_s;tt.Threads=Yr;var Xn=class extends w{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Us=class extends w{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(h`/containers/${o}/files/${e}/content`,{...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Qn=class extends w{constructor(){super(...arguments),this.content=new Us(this._client)}create(e,r,n){return this._client.post(h`/containers/${e}/files`,Nr({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(h`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/containers/${e}/files`,P,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(h`/containers/${o}/files/${e}`,{...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Qn.Content=Us;var en=class extends w{constructor(){super(...arguments),this.files=new Qn(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",P,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/containers/${e}`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};en.Files=Qn;var Yn=class extends w{create(e,r){return this._client.post("/content_provenance_checks",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}};var qs=class extends w{create(e,r,n){let{include:o,...s}=r;return this._client.post(h`/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(h`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/conversations/${e}/items`,J,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(h`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var tn=class extends w{constructor(){super(...arguments),this.items=new qs(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};tn.Items=qs;function Wg(t,e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&he(t).debug("embeddings/user defined encoding_format:",e.encoding_format);let i={body:{...e,encoding_format:o},...r,__security:{bearerAuth:!0}},a=t.post("/embeddings",i);return n?a:(he(t).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(l=>{let c=l?.data;if(c!==void 0){if(!Array.isArray(c))throw new TypeError("Expected embeddings response data to be an array");let{length:d}=c;for(let m=0;m<d;m+=1)if(m in c){let f=c[m],{embedding:g}=f;if(Array.isArray(g))continue;f.embedding=Tg(g)}}return l}))}var eo=class extends w{create(e,r){return Wg(this._client,e,r)}};var Ws=class extends w{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(h`/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(h`/evals/${o}/runs/${e}/output_items`,P,{query:s,...n,__security:{bearerAuth:!0}})}};var to=class extends w{constructor(){super(...arguments),this.outputItems=new Ws(this._client)}create(e,r,n){return this._client.post(h`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(h`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/evals/${e}/runs`,P,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(h`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(h`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};to.OutputItems=Ws;var rn=class extends w{constructor(){super(...arguments),this.runs=new to(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",P,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};rn.Runs=to;async function Kg(t,e,r,n){let o=new Set(["processed","error","deleted"]),s=performance.now(),i=await t.retrieve(e);for(;!i.status||!o.has(i.status);)if(await $o(r),i=await t.retrieve(e),performance.now()-s>n)throw new ce({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}var ro=class extends w{create(e,r){return this._client.post("/files",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(h`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",P,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(h`/files/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){return await Kg(this,e,r,n)}};var Ks=class extends w{};var Hs=class extends w{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 no=class extends w{constructor(){super(...arguments),this.graders=new Hs(this._client)}};no.Graders=Hs;var Vs=class extends w{create(e,r,n){return this._client.getAPIList(h`/fine_tuning/checkpoints/${e}/permissions`,Ee,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(h`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/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(h`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var oo=class extends w{constructor(){super(...arguments),this.permissions=new Vs(this._client)}};oo.Permissions=Vs;var Gs=class extends w{list(e,r={},n){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/checkpoints`,P,{query:r,...n,__security:{bearerAuth:!0}})}};var so=class extends w{constructor(){super(...arguments),this.checkpoints=new Gs(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(h`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",P,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(h`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/events`,P,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(h`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(h`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};so.Checkpoints=Gs;var It=class extends w{constructor(){super(...arguments),this.methods=new Ks(this._client),this.jobs=new so(this._client),this.checkpoints=new oo(this._client),this.alpha=new no(this._client)}};It.Methods=Ks;It.Jobs=so;It.Checkpoints=oo;It.Alpha=no;var Js=class extends w{};var nn=class extends w{constructor(){super(...arguments),this.graderModels=new Js(this._client)}};nn.GraderModels=Js;var io=class extends w{createVariation(e,r){return this._client.post("/images/variations",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",we({body:e,...r,stream:e.stream??!1,__metadata:{...r?.__metadata,...e.model==null?{}:{model:e.model}},__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 Zs=class extends w{accept(e,r,n){return this._client.post(h`/live/sessions/${e}/accept`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,r){return this._client.get(h`/live/sessions/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,r,n){return this._client.post(h`/live/sessions/${e}/fork`,{body:r,...n,__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(h`/live/sessions/${e}/hangup`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(h`/live/sessions/${e}/refer`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r,n){return this._client.post(h`/live/sessions/${e}/reject`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Xs=class extends w{};var Qs=class extends w{};var qt=class extends w{constructor(){super(...arguments),this.sideband=new Qs(this._client),this.forks=new Xs(this._client),this.sessions=new Zs(this._client)}create(e,r){return this._client.post("/live/sessions",{body:e,...r,__security:{bearerAuth:!0}})}};qt.Sideband=Qs;qt.Forks=Xs;qt.Sessions=Zs;var ao=class extends w{retrieve(e,r){return this._client.get(h`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Ee,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var lo=class extends w{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};async function Hg(t,e,r,n=null){if(t.body===null||typeof t.body!="object"||Array.isArray(t.body))throw new TypeError("Multipart request body must be an object");let o=Object.fromEntries(Object.entries(t.body).filter(([,l])=>l!==void 0));if(n!==null&&Object.keys(o).length===1&&Object.prototype.hasOwnProperty.call(o,n)){let l=o[n];if(typeof l!="string")throw new TypeError("Raw multipart alternative must be a string");return{...t,body:l,headers:v([t.headers,{"content-type":r[n].content_type}])}}let s=[];for(let[l,c]of Object.entries(r)){if(!Object.prototype.hasOwnProperty.call(o,l))continue;let d=o[l],m=c.json?JSON.stringify(d):d;if(typeof m!="string")throw new TypeError(`Multipart field ${l} must encode as a string`);s.push([l,tr([m],"",{type:c.content_type})]),delete o[l]}let a=(await we({...t,body:o},e)).body;if(!(a instanceof FormData))throw await a.cancel(),new TypeError("Unexpected streaming upload in typed multipart request body");for(let[l,c]of s)a.append(l,c,"");return{...t,body:a,headers:v([t.headers,{"content-type":null}])}}var Ys=class extends w{create(e,r){return this._client.post("/realtime/calls",Hg({body:e,...r,headers:v([{Accept:"application/sdp"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp"))}accept(e,r,n){return this._client.post(h`/realtime/calls/${e}/accept`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(h`/realtime/calls/${e}/hangup`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(h`/realtime/calls/${e}/refer`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(h`/realtime/calls/${e}/reject`,{body:r,...n,headers:v([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var ei=class extends w{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var ar=class extends w{constructor(){super(...arguments),this.clientSecrets=new ei(this._client),this.calls=new Ys(this._client)}};ar.ClientSecrets=ei;ar.Calls=Ys;function Vg(t,e){if(!e||!NS(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 Gg(t,r)&&ti(r),r}return mp(t,e)}function mp(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return r?jS(e,s):{...s,parsed_arguments:null};if(s.type==="message"){let i=s.content.map(a=>a.type==="output_text"?{...a,parsed:r?$S(e,a.text):null}:a);return{...s,content:i}}return s}),o={...t,output:n};return Gg(t,o)&&ti(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 $S(t,e){return wt(t.text?.format,e)}function NS(t){return zt(t.text?.format)?!0:Array.isArray(t.tools)&&t.tools.some(e=>fp(e)||e.type==="function"&&e.strict===!0||e.type==="namespace"&&e.tools.some(r=>r.type==="function"&&(fp(r)||r.strict===!0)))}function fp(t){return t?.$brand==="auto-parseable-tool"}function LS(t,e,r){for(let n of t)if(r==null){if(n.type==="function"&&n.name===e)return n}else if(n.type==="namespace"&&n.name===r)return n.tools.find(o=>o.type==="function"&&o.name===e)}function jS(t,e){let r=LS(t.tools??[],e.name,e.namespace),n=null;return fp(r)?n=r.$parseRaw(e.arguments):r?.strict&&(n=wt({type:"json_schema",$parseRaw:void 0},e.arguments)),{...e,parsed_arguments:n}}function Gg(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function ti(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("")}var ri=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let r=this.size;this.size+=1,this.update(r,e)}update(e,r){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw new RangeError(`missing output at index ${e}`);let n=this.capacity+e,o=r-(this.values[n]??0);if(o!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+o,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw new RangeError(`missing output at index ${e}`);let r=this.capacity,n=this.capacity+e,o=0;for(;r<n;)r%2===1&&(o+=this.values[r]??0,r+=1),n%2===1&&(n-=1,o+=this.values[n]??0),r=Math.floor(r/2),n=Math.floor(n/2);return o}grow(){let e=this.capacity;this.capacity*=2;let r=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)r[this.capacity+n]=this.values[e+n]??0;for(let n=this.capacity-1;n>0;n-=1)r[n]=(r[n*2]??0)+(r[n*2+1]??0);this.values=r}};function hp(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new ri}}function ni(t,e){if(e.type!=="message")return"";let r="";for(let n of e.content)n.type==="output_text"&&(r+=n.text);return t.outputTextLengths.set(e,r.length),r}function on(t,e){if(t.canonicalSnapshot===e)return;let r=new ri,n="";for(let o of e.output){let s=ni(t,o);n+=s,r.append(s.length)}e.output_text=n,t.outputTextIndex=r,t.canonicalSnapshot=e}function Zg(t,e){t.canonicalSnapshot=void 0,t.outputTextLengths=new WeakMap,t.outputTextIndex=new ri;let r=structuredClone(e);return!Object.getOwnPropertyDescriptor(r,"output_text")||r.output_text===null||r.output_text===void 0?on(t,r):r.output.length===0&&r.output_text===""&&(t.canonicalSnapshot=r),r}function ka(t,e,r,n,o){let s=t.outputTextLengths.get(e);if(s!==void 0){let i=s-n.length+o.length;t.outputTextLengths.set(e,i),t.outputTextIndex.update(r,i)}}function Jg(t,e,r){if(e.length===0){t.output_text+=r;return}t.output_text=t.output_text.slice(0,t.output_text.length-e.length)+r}function DS(t,e,r,n){if(r===void 0||e?.type!=="message")return 0;if(r<e.content.length-r-1){let i=0;for(let a=0;a<r;a+=1){let l=e.content[a];l?.type==="output_text"&&(i+=l.text.length)}return i}let o=0;for(let i=r+1;i<e.content.length;i+=1){let a=e.content[i];a?.type==="output_text"&&(o+=a.text.length)}return(t.outputTextLengths.get(e)??ni(t,e).length)-o-n.length}function oi(t,e,r,n,o,s){if(n===o)return;let i=e.output[r];if(r===e.output.length-1&&(s===void 0||i?.type==="message"&&s===i.content.length-1)){Jg(e,n,o);return}let a=DS(t,i,s,o),l=t.outputTextIndex.prefixSum(r)+a;if(l+n.length===e.output_text.length){Jg(e,n,o);return}e.output_text=e.output_text.slice(0,l)+o+e.output_text.slice(l+n.length)}var gp=new WeakMap;function sn(t,e,r,n=!1){if(!Array.isArray(t)||!Number.isSafeInteger(e)||e<0||e>t.length||(e===t.length?!n||e in t:!N(t,e)))throw new A(`missing ${r} at index ${e}`)}function hc(t,e,r){if(e!==t.length)throw new A(`missing ${r} at index ${e}`);sn(t,e,r,!0)}function W(t,e){sn(t.output,e,"output");let r=t.output[e];if(!r)throw new A(`missing output at index ${e}`);return r}function yp(t){return t.type==="function_call"||t.type==="custom_tool_call"||t.type==="shell_call"||t.type==="shell_call_output"}function gc(t,e){if(!N(t,"type")||typeof t.type!="string")throw new A(`expected an own output item type for ${e}`);let r=t.type==="function_call"||t.type==="custom_tool_call",n=[];if(N(t,"id")){if(typeof t.id!="string"||t.id.length===0)throw new A(`expected a non-empty output item id for ${e}`);n.push(`id:${t.id}`)}else if(!r)throw new A(`expected a non-empty output item id for ${e}`);if(yp(t)){if(!N(t,"call_id")||typeof t.call_id!="string"||t.call_id.length===0)throw new A(`expected a non-empty output item call_id for ${e}`);n.push(`call:${t.type}:${t.call_id}`)}return n}function Yg(t,e){for(let r of e)if(t.has(r))throw new A(`duplicate output item identity '${r}'`)}function ey(t,e){Yg(t,e);for(let r of e)t.add(r)}function ty(t){let e={snapshot:t,output:t.output,length:t.output.length,identities:new Set};for(let r=0;r<t.output.length;r+=1){let n=W(t,r);ey(e.identities,gc(n,"response snapshot"))}return e}function FS(t,e){let r=gp.get(t);if(r&&r.snapshot===e&&r.output===e.output&&r.length===e.output.length)return r;let n=ty(e);return gp.set(t,n),n}function Xg(t,e){let r=hp(),n=Zg(r,e),o=ty(n);return t.canonicalSnapshot=r.canonicalSnapshot,t.outputTextLengths=r.outputTextLengths,t.outputTextIndex=r.outputTextIndex,gp.set(t,o),n}var _p={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools","response.compaction.compacting":"compaction"};function zS(t){return t.type==="response.content_part.added"||t.type==="response.content_part.done"?t.part.type==="reasoning_text"?"reasoning":"message":_p[t.type]}function BS(t,e){let r=W(e,t.output_index),n=t.item;if(gc(r,t.type),gc(n,t.type),!N(n,"type")||r.type!==n.type)throw new A(`expected output item type '${r.type}', got '${n.type}'`);let o=N(r,"id")?r.id:void 0,s=N(n,"id")?n.id:void 0;if(o!==s)throw new A(`expected output item id '${o}', got '${s}'`);if(yp(r)&&yp(n)&&r.call_id!==n.call_id)throw new A(`expected output item call_id '${r.call_id}', got '${n.call_id}'`)}function US(t,e,r){if(t.type==="response.output_item.done"){BS(t,e);return}if(r&&(t.type==="response.shell_call_command.added"||t.type==="response.shell_call_command.delta"||t.type==="response.shell_call_command.done")){let a=W(e,t.output_index);if(!N(a,"type")||a.type!=="shell_call")throw new A(`expected output item type 'shell_call', got '${a.type}'`);return}if(t.type!=="response.content_part.added"&&t.type!=="response.content_part.done"&&!N(_p,t.type))return;let n=t;if(!N(t,"item_id")||typeof n.item_id!="string"||n.item_id.length===0)throw new A(`expected a non-empty item_id for ${t.type}`);let o=W(e,n.output_index),s=N(o,"id")?o.id:void 0;if(s!==n.item_id)throw new A(`expected item_id '${s}', got '${n.item_id}'`);let i=zS(n);if(o.type!==i)throw new A(`expected output item type '${i}', got '${o.type}'`)}function Qe(t,e){sn(t,e,"content");let r=t[e];if(!r)throw new A(`missing content at index ${e}`);return r}function Qg(t,e,r){let n=t.output.find(o=>o.type==="shell_call"&&o.call_id===e.call_id);for(n?sn(n.action.commands,r,"command"):sn(e.output,r,"content",!0);e.output.length<=r;)e.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return Qe(e.output,r)}function qS(t){return new Set(t)}var WS=qS(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function mc(t){throw new A("Unhandled response stream event: unknown")}var KS=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function HS(t){let e;try{e=Object.getOwnPropertyDescriptor(t,"type")}catch{return mc(t)}let r=e?.value;if(typeof r!="string"||!WS.has(r))return mc(t);let n=new Map([["type",r]]);if(r==="response.output_item.added"||r==="response.output_item.done"||r==="response.content_part.added"||r==="response.content_part.done"||r==="response.shell_call_command.added"||r==="response.shell_call_command.delta"||r==="response.shell_call_command.done"||N(_p,r))try{for(let s of KS){let i=Object.getOwnPropertyDescriptor(t,s);n.set(s,i?t[s]:void 0)}r==="response.output_item.done"?n.set("item",structuredClone(t.item)):(r==="response.content_part.added"||r==="response.content_part.done")&&n.set("part",structuredClone(t.part))}catch{return mc(t)}return new Proxy(t,{get(s,i){return n.has(i)?n.get(i):Reflect.get(s,i,s)}})}function VS(t,e,r){switch(t.type){case"response.output_item.added":{hc(e.output,t.output_index,"output");let n=FS(r,e),o=structuredClone(t.item),s=gc(o,t.type);Yg(n.identities,s),o.type==="message"&&on(r,e),e.output.push(o),ey(n.identities,s),n.length=e.output.length;let i=ni(r,o);return r.canonicalSnapshot===e&&r.outputTextIndex.append(i.length),i&&(e.output_text+=i),!0}case"response.output_item.done":{let n=W(e,t.output_index),o=ni(r,n),s=t.item;(n.type==="message"||s.type==="message")&&on(r,e),e.output[t.output_index]=s;let i=ni(r,s);return r.canonicalSnapshot===e&&r.outputTextIndex.update(t.output_index,i.length),oi(r,e,t.output_index,o,i),!0}default:return!1}}function GS(t,e,r){switch(t.type){case"response.content_part.added":{let n=W(e,t.output_index),{type:o}=n,{part:s}=t;if(o==="message"&&s.type!=="reasoning_text"){hc(n.content,t.content_index,"content");let i=s;i.type==="output_text"&&on(r,e),n.content.push(i),i.type==="output_text"&&(ka(r,n,t.output_index,"",i.text),oi(r,e,t.output_index,"",i.text,t.content_index))}else if(o==="reasoning"&&s.type==="reasoning_text"){let i=n.content??[];hc(i,t.content_index,"content"),n.content||(n.content=i),i.push(s)}return!0}default:return!1}}function JS(t,e,r){switch(t.type){case"response.content_part.done":{let n=W(e,t.output_index),{part:o}=t;if(n.type==="message"&&o.type!=="reasoning_text"){let s=Qe(n.content,t.content_index),i=s.type==="output_text"?s.text:"",a=o;(s.type==="output_text"||a.type==="output_text")&&on(r,e),n.content[t.content_index]=a;let l=a.type==="output_text"?a.text:"";ka(r,n,t.output_index,i,l),oi(r,e,t.output_index,i,l,t.content_index)}else if(n.type==="reasoning"&&o.type==="reasoning_text"){let{content:s}=n;if(!s)throw new A(`missing content at index ${t.content_index}`);Qe(s,t.content_index),s[t.content_index]=o}return!0}default:return!1}}function ZS(t,e,r){switch(t.type){case"response.output_text.delta":{let n=W(e,t.output_index);if(n.type==="message"){let o=Qe(n.content,t.content_index);if(o.type!=="output_text")throw new A(`expected content to be 'output_text', got ${o.type}`);let s=o.text;on(r,e),o.text=s+t.delta,ka(r,n,t.output_index,s,o.text),t.output_index===e.output.length-1&&t.content_index===n.content.length-1?e.output_text+=t.delta:oi(r,e,t.output_index,s,o.text,t.content_index)}return!0}case"response.output_text.done":{let n=W(e,t.output_index);if(n.type==="message"){let o=Qe(n.content,t.content_index);if(o.type!=="output_text")throw new A(`expected content to be 'output_text', got ${o.type}`);let s=o.text;on(r,e),o.text=t.text,ka(r,n,t.output_index,s,t.text),oi(r,e,t.output_index,s,t.text,t.content_index)}return!0}case"response.output_text.annotation.added":{let n=W(e,t.output_index);if(n.type==="message"){let o=Qe(n.content,t.content_index);if(o.type!=="output_text")throw new A(`expected content to be 'output_text', got ${o.type}`);sn(o.annotations,t.annotation_index,"annotation",!0),o.annotations[t.annotation_index]=structuredClone(t.annotation)}return!0}default:return!1}}function XS(t,e){switch(t.type){case"response.refusal.delta":{let r=W(e,t.output_index);if(r.type==="message"){let n=Qe(r.content,t.content_index);if(n.type!=="refusal")throw new A(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}return!0}case"response.refusal.done":{let r=W(e,t.output_index);if(r.type==="message"){let n=Qe(r.content,t.content_index);if(n.type!=="refusal")throw new A(`expected content to be 'refusal', got ${n.type}`);n.refusal=t.refusal}return!0}case"response.function_call_arguments.delta":{let r=W(e,t.output_index);return r.type==="function_call"&&(r.arguments+=t.delta),!0}case"response.function_call_arguments.done":{let r=W(e,t.output_index);return r.type==="function_call"&&(r.arguments=t.arguments),!0}case"response.custom_tool_call_input.delta":{let r=W(e,t.output_index);return r.type==="custom_tool_call"&&(r.input+=t.delta),!0}case"response.custom_tool_call_input.done":{let r=W(e,t.output_index);return r.type==="custom_tool_call"&&(r.input=t.input),!0}case"response.mcp_call_arguments.delta":{let r=W(e,t.output_index);return r.type==="mcp_call"&&(r.arguments+=t.delta),!0}case"response.mcp_call_arguments.done":{let r=W(e,t.output_index);return r.type==="mcp_call"&&(r.arguments=t.arguments),!0}default:return!1}}function QS(t,e){switch(t.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let r=W(e,t.output_index);if(r.type==="shell_call"){let n=t.type==="response.shell_call_command.added";sn(r.action.commands,t.command_index,"command",n),r.action.commands[t.command_index]=t.command}return!0}case"response.shell_call_command.delta":{let r=W(e,t.output_index);return r.type==="shell_call"&&(sn(r.action.commands,t.command_index,"command"),r.action.commands[t.command_index]+=t.delta),!0}case"response.shell_call_output_content.delta":{let r=W(e,t.output_index);if(r.type==="shell_call_output"){let n=Qg(e,r,t.command_index);n.stdout+=t.delta.stdout??"",n.stderr+=t.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let r=W(e,t.output_index);if(r.type==="shell_call_output"){let n=Qe(t.output,0);Qg(e,r,t.command_index),r.output[t.command_index]=structuredClone(n)}return!0}default:return!1}}function YS(t,e){switch(t.type){case"response.reasoning_text.delta":{let r=W(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new A(`missing content at index ${t.content_index}`);let n=Qe(r.content,t.content_index);if(n.type!=="reasoning_text")throw new A(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}return!0}case"response.reasoning_text.done":{let r=W(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new A(`missing content at index ${t.content_index}`);let n=Qe(r.content,t.content_index);if(n.type!=="reasoning_text")throw new A(`expected content to be 'reasoning_text', got ${n.type}`);n.text=t.text}return!0}case"response.reasoning_summary_part.added":{let r=W(e,t.output_index);return r.type==="reasoning"&&(hc(r.summary,t.summary_index,"content"),r.summary.push(structuredClone(t.part))),!0}case"response.reasoning_summary_part.done":{let r=W(e,t.output_index);return r.type==="reasoning"&&(Qe(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part)),!0}case"response.reasoning_summary_text.delta":{let r=W(e,t.output_index);if(r.type==="reasoning"){let n=Qe(r.summary,t.summary_index);n.text+=t.delta}return!0}case"response.reasoning_summary_text.done":{let r=W(e,t.output_index);if(r.type==="reasoning"){let n=Qe(r.summary,t.summary_index);n.text=t.text}return!0}default:return!1}}function eT(t,e){switch(t.type){case"response.code_interpreter_call_code.delta":{let r=W(e,t.output_index);return r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta),!0}case"response.code_interpreter_call_code.done":{let r=W(e,t.output_index);return r.type==="code_interpreter_call"&&(r.code=t.code),!0}case"response.code_interpreter_call.in_progress":{let r=W(e,t.output_index);return r.type==="code_interpreter_call"&&(r.status="in_progress"),!0}case"response.code_interpreter_call.interpreting":{let r=W(e,t.output_index);return r.type==="code_interpreter_call"&&(r.status="interpreting"),!0}case"response.code_interpreter_call.completed":{let r=W(e,t.output_index);return r.type==="code_interpreter_call"&&(r.status="completed"),!0}default:return!1}}function tT(t,e){switch(t.type){case"response.file_search_call.in_progress":{let r=W(e,t.output_index);return r.type==="file_search_call"&&(r.status="in_progress"),!0}case"response.file_search_call.searching":{let r=W(e,t.output_index);return r.type==="file_search_call"&&(r.status="searching"),!0}case"response.file_search_call.completed":{let r=W(e,t.output_index);return r.type==="file_search_call"&&(r.status="completed"),!0}case"response.web_search_call.in_progress":{let r=W(e,t.output_index);return r.type==="web_search_call"&&(r.status="in_progress"),!0}case"response.web_search_call.searching":{let r=W(e,t.output_index);return r.type==="web_search_call"&&(r.status="searching"),!0}case"response.web_search_call.completed":{let r=W(e,t.output_index);return r.type==="web_search_call"&&(r.status="completed"),!0}default:return!1}}function rT(t,e){switch(t.type){case"response.image_generation_call.in_progress":{let r=W(e,t.output_index);return r.type==="image_generation_call"&&(r.status="in_progress"),!0}case"response.image_generation_call.generating":{let r=W(e,t.output_index);return r.type==="image_generation_call"&&(r.status="generating"),!0}case"response.image_generation_call.completed":{let r=W(e,t.output_index);return r.type==="image_generation_call"&&(r.status="completed"),!0}case"response.mcp_call.in_progress":{let r=W(e,t.output_index);return r.type==="mcp_call"&&(r.status="in_progress"),!0}case"response.mcp_call.completed":{let r=W(e,t.output_index);return r.type==="mcp_call"&&(r.status="completed"),!0}case"response.mcp_call.failed":{let r=W(e,t.output_index);return r.type==="mcp_call"&&(r.status="failed"),!0}default:return!1}}function nT(t){switch(t.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}function oT(t){switch(t.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.compaction.compacting":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":return!0;default:return!1}}function yc(){return hp()}function ry(t,e,r,n=!1,o){let s=HS(t);if(o&&s.type!=="keepalive"&&o(s),!e){if(s.type!=="response.created")throw new A(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return Xg(r,s.response)}return US(s,e,n),VS(s,e,r)||GS(s,e,r)||JS(s,e,r)||ZS(s,e,r)||XS(s,e)||QS(s,e)||YS(s,e)||eT(s,e)||tT(s,e)||rT(s,e)?e:nT(s)?Xg(r,s.response):oT(s)?e:mc(s)}var an,_c,co,wc,Ca,wp,bp,Ap,bc=class t extends jr{constructor(e){super(),an.add(this),_c.set(this,void 0),co.set(this,void 0),wc.set(this,void 0),Ca.set(this,yc()),E(this,_c,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,__metadata:{...n?.__metadata,helperMethod:"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),u(this,an,"m",wp).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)u(this,an,"m",bp).call(this,i,s);if(o.controller.signal?.aborted)throw this._userAbortError();return u(this,an,"m",Ap).call(this)}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),u(this,an,"m",wp).call(this),this._connected();let n=Je.fromReadableStream(e,this.controller);for await(let o of n)u(this,an,"m",bp).call(this,o,null);if(n.controller.signal?.aborted)throw this._userAbortError();return u(this,an,"m",Ap).call(this)}[(_c=new WeakMap,co=new WeakMap,wc=new WeakMap,Ca=new WeakMap,an=new WeakSet,wp=function(){this.ended||(E(this,co,void 0,"f"),E(this,Ca,yc(),"f"))},bp=function(r,n){if(this.ended)return;let o=(a,l)=>{(n==null||l.sequence_number>n)&&this._emit(a,l)};if(r.type==="error"){let a="error"in r&&typeof r.error=="object"&&r.error!==null?r.error:r;throw new ee(void 0,a,r.message,void 0)}let s=r,i=ry(r,u(this,co,"f"),u(this,Ca,"f"),!0,a=>{s=a});switch(E(this,co,i,"f"),o("event",r),s.type){case"response.output_text.delta":{let a=i.output[s.output_index];if(!a)throw new A(`missing output at index ${s.output_index}`);if(a.type==="message"){let l=a.content[s.content_index];if(!l)throw new A(`missing content at index ${s.content_index}`);if(l.type!=="output_text")throw new A(`expected content to be 'output_text', got ${l.type}`);o("response.output_text.delta",{...s,type:s.type,item_id:s.item_id,output_index:s.output_index,content_index:s.content_index,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let a=i.output[s.output_index];if(!a)throw new A(`missing output at index ${s.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...s,type:s.type,item_id:s.item_id,output_index:s.output_index,snapshot:a.arguments});break}default:{o(s.type,r);break}}},Ap=function(){if(this.ended)throw new A("stream has ended, this shouldn't happen");let r=u(this,co,"f");if(!r)throw new A("request ended without sending any events");E(this,co,void 0,"f"),E(this,Ca,yc(),"f");let n=sT(r,u(this,_c,"f"));return E(this,wc,n,"f"),n},Symbol.asyncIterator)](){return this._createIterator(e=>{let r=n=>e(n);return this.on("event",r),()=>this.off("event",r)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=u(this,wc,"f");if(!e)throw new A("stream ended without producing a Response");return e}};function sT(t,e){return Vg(t,e)}var si=class extends w{list(e,r={},n){return this._client.getAPIList(h`/responses/${e}/input_items`,P,{query:r,...n,__security:{bearerAuth:!0}})}};var ii=class extends w{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Wt=class extends w{constructor(){super(...arguments),this.inputItems=new si(this._client),this.inputTokens=new ii(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"&&ti(n),n))}retrieve(e,r={},n){return this._client.get(h`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&ti(o),o))}delete(e,r){return this._client.delete(h`/responses/${e}`,{...r,headers:v([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>mp(n,e))}stream(e,r){return bc.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(h`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};Wt.InputItems=si;Wt.InputTokens=ii;var ai=class extends w{retrieve(e,r){return this._client.get(h`/safety/alerts/${e}`,{...r,__security:{bearerAuth:!0}})}};var ln=class extends w{constructor(){super(...arguments),this.alerts=new ai(this._client)}};ln.Alerts=ai;var li=class extends w{retrieve(e,r){return this._client.get(h`/skills/${e}/content`,{...r,headers:v([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ci=class extends w{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(h`/skills/${o}/versions/${e}/content`,{...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var uo=class extends w{constructor(){super(...arguments),this.content=new ci(this._client)}create(e,r={},n){return this._client.post(h`/skills/${e}/versions`,Nr({body:r,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(h`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/skills/${e}/versions`,P,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(h`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};uo.Content=ci;var lr=class extends w{constructor(){super(...arguments),this.content=new li(this._client),this.versions=new uo(this._client)}create(e={},r){return this._client.post("/skills",Nr({body:e,...r,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,r){return this._client.get(h`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",P,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};lr.Content=li;lr.Versions=uo;var ui=class extends w{create(e,r,n){return this._client.post(h`/uploads/${e}/parts`,we({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var cn=class extends w{constructor(){super(...arguments),this.parts=new ui(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(h`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(h`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};cn.Parts=ui;function ny(t,e,r,n){return Oa(o=>t.retrieve(r,{vector_store_id:e},{...n,headers:o}),["in_progress"],["failed","cancelled","completed"],n)}function oy(t,e,r,n){return Oa(o=>t.retrieve(r,{vector_store_id:e},{...n,headers:o}),["in_progress"],["failed","cancelled","completed"],n)}var sy=async t=>{let e=await Promise.allSettled(t),r=e.filter(o=>o.status==="rejected");if(r.length)throw Object.defineProperty(new Error(`${r.length} promise(s) failed`),"rejections",{configurable:!0,value:r.map(({reason:o})=>o),writable:!0});let n=[];for(let o of e)o.status==="fulfilled"&&n.push(o.value);return n};async function iy(t,e,r,n,o,s){if(n==null||n.length===0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=s?.maxConcurrency??5,a=Math.min(i,n.length);if(a===0)throw new RangeError("maxConcurrency must be greater than 0");let l=n.values(),c=[...o];async function d(f){for(let g of f){let b=await e.files.create({file:g,purpose:"assistants"},s);c.push(b.id)}}let m=[];m.length=a;for(let f=0;f<m.length;f+=1)m[f]=d(l);return await sy(m),await t.createAndPoll(r,{file_ids:c},s)}var di=class extends w{create(e,r,n){return this._client.post(h`/vector_stores/${e}/file_batches`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(h`/vector_stores/${o}/file_batches/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(h`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:v([{"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)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(h`/vector_stores/${o}/file_batches/${e}/files`,P,{query:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){return await oy(this,e,r,n)}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){return await iy(this,this._client,e,r,n,o)}};var pi=class extends w{create(e,r,n){return this._client.post(h`/vector_stores/${e}/files`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(h`/vector_stores/${o}/files/${e}`,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(h`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/vector_stores/${e}/files`,P,{query:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(h`/vector_stores/${o}/files/${e}`,{...n,headers:v([{"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){return await ny(this,e,r,n)}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(h`/vector_stores/${o}/files/${e}/content`,Ee,{...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var cr=class extends w{constructor(){super(...arguments),this.files=new pi(this._client),this.fileBatches=new di(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/vector_stores/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/vector_stores/${e}`,{body:r,...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",P,{query:e,...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/vector_stores/${e}`,{...r,headers:v([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(h`/vector_stores/${e}/search`,Ee,{body:r,method:"post",...n,headers:v([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};cr.Files=pi;cr.FileBatches=di;var po=class extends w{create(e,r){return this._client.post("/videos",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(h`/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(h`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(h`/videos/${e}/content`,{query:r,...n,headers:v([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",we({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(h`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(h`/videos/${e}/remix`,Nr({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var ay=32,hT=32;function xp(t){return t.split(" ",ay+1).length>ay}function*vp(t){let e=0;for(;e<=t.length;){let r=t.indexOf(" ",e),n=t.slice(e,r===-1?void 0:r);if(yield n.startsWith("v1,")?n.slice(3):n,r===-1)break;e=r+1}}function ly(t){try{let e=uc(t);return e.byteLength===hT?e:void 0}catch{return}}function gT(t){for(let e of vp(t)){let r=ly(e);if(r)return r}}function yT(t,e,r){let n=r;for(let o of vp(t)){let s=ly(o);if(!s)continue;let i=0;for(let[a,l]of s.entries())i|=l^(e[a]??0);i===0&&(n=s)}return n}async function cy(t,e,r,n,o,s){let i=Number.parseInt(r,10);if(Number.isNaN(i))throw new Ge("Invalid webhook timestamp format");let a=Math.floor(Date.now()/1e3);if(a-i>s)throw new Ge("Webhook timestamp is too old");if(i>a+s)throw new Ge("Webhook timestamp is too new");let l=xp(e),c=l?gT(e):void 0;if(l&&!c)throw new Ge("The given webhook signature does not match the expected signature");let d=Uint8Array.from(o.startsWith("whsec_")?uc(o.slice(6)):Me(o)),m=n?`${n}.${r}.${t}`:`${r}.${t}`,f=Uint8Array.from(Me(m)),g=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,l?["sign","verify"]:["verify"]);if(l&&c){let b=new Uint8Array(await crypto.subtle.sign("HMAC",g,f)),_=yT(e,b,c);try{if(await crypto.subtle.verify("HMAC",g,Uint8Array.from(_),f))return}catch{}throw new Ge("The given webhook signature does not match the expected signature")}for(let b of vp(e))try{let _=Uint8Array.from(uc(b));if(await crypto.subtle.verify("HMAC",g,_,f))return}catch{}throw new Ge("The given webhook signature does not match the expected signature")}var fi,uy,Ac,fo=class extends w{constructor(){super(...arguments),fi.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");u(this,fi,"m",uy).call(this,n);let s=v([r]).values,i=u(this,fi,"m",Ac).call(this,s,"webhook-signature"),a=u(this,fi,"m",Ac).call(this,s,"webhook-timestamp"),l=u(this,fi,"m",Ac).call(this,s,"webhook-id");if(xp(i)&&typeof crypto.subtle.sign!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");return await cy(e,i,a,l,n,o)}};fi=new WeakSet,uy=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")},Ac=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};async function Ip(t){let e,r=await t._callApiKey(n=>{e=n});return{apiKey:e===void 0?t.apiKey:e,isProvider:r}}var py=Symbol.for("openai.node.providerDefinitions.v1"),fy=globalThis,my=fy[py],hy=my??new WeakMap;my||Object.defineProperty(fy,py,{value:hy});function gy(t){let e=hy.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Sp,St,Pa,se,xc,ur,Ma,Ra,by;function yy(){if(Zm())return!0;let t=globalThis;return typeof t.WorkerGlobalScope=="function"&&t instanceof t.WorkerGlobalScope&&typeof t.WorkerNavigator=="function"&&t.navigator instanceof t.WorkerNavigator&&typeof t.navigator?.userAgent=="string"&&t.navigator.userAgent!=="Cloudflare-Workers"&&t.process?.versions?.node===void 0&&t.Deno===void 0&&t.Bun===void 0&&t.EdgeRuntime===void 0&&t.WebSocketPair===void 0}var _T="workload-identity-auth",_y=Symbol("inheritedDataResidencySelection"),F=class{constructor(e={}){Sp.add(this),Pa.set(this,void 0),se.set(this,void 0),xc.set(this,void 0),ur.set(this,void 0),Ma.set(this,!1),Ra.set(this,new WeakMap),this.completions=new Xn(this),this.chat=new zr(this),this.embeddings=new eo(this),this.files=new ro(this),this.images=new io(this),this.contentProvenanceChecks=new Yn(this),this.audio=new Ut(this),this.moderations=new lo(this),this.models=new ao(this),this.fineTuning=new It(this),this.graders=new nn(this),this.vectorStores=new cr(this),this.safety=new ln(this),this.webhooks=new fo(this),this.beta=new tt(this),this.batches=new Un(this),this.uploads=new cn(this),this.admin=new Ur(this),this.responses=new Wt(this),this.live=new qt(this),this.realtime=new ar(this),this.conversations=new tn(this),this.evals=new rn(this),this.containers=new en(this),this.skills=new lr(this),this.videos=new po(this);let{credential:r,options:n}=$h(e);e=n;let o=pd(e),s=e.provider,{baseURL:i=s?null:ft("OPENAI_BASE_URL"),dataResidency:a,[_y]:l=!1,apiKey:c=s?null:ft("OPENAI_API_KEY")??null,adminAPIKey:d=s?null:ft("OPENAI_ADMIN_KEY")??null,organization:m=s?null:ft("OPENAI_ORG_ID")??null,project:f=s?null:ft("OPENAI_PROJECT_ID")??null,webhookSecret:g=ft("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:b,x509Transport:_,credential:x,...O}=e;if(s){let j=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter(M=>(M==="workloadIdentity"?b:e[M])!=null);if(j.length)throw new A(`The \`provider\` option cannot be used with ${j.map(M=>`\`${M}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let y=Rl(b)?{x509:b,legacy:void 0}:{x509:void 0,legacy:b},S=y.x509,I=S!==void 0,R=s?gy(s):void 0,k={apiKey:c,adminAPIKey:d,organization:m,project:f,webhookSecret:g,workloadIdentity:b,x509Transport:_,provider:s,...O,baseURL:R?.baseURL??o??(i||(I?ph:"https://api.openai.com/v1"))};if(_&&!I)throw new A("An X.509 transport requires an X.509 workload identity.");if(I){if(o!==void 0||l)throw new A("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new A("X.509 workload identity does not support a custom fetch implementation.");if(jo(k.baseURL),Xi(k.fetchOptions),this.fetchWithAuth!==St.prototype.fetchWithAuth||this.fetchWithTimeout!==St.prototype.fetchWithTimeout)throw new A("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(c&&b)throw new A("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!R&&!c&&!d&&!b)throw new A("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!k.dangerouslyAllowBrowser&&yy())throw new A(`It looks like you're running in a browser-like environment.
58
+
59
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
60
+ If you understand the risks and have appropriate mitigations in place,
61
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
62
+
63
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
64
+
65
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
66
+ `);this.baseURL=k.baseURL,E(this,Ma,o!==void 0||l,"f"),this.timeout=k.timeout??St.DEFAULT_TIMEOUT,this.logger=k.logger??console;let D="warn";this.logLevel=D,this.logLevel=nd(k.logLevel,"ClientOptions.logLevel",this)??nd(ft("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??D,this.fetchOptions=k.fetchOptions,this.maxRetries=k.maxRetries??2,this.fetch=k.fetch??Ui(),E(this,Pa,Ym,"f");let $=s||r?void 0:ft("OPENAI_CUSTOM_HEADERS");if($){let j={};for(let M of $.split(`
67
+ `)){let C=M.indexOf(":");C>=0&&(j[M.substring(0,C).trim()]=M.substring(C+1).trim())}k.defaultHeaders=v([j,k.defaultHeaders])}if(this._options=k,this._provider=R,S){let j=new je(S,_,m,f);this._workloadIdentityAuth=j,E(this,se,j,"f"),E(this,xc,r,"f"),E(this,ur,j.fetch(),"f"),this.fetch=u(this,ur,"f"),xh(this)}else y.legacy&&(this._workloadIdentityAuth=new El(y.legacy,this.fetch));this.apiKey=typeof c=="string"?c:null,this.adminAPIKey=d,this.organization=m,this.project=f,this.webhookSecret=g}withOptions(e){let r=pd(e),n=u(this,se,"f"),o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:u(this,se,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:n?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:s,provider:i}=Nh(o,e,u(this,xc,"f"),n!==void 0);r!==void 0&&delete o.baseURL;let a={...o,...e,credential:s,provider:i,[_y]:u(this,Ma,"f")&&r===void 0&&!N(e,"baseURL")&&e.credential===void 0&&!i},l=new this.constructor(a);return i&&new URL(l.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(l._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),l.fetchOptions=e.fetchOptions,l.fetch=e.fetch??Ui(),l.organization=e.organization??null,l.project=e.project??null),u(this,se,"f")&&u(l,se,"f")&&this.baseURL===l.baseURL&&u(this,se,"f").matches(u(l,se,"f"))&&(l._workloadIdentityAuth=u(this,se,"f"),E(l,se,u(this,se,"f"),"f"),E(l,ur,u(this,ur,"f"),"f")),l}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(u(this,se,"f")??this._workloadIdentityAuth)instanceof je&&r.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):v([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let r=u(this,se,"f")??this._workloadIdentityAuth;if(r){if(r instanceof je){if(r===this._workloadIdentityAuth&&(this.fetchWithAuth!==St.prototype.fetchWithAuth||this.fetchWithTimeout!==St.prototype.fetchWithTimeout))throw new A("X.509 workload identity does not support overridden fetch dispatch hooks.");let s=r.headerSnapshots();if(!je.shouldAuthenticate(e,s.defaultHeaders,s.requestHeaders))return}let o=r instanceof je?await r.getToken(e,{apiURL:r.requestAPIURL(),...r.headerSnapshots(),...r.requestSnapshot(),signal:r.effectiveSignal(),...r.tenantSnapshot()}):await r.getToken();return v([{Authorization:`Bearer ${o}`}])}let{apiKey:n}=await Ip(this);if(n!=null)return v([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return v([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return uh(e)}getUserAgent(){return`${this.constructor.name}/JS ${$r}`}defaultIdempotencyKey(){return`stainless-node-retry-${_t()}`}makeStatusError(e,r,n,o){let s=r&&typeof r=="object"&&r.error==null?{error:r}:r;return ee.generate(e,s,n,o)}_hasApiKeyProvider(){return typeof this._options.apiKey=="function"}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let r=this._options.apiKey;if(typeof r!="function")return e?.(this.apiKey),!1;let n;try{n=await r()}catch(o){throw o instanceof A?o:new A(`Failed to get token from 'apiKey' function: ${o.message}`,{cause:o})}if(typeof n!="string"||!n)throw new A(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,r,n){let o=!u(this,Sp,"m",by).call(this)&&n||this.baseURL,s=Rm(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!Qu(i)||!Qu(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){}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){let n=u(this,se,"f")??this._workloadIdentityAuth,o=n instanceof je?Promise.resolve(e).then(s=>n.runRequest(()=>this.makeRequest(s,r,void 0),this)):this.makeRequest(e,r,void 0);return this.responsePromise(o)}responsePromise(e,r=(n,o)=>this.parseResponseWithTimeout(n,o)){let n=new In(this,e,(o,s)=>{let i=u(this,Ra,"f").get(s.controller)?.continueRequest;return i?i(()=>r(o,s)):r(o,s)});return n.withResponse=async()=>{let o=await n,{response:s}=await e;return{data:o,response:s,request_id:s.headers.get("x-request-id")}},n._thenUnwrap=o=>this.responsePromise(e,async(s,i)=>Vi(o(await r(s,i),i),i.response)),n}async parseResponseWithTimeout(e,r){if(r.options.stream||r.options.__binaryResponse||r.response.status===204||r.response.headers.get("content-length")==="0")return vn(e,r);for(;;){let n=u(this,Ra,"f").get(r.controller),o=n?.timeout??r.options.timeout??this.timeout,s=n?.authentication,i=s?r.controller.signal:r.options.signal,a=()=>s&&i?this._makeUserAbortError(i):new ie,l;try{l=s?.remainingTimeout(r.options,o)??Math.max(0,r.startTime+o-Date.now())}catch(f){let g=i?.aborted?a():void 0;throw r.controller.abort(),Zt(r.response.body).catch(()=>{}),g??f}let c,d,m=!1;try{if(i?.aborted&&n?.helperMethod!=="runTools")throw a();let f=new Promise((g,b)=>{c=setTimeout(()=>{m=!0,r.controller.abort(),b(new ce)},l),i&&(d=()=>{m||b(a())},i.addEventListener("abort",d,{once:!0}))});return await Promise.race([vn(e,r),f])}catch(f){if(i?.aborted&&!m)throw a();if(!m)throw s&&f instanceof SyntaxError?new SyntaxError("X.509 workload identity API response contains invalid JSON."):s&&!(f instanceof A)?new st({message:"X.509 workload identity API response body could not be read."}):f;let g=n?.retriesRemaining??0;if(!g||n?.hasStreamingBody||r.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&r.options.body instanceof globalThis.ReadableStream||typeof r.options.body=="object"&&r.options.body!==null&&(Symbol.asyncIterator in r.options.body||Symbol.iterator in r.options.body&&"next"in r.options.body&&typeof r.options.body.next=="function"))throw new ce;c!==void 0&&clearTimeout(c),d&&i?.removeEventListener("abort",d),d=void 0;let b=await this.retryRequest(r.options,g,r.retryOfRequestLogID??r.requestLogID,void 0,r.requestSignal);Object.assign(r,b)}finally{c!==void 0&&clearTimeout(c),d&&i?.removeEventListener("abort",d)}}}async readX509ResponseError(e,r,n,o,s){let i=new AbortController,a=o.signal,l=!1,c=()=>i.abort(a.reason);a.addEventListener("abort",c,{once:!0}),a.aborted&&c();try{let d=s.remainingTimeout(r,n),m=s.waitForRetry(d,i.signal).then(()=>{throw new ce}),f=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),m]);if(a.aborted)throw this._makeUserAbortError(a);return f}catch(d){throw d instanceof ce&&(l=!a.aborted,o.abort(),Zt(e.body).catch(()=>{})),a.aborted&&!l?this._makeUserAbortError(a):d}finally{a.removeEventListener("abort",c),i.abort()}}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s);let i=u(this,se,"f");i?.beginRequestPreparation(),await this.prepareOptions(o),i?.beginRequestPlanning();let a;try{let j=await this.buildRequest(o,{retryCount:s-r});if(a={req:j.req,url:j.url,timeout:j.timeout},i){Yu("timeout",a.timeout),i.authorizePlannedRequest(a.url,a.req,a.timeout),je.isStreamingRequestBody(a.req.body)&&(o.__metadata={...o.__metadata,hasStreamingBody:!0}),await this.prepareRequest(a.req,{url:a.url,options:o}),await this._provider?.prepareRequest?.(a.req,{url:a.url,options:o}),i.beginRequestPlanning(),i.authorizePlannedRequest(a.url,a.req,a.timeout,!0),je.isStreamingRequestBody(a.req.body)&&(o.__metadata={...o.__metadata,hasStreamingBody:!0});let M=i.requestSnapshot().signal;if(M?.aborted||a.req.signal?.aborted)throw this._makeUserAbortError(M?.aborted?M:a.req.signal);i.setEffectiveSignal(a.req.signal||M?wy(a.req.signal??M,M).signal:void 0),i.beginRequestNetwork();let C=o.__security??{bearerAuth:!0},L=await this.authHeaders(o,C),z=i.headerSnapshots(),V=v([z.defaultHeaders,z.requestHeaders]);for(let[Ne,Z]of L?.values??[])!V.nulls.has(Ne)&&!a.req.headers.has(Ne)&&a.req.headers.set(Ne,Z);this.validateHeaders(v([V,a.req.headers]),C)}}catch(j){if(i?.retireRequestBody(),i&&r&&!o.__metadata?.hasStreamingBody&&je.isRetryableFailure(j))return await this.retryRequest(o,r,n??"x509-token-exchange",je.retryHeaders(j));throw j}let{req:l,url:c}=a,d=i?Math.min(a.timeout,i.requestSnapshot().timeout):a.timeout;i?.bindRequest(o,l,this.adminAPIKey);let m=o.__metadata?.hasStreamingBody===!0;i||(await this.prepareRequest(l,{url:c,options:o}),await this._provider?.prepareRequest?.(l,{url:c,options:o})),i?.adoptRequestHeaders(l),i&&je.isStreamingRequestBody(l.body)&&(m=!0);let f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=n===void 0?"":`, retryOf: ${n}`,b=i?.requestStartedAt(o)??Date.now();he(this).debug(`[${f}] sending request`,Xt({retryOfRequestLogID:n,method:o.method,url:c,options:i?{body:l.body,...i.requestSnapshot()}:o,headers:l.headers}));let _=i?i.requestSnapshot().signal:o.signal;if(_?.aborted||l.signal?.aborted)throw this._makeUserAbortError(_?.aborted?_:l.signal);let x=o.__security??{bearerAuth:!0},O=i||this.fetchWithTimeout===St.prototype.fetchWithTimeout?wy(l.signal??(i?_:void 0),i?_:void 0):new AbortController,y=i?.remainingTimeout(o,d)??d,S=i?St.prototype.fetchWithAuth:this.fetchWithAuth;i?.releaseRequestBody(l.body);let I=await S.call(this,c,l,y,O,x).catch(Fi),R=Date.now();if(I instanceof globalThis.Error){let j=`retrying, ${r} attempts remaining`;if(_?.aborted||l.signal?.aborted)throw this._makeUserAbortError(_?.aborted?_:l.signal);let M=Jt(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(r&&!m&&(!i||kl(I)))return he(this).info(`[${f}] connection ${M?"timed out":"failed"} - ${j}`),he(this).debug(`[${f}] connection ${M?"timed out":"failed"} (${j})`,Xt({retryOfRequestLogID:n,url:c,durationMs:R-b,message:i?"X.509 workload identity API connection failed.":I.message})),this.retryRequest(o,r,n??f,void 0,l.signal);let C=m?"error; streaming body cannot be retried":"error; no more retries left";if(he(this).info(`[${f}] connection ${M?"timed out":"failed"} - ${C}`),he(this).debug(`[${f}] connection ${M?"timed out":"failed"} (${C})`,Xt({retryOfRequestLogID:n,url:c,durationMs:R-b,message:i?"X.509 workload identity API connection failed.":I.message})),I instanceof it||I instanceof bn)throw I;if(M){let L="cause"in I?I.cause:void 0,V=typeof L=="object"&&L!==null&&"code"in L&&L.code==="UND_ERR_HEADERS_TIMEOUT"?new ce({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new ce;throw i?new ce:Object.assign(V,{cause:I})}throw i?new st({message:"X.509 workload identity API connection failed."}):new st({message:wT(I),cause:I})}let k=[...I.headers.entries()].filter(([j])=>j==="x-request-id").map(([j,M])=>", "+j+": "+JSON.stringify(M)).join(""),D=`[${f}${g}${k}] ${l.method} ${Al(c)} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${R-b}ms`;if(!I.ok){let j=I.status===401&&i&&x.bearerAuth&&i.usedWorkloadToken(o);if(j&&i.invalidateToken(),I.status===401&&(i||this._workloadIdentityAuth)&&x.bearerAuth&&(!i||i.usedWorkloadToken(o))&&(!i||r>0)&&!m&&!o.__metadata?.workloadIdentityTokenRefreshed){i?Zt(I.body).catch(()=>{}):(await Zt(I.body),this._workloadIdentityAuth?.invalidateToken());let Z={...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(Z,i?r-1:r,n??f)}let M=j&&o.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(I);if(r&&M&&!m){let Z=`retrying, ${r} attempts remaining`;return i?Zt(I.body).catch(()=>{}):await Zt(I.body),he(this).info(`${D} - ${Z}`),he(this).debug(`[${f}] response error (${Z})`,Xt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,durationMs:R-b})),this.retryRequest(o,r,n??f,I.headers,l.signal)}let C=M?m?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";he(this).info(`${D} - ${C}`);let L=i?await this.readX509ResponseError(I,o,d,O,i):await I.text().catch(Z=>Fi(Z).message),z=$m(L),V=z?void 0:L;throw he(this).debug(`[${f}] response error (${C})`,Xt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,message:V,durationMs:Date.now()-b})),this.makeStatusError(I.status,z,V,I.headers)}he(this).info(D),he(this).debug(`[${f}] response start`,Xt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,durationMs:R-b}));let $=i?.continuation();return i?.releaseRequestCredentials(),u(this,Ra,"f").set(O,{timeout:d,retriesRemaining:r,hasStreamingBody:m,...i?{authentication:i}:{},helperMethod:o.__metadata?.helperMethod,...$?{continueRequest:$}:{}}),{response:I,options:o,controller:O,requestSignal:l.signal,requestLogID:f,retryOfRequestLogID:n,startTime:b}}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=u(this,se,"f")??this._workloadIdentityAuth,o=n instanceof je?Promise.resolve(r).then(a=>n.runRequest(()=>this.makeRequest(a,null,void 0),this)):this.makeRequest(r,null,void 0),s=new Zi(this,o,e),i=this.responsePromise(o,async(a,l)=>{let c=await this.parseResponseWithTimeout(a,l);return new e(a,l.response,c,l.options)});return s.then=i.then.bind(i),s.catch=i.catch.bind(i),s.finally=i.finally.bind(i),s.withResponse=i.withResponse.bind(i),s._thenUnwrap=i._thenUnwrap.bind(i),s}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!u(this,ur,"f")&&s.bearerAuth){let l=r.headers;if(l.get("Authorization")===`Bearer ${_T}`){let d=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${d}`)}}return await(u(this,ur,"f")?St.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:i,...a}=r||{},l=this._makeAbort(o),c=!!s&&Ay.get(o)===s,d=s&&!c?Lm(s,l,o.signal):void 0,m=setTimeout(l,n),f=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,g={signal:o.signal,...f?{duplex:"half"}:{},method:"GET",...a};i&&(g.method=i.toUpperCase());try{let b=await(u(this,ur,"f")??this.fetch).call(void 0,e,g);return d&&ed(b.body??b,l,o.signal),b}catch(b){throw d?.(),b}finally{clearTimeout(m)}}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,s=e.signal){let i,a=o?.get("retry-after-ms");if(a){let d=parseFloat(a);Number.isNaN(d)||(i=d)}let l=o?.get("retry-after");if(l&&i===void 0){let d=parseFloat(l);Number.isNaN(d)?i=Date.parse(l)-Date.now():i=d*1e3}if(i===void 0||!Number.isFinite(i)||i<0||i>60*1e3){let d=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(r,d)}let c=u(this,se,"f");if(c){let d=c.remainingTimeout(e,c.requestSnapshot().timeout);if(i>=d)throw new ce}if(c)await c.waitForRetry(i,c.effectiveSignal());else{let d=s===e.signal?[s]:[s,e.signal];try{await $o(i,...d)}catch(m){let f=d.find(g=>g?.aborted);throw f?this._makeUserAbortError(f):m}}return 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}={}){if(u(this,se,"f")&&!u(this,se,"f").inRequest(this)){let R=u(this,se,"f");return await R.runRequest(async()=>{let k=await St.prototype.buildRequest.call(this,e,{retryCount:r});return R.releaseRequestBody(k.req.body),k},this)}let n={...e},o=u(this,se,"f"),s=o?.snapshotTenant(this.organization,this.project),i=o?.snapshotHeaders(this._options.defaultHeaders,n.headers);i&&(n.headers=i.requestHeaders);let a=o?wd(this.fetchOptions):void 0,l=o?wd(n.fetchOptions):void 0,{method:c,path:d,query:m,defaultBaseURL:f}=n,g=this.buildURL(d,m,f);o?.snapshotAPIURL(g);let b="timeout"in n;if(b&&Yu("timeout",n.timeout),n.timeout=n.timeout??this.timeout,o&&l&&o.snapshotRequest(n.signal,n.timeout,l),o){let R=o.requestSnapshot();n.timeout=R.timeout,R.signal===void 0?delete n.signal:n.signal=R.signal}let _=this._provider||o?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:x,body:O,isStreamingBody:y}=this.buildBody({options:n});y&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},o?.ownRequestBody(O,n.body));let S=await this.buildHeaders({options:e,method:c,bodyHeaders:x,authenticationHeaders:_,retryCount:r,x509Headers:i,x509Timeout:b?n.timeout:void 0,x509Tenant:s});return{req:{method:c,headers:S,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&O instanceof globalThis.ReadableStream&&{duplex:"half"},...O&&{body:O},...(o?a:this.fetchOptions)??{},...(o?l:n.fetchOptions)??{}},url:g,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,authenticationHeaders:o,retryCount:s,x509Headers:i,x509Timeout:a,x509Tenant:l}){let c={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),c[this.idempotencyHeader]=e.idempotencyKey);let d=e.__metadata?.helperMethod,m=i?a:e.timeout,f=v([c,{Accept:"application/json",...yy()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(s),...m?{"X-Stainless-Timeout":String(Math.trunc(m/1e3))}:{},...Xm(),...typeof d=="string"?{"X-Stainless-Helper-Method":d}:{},"OpenAI-Organization":l?l.organization:this.organization,"OpenAI-Project":l?l.project:this.project},u(this,se,"f")&&!u(this,se,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):o,i?.defaultHeaders??this._options.defaultHeaders,n,i?.requestHeaders??e.headers]);return!this._provider&&!u(this,se,"f")?.isPlanningRequest()&&this.validateHeaders(f,e.__security??{bearerAuth:!0}),f.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let r=new ie;return Object.defineProperty(r,"cause",{value:e.reason,writable:!0,configurable:!0}),r}buildBody({options:e}){let{body:r,headers:n}=e;if(!r)return r===void 0&&"body"in e?{...u(this,Pa,"f").call(this,{body:r,headers:v([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=v([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:qi(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}:{...u(this,Pa,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};St=F,Pa=new WeakMap,se=new WeakMap,xc=new WeakMap,ur=new WeakMap,Ma=new WeakMap,Ra=new WeakMap,Sp=new WeakSet,by=function(){return u(this,Ma,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};F.OpenAI=St;F.DEFAULT_TIMEOUT=6e5;F.OpenAIError=A;F.APIError=ee;F.APIConnectionError=st;F.APIConnectionTimeoutError=ce;F.APIUserAbortError=ie;F.NotFoundError=Er;F.ConflictError=Or;F.RateLimitError=Cr;F.BadRequestError=Nt;F.AuthenticationError=Sr;F.InternalServerError=Pr;F.PermissionDeniedError=Tr;F.UnprocessableEntityError=kr;F.InvalidWebhookSignatureError=Ge;F.toFile=ta;F.toStreamingFile=$l;F.Completions=Xn;F.Chat=zr;F.Embeddings=eo;F.Files=ro;F.Images=io;F.ContentProvenanceChecks=Yn;F.Audio=Ut;F.Moderations=lo;F.Models=ao;F.FineTuning=It;F.Graders=nn;F.VectorStores=cr;F.Safety=ln;F.Webhooks=fo;F.Beta=tt;F.Batches=Un;F.Uploads=cn;F.Admin=Ur;F.Responses=Wt;F.Live=qt;F.Realtime=ar;F.Conversations=tn;F.Evals=rn;F.Containers=en;F.Skills=lr;F.Videos=po;F.ConversationCursorPage=J;F.CursorPage=P;F.NextCursorPage=ue;F.Page=Ee;F.TokenPage=Lo;var Ay=new WeakMap;function wy(t,e){let r=new AbortController;if(!t)return r;let n=globalThis.AbortSignal;if(typeof n?.any!="function"||!(t instanceof n))return r;try{let o=[r.signal,t];e&&e!==t&&o.push(e);let s=n.any(o);Object.defineProperty(r,"signal",{value:s,configurable:!0}),Ay.set(r,t)}catch{}return r}function wT(t){if(bT(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 bT(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}var xy=Symbol.for("openai.privateBedrockClient");var xT;xT=xy;function vT(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 ht(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===ce.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError",gn(e,!0)):t.constructor.name===ie.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",gn(e,!1)):vT(t)?e=Wf.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=gn(Di(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=gn(Di(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=gn(Di(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=gn(Di(t,"MODEL_NOT_FOUND"),!1):e=t,e}var Tt=t=>t();function dr(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function IT(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 vc(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var ST="LC_AUTOGENERATED";function mo(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'."),ST)}function pr(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(!el.isInstance(t))throw new Error("Invalid generic chat message");return IT(t);default:throw new Error(`Unknown message type: ${e}`)}}function vy(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("gpt-5.6-sol")||t.includes("codex"))}function fr(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 Ep(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Iy(t){let e=Tt(()=>{if(Ep(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ep(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 Sy(){let t=Uf();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function mr(t,e=!1,r="1.0.0"){let n=Iy(t),o=Sy(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function Ty(t,e){let r;return Po(t)?r=Mu(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function TT(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ey(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(Oy(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
68
+ `)}function Oy(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}: ${Ic(o,e)},`):r.push(`${n}?: ${Ic(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
69
+ `)}function Ic(t,e){if(TT(t))return t.anyOf.map(r=>Ic(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["{",Oy(t,e+2),"}"].join(`
70
+ `);case"array":return t.items?`${Ic(t.items,e)}[]`:"any[]";default:return""}}function Sc(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 mi(t){return"type"in t&&t.type!=="function"}function ky(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 Cy(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function ho(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 Tc(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Py(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 Ry(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 My(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function $y(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 Ny(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 Ly(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()}}}function jy(){return{}}function Op(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function X(t,e,r,n,o){t[e]=r,Op(t,e,n,o)}function Dy(t,e){let r={type:"array"};return(t.type?._def?.typeName!==K.ZodAny||e.openaiStrictMode)&&(r.items=U(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&X(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&X(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(X(r,"minItems",t.exactLength.value,t.exactLength.message,e),X(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Fy(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?X(r,"minimum",n.value,n.message,e):X(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),X(r,"minimum",n.value,n.message,e));break}case"max":{e.target==="jsonSchema7"?n.inclusive?X(r,"maximum",n.value,n.message,e):X(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),X(r,"maximum",n.value,n.message,e));break}case"multipleOf":{X(r,"multipleOf",n.value,n.message,e);break}}return r}function zy(){return{type:"boolean"}}function By(t,e,r){return U(t.type._def,e,r)}var Uy=(t,e,r)=>U(t.innerType._def,e,r);function kp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>kp(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 ET(t,e)}}var ET=(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":{X(r,"minimum",n.value,n.message,e);break}case"max":{X(r,"maximum",n.value,n.message,e);break}}return r};function qy(t,e,r){return{...U(t.innerType._def,e,r),default:t.defaultValue()}}function Wy(t,e,r){return e.effectStrategy==="input"?U(t.schema._def,e,r):{}}function Ky(t){return{type:"string",enum:[...t.values]}}var OT=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Hy(t,e){let r=[U(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),U(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];for(let s of r)if(OT(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,...l}=s;i=l}else n=void 0;o.push(i)}return o.length?{allOf:o,...n}:void 0}function Ec(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function Vy(t,e){if(t.value===null)return e.target==="openApi3"?Ec(e):{type:"null",const:null};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 Cp,go={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:()=>{if(Cp===void 0){let t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Cp=new RegExp(t,"u")}return Cp},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 Oc(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?kT(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":{X(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break}case"max":{X(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":{Et(r,"email",o.message,e);break}case"format:idn-email":{Et(r,"idn-email",o.message,e);break}case"pattern:zod":{Ot(r,go.email,o.message,e);break}}break}case"url":{Et(r,"uri",o.message,e);break}case"uuid":{Et(r,"uuid",o.message,e);break}case"regex":{Ot(r,o.regex,o.message,e);break}case"cuid":{Ot(r,go.cuid,o.message,e);break}case"cuid2":{Ot(r,go.cuid2,o.message,e);break}case"startsWith":{Ot(r,new RegExp(`^${n(o.value)}`),o.message,e);break}case"endsWith":{Ot(r,new RegExp(`${n(o.value)}$`),o.message,e);break}case"datetime":{Et(r,"date-time",o.message,e);break}case"date":{Et(r,"date",o.message,e);break}case"time":{Et(r,"time",o.message,e);break}case"duration":{Et(r,"duration",o.message,e);break}case"length":{X(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),X(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break}case"includes":{Ot(r,new RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Et(r,"ipv4",o.message,e),o.version!=="v4"&&Et(r,"ipv6",o.message,e);break}case"emoji":{Ot(r,go.emoji,o.message,e);break}case"ulid":{Ot(r,go.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Et(r,"binary",o.message,e);break}case"contentEncoding:base64":{X(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Ot(r,go.base64,o.message,e);break}}break}case"nanoid":{Ot(r,go.nanoid,o.message,e);break}case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var kT=t=>[...t].map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Et=(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}}})):X(t,"format",e,r,n)},Ot=(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:Gy(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):X(t,"pattern",Gy(e,n),r,n)},Gy=(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,l=!1;for(let c=0;c<o.length;c++){if(i){s+=o[c],i=!1;continue}if(n.i){if(a){if(/[a-z]/.test(o[c])){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&o[c+2]?.match(/[a-z]/)?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(/[a-z]/.test(o[c])){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
71
+ ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
72
+ ]))`;continue}}if(n.s&&o[c]==="."){s+=a?`${o[c]}\r
73
+ `:`[${o[c]}\r
74
+ ]`;continue}s+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{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 kc(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===K.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:Object.fromEntries(t.keyType._def.values.map(n=>[n,U(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}])),additionalProperties:!1};let r={type:"object",additionalProperties:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===K.ZodString&&t.keyType._def.checks?.length){let n=Object.fromEntries(Object.entries(Oc(t.keyType._def,e)).filter(([o])=>o!=="type"));return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===K.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function Jy(t,e){if(e.mapStrategy==="record")return kc(t,e);let r=U(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=U(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 Zy(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=[...new Set(n.map(i=>typeof i))],s=["string","number"];return o.length===1&&(s=o[0]==="string"?"string":"number"),{type:s,enum:n}}function Xy(){return{not:{}}}var $a={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yy(t,e){if(e.target==="openApi3")return Qy(t,e);let r=t.options instanceof Map?[...t.options.values()]:t.options;if(r.every(n=>n._def.typeName in $a&&(!n._def.checks||!n._def.checks.length))){let n=[];for(let o of r){let s=$a[o._def.typeName];s&&!n.includes(s)&&n.push(s)}return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=[];for(let o of r){let s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":{n.push(s);break}case"bigint":{n.push("integer");break}case"object":{o._def.value===null&&n.push("null");break}}}if(n.length===r.length){let o=n.filter((i,a,l)=>l.indexOf(i)===a),s=[];for(let i of r)s.includes(i._def.value)||s.push(i._def.value);return{type:o.length>1?o:o[0],enum:s}}}else if(r.every(n=>n._def.typeName==="ZodEnum")){let n=[];for(let o of r)for(let s of o._def.values)n.includes(s)||n.push(s);return{type:"string",enum:n}}return Qy(t,e)}var Qy=(t,e)=>{let r=(t.options instanceof Map?[...t.options.values()]:t.options).map((n,o)=>U(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 e_(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:$a[t.innerType._def.typeName],nullable:!0}:{type:[$a[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=U(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function t_(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",Op(r,"type",n.message,e);break}case"min":{e.target==="jsonSchema7"?n.inclusive?X(r,"minimum",n.value,n.message,e):X(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),X(r,"minimum",n.value,n.message,e));break}case"max":{e.target==="jsonSchema7"?n.inclusive?X(r,"maximum",n.value,n.message,e):X(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),X(r,"maximum",n.value,n.message,e));break}case"multipleOf":{X(r,"multipleOf",n.value,n.message,e);break}}return r}function CT(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":U(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":U(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function r_(t,e){let r={},n=[];for(let[s,i]of Object.entries(t.shape())){if(i===void 0||i._def===void 0)continue;let a=[...e.currentPath,"properties",s];if(s==="__proto__")throw new Error(`Zod field at \`${a.join("/")}\` uses unsupported property name \`__proto__\`, which Zod omits from parsed output.`);let l=U(i._def,{...e,currentPath:a,propertyPath:a});if(l!==void 0){if(e.openaiStrictMode&&i.isOptional()&&!i.isNullable()&&i._def?.defaultValue===void 0)throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);r[s]=l,(!i.isOptional()||e.openaiStrictMode)&&n.push(s)}}let o={type:"object",properties:r,required:n,additionalProperties:CT(t,e)};return o.required.length||delete o.required,o}var n_=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return U(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=e.openaiStrictMode&&!e.override,o=U(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf",n?"0":"1"]},r);return o?{anyOf:n?[o]:[{not:{}},o]}:{}};var o_=(t,e,r)=>{if(e.pipeStrategy==="input")return U(t.in._def,e,r);if(e.pipeStrategy==="output")return U(t.out._def,e,r);let n=U(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=U(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function s_(t,e,r){return U(t.type._def,e,r)}function i_(t,e){let n={type:"array",uniqueItems:!0,items:U(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&X(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&X(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function a_(t,e){return t.map((r,n)=>U(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})??{})}function l_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:a_(t.items,e),additionalItems:U(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:a_(t.items,e)}}function c_(){return{not:{}}}function u_(){return{}}var d_=(t,e,r)=>U(t.innerType._def,e,r);var f_=Symbol("Let zodToJsonSchema decide on which parser to use"),p_={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"},m_=t=>{let e=typeof t=="string"?{...p_,basePath:["#"],definitions:{},name:t}:{...p_,basePath:["#"],definitions:{},...t};return typeof t!="string"&&t?.definitions&&e.$refStrategy==="extract-to-root"&&e.nameStrategy==="duplicate-ref"&&(e.definitions={...t.definitions}),e};var yo=t=>"_def"in t?t._def:t;function h_(t){if(!t)return!0;for(let e in t)return!1;return!0}function U(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==f_)return s}if(n&&!r){let s=PT(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=$T(t,t.typeName,e,r);return s&&NT(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var PT=(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((s,i)=>i===0?s:RT(s)).join("_"),n=r;if(!(n===e.name&&t.path.length===e.basePath.length+2&&t.path[e.basePath.length]===e.definitionPath)&&e.nameStrategy==="duplicate-ref"){let s=a=>{if(!N(e.definitions,a))return!1;let l=e.definitions[a];return l===void 0||yo(l)!==t.def},i=0;for(;n===e.name||s(n);)i+=1,n=`${r}_${i}`;N(e.definitions,n)||(e.definitions[n]=t.def)}return{$ref:[...e.basePath,e.definitionPath,n].join("/")}}case"relative":return{$ref:MT(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},g_="_x_",RT=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(g_))return t;let e=g_;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},MT=(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("/")},$T=(t,e,r,n)=>{switch(e){case K.ZodString:return Oc(t,r);case K.ZodNumber:return t_(t,r);case K.ZodObject:return r_(t,r);case K.ZodBigInt:return Fy(t,r);case K.ZodBoolean:return zy();case K.ZodDate:return kp(t,r);case K.ZodUndefined:return c_();case K.ZodNull:return Ec(r);case K.ZodArray:return Dy(t,r);case K.ZodUnion:case K.ZodDiscriminatedUnion:return Yy(t,r);case K.ZodIntersection:return Hy(t,r);case K.ZodTuple:return l_(t,r);case K.ZodRecord:return kc(t,r);case K.ZodLiteral:return Vy(t,r);case K.ZodEnum:return Ky(t);case K.ZodNativeEnum:return Zy(t);case K.ZodNullable:return e_(t,r,n);case K.ZodOptional:return n_(t,r,n);case K.ZodMap:return Jy(t,r);case K.ZodSet:return i_(t,r);case K.ZodLazy:return U(t.getter()._def,r,n);case K.ZodPromise:return s_(t,r,n);case K.ZodNaN:case K.ZodNever:return Xy();case K.ZodEffects:return Wy(t,r,n);case K.ZodAny:return jy();case K.ZodUnknown:return u_();case K.ZodDefault:return qy(t,r,n);case K.ZodBranded:return By(t,r,n);case K.ZodReadonly:return d_(t,r,n);case K.ZodCatch:return Uy(t,r,n);case K.ZodPipeline:return o_(t,r,n);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return(o=>{})(e)}},NT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var y_=t=>{let e=m_(t),r=e.name===void 0?e.basePath:[...e.basePath,e.definitionPath,e.name];return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[yo(o),{def:yo(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function LT(t,e,r){if(t===null||typeof t!="object")throw new TypeError("Root schema must be a plain JSON-schema record");let n=Object.getPrototypeOf(t);if(![null,Object.prototype].includes(n))throw new TypeError("Root schema must be a plain JSON-schema record");let o={};for(let[l,c]of Object.entries(Object.getOwnPropertyDescriptors(t))){if(!c.enumerable)continue;if(!("value"in c))throw new TypeError(`Root schema property '${l}' must be a data property`);let d=c.value;if(l==="toJSON"&&typeof d=="function")throw new TypeError("Root schema cannot contain a callable 'toJSON' property");["undefined","function","symbol"].includes(typeof d)||Object.defineProperty(o,l,{configurable:!0,enumerable:!0,value:d,writable:!0})}let{type:s,nullable:i,$ref:a}=o;if(!["undefined","boolean"].includes(typeof i))throw new TypeError("Root schema 'nullable' must be a boolean");if(s!=="object"||i===!0){let l;throw typeof s=="string"?l=i===!0?`${s},null`:s:Array.isArray(s)&&(l=s.join(",")),new Error(`Root schema must have type: 'object' but got type: ${l?`'${l}'`:"undefined"}`)}if(a!==void 0)throw new Error("Root schema must be a concrete object and cannot contain '$ref'");if(e!==void 0&&r!=="duplicate-ref")throw new Error("Root schema must have type: 'object' but got type: undefined");return o}var Pp=(t,e)=>{let r=y_(e);r.openaiStrictMode&&(r.definitions={...r.definitions});let n;typeof e=="string"?n=e:e?.nameStrategy!=="title"&&(n=e?.name);let o=U(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},r.openaiStrictMode===!0)??{},s=r.openaiStrictMode?LT(o,n,r.nameStrategy):o,i=r.nameStrategy==="title"?r.name:void 0;i!==void 0&&(s.title=i);let a=(()=>{if(h_(r.definitions))return;let c={},d=new Set;for(let m=0;m<500;m++){let f=Object.entries(r.definitions).filter(([g])=>!d.has(g));if(f.length===0)break;for(let[g,b]of f)Object.defineProperty(c,g,{value:U(yo(b),{...r,currentPath:[...r.basePath,r.definitionPath,g]},!0)??{},enumerable:!0,configurable:!0,writable:!0}),d.add(g)}return c})(),l;return n===void 0?l=a?{...s,[r.definitionPath]:a}:s:r.nameStrategy==="duplicate-ref"?l={...s,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:s}:void 0}}:void 0}:l={$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:s}},r.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),l};var kt=new Set(["$comment","default","description","examples","readOnly","title","writeOnly"]),wo=new Set(["$id","$schema"]),Np=new Set(["additionalProperties","dependencies","maxProperties","minProperties","patternProperties","properties","propertyNames","required"]),b_=["additionalItems","additionalProperties","contains","contentSchema","else","if","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"],A_=["allOf","anyOf","items","oneOf","prefixItems"],x_=["$defs","definitions","dependentSchemas","dependencies","patternProperties","properties"],jT=new Set(["$anchor","$dynamicAnchor","$dynamicRef","$recursiveAnchor","$recursiveRef","allOf","contains","contentEncoding","contentMediaType","contentSchema","dependentRequired","dependentSchemas","dependencies","else","if","maxContains","maxProperties","minContains","minProperties","not","oneOf","patternProperties","prefixItems","propertyNames","then","unevaluatedItems","unevaluatedProperties","uniqueItems"]),__=new Set([...kt,"additionalProperties","properties","required","type"]);function hi(t,...e){for(let r of e)Object.prototype.propertyIsEnumerable.call(r,"__proto__")&&!N(t,"__proto__")&&Object.defineProperty(t,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(t,r);return t}function Ye(t,e,r){let n=t;for(let o of b_)o in n&&r(n[o],[...e,o],o);for(let o of A_){let s=n[o];if(Array.isArray(s))for(let[i,a]of s.entries())r(a,[...e,o,String(i)],o);else s!==void 0&&r(s,[...e,o],o)}for(let o of x_){let s=n[o];if(G(s))for(let[i,a]of Object.entries(s))o==="dependencies"&&!gi(a)||r(a,[...e,o,i],o)}}function v_(t){let e=structuredClone(t);if(I_(e),S_(e),XT(e),DT(e),e.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:"undefined"}`);if(e.anyOf!==void 0)throw new Error("Root schema must not use `anyOf` because strict Structured Outputs requires a root object without a union.");Pc(e,[],e),O_(e),Pc(e,[],e),YT(e),Mc(e,[],e);let r=Cc(e,[],e);return Pc(r,[],r),r}function I_(t,e=new Set){if(!G(t)||e.has(t))return;e.add(t);let r=t;for(let n of Object.keys(r))r[n]===void 0&&delete r[n];Ye(t,[],n=>{I_(n,e)})}function DT(t){let e=new Set;for(;;){if(typeof t.$ref=="string"){if(e.has(t.$ref))throw new Error("Cyclic local $ref at `<root>` is not supported: "+JSON.stringify(t.$ref));e.add(t.$ref)}FT(t),O_(t,!0),zT(t);let r=BT(t);if(t.$ref===void 0&&!r)return}}function FT(t){let e=t.$ref;if(e===void 0)return;if(w_(e),!WT(t))throw new Error("Schema $ref at `<root>` has non-metadata siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.");let r=new Set,n=Object.fromEntries(Object.entries(t).filter(([d])=>kt.has(d))),o;for(;;){if(r.has(e))throw new Error("Cyclic local $ref at `<root>` is not supported: "+JSON.stringify(e));r.add(e);let d=un(t,e);if(d===void 0)throw new Error("Local $ref at `<root>` does not resolve to an object or boolean schema: "+JSON.stringify(e));if(typeof d=="boolean")throw new TypeError("Expected object schema but got boolean; path=<root>");let m=d.$ref;if(m===void 0){o=d;break}if(w_(m),r.has(m))throw new Error("Cyclic local $ref at `<root>` is not supported: "+JSON.stringify(m));if(!yi(d))throw new Error("Schema $ref in root chain has non-annotation siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.");for(let f of kt)!(f in n)&&f in d&&(n[f]=d[f]);e=m}let s=t.$defs,i=t.definitions,a=Object.fromEntries(Object.entries(t).filter(([d])=>kt.has(d)||wo.has(d))),l=structuredClone(o);for(let d of["$defs","definitions"])t[d]!==void 0&&l[d]!==void 0&&delete l[d];let c=t;for(let d of Object.keys(t))delete c[d];hi(t,l,n,a),s!==void 0&&(t.$defs=s),i!==void 0&&(t.definitions=i)}function zT(t){for(;t.allOf!==void 0;){if(Array.isArray(t.allOf))for(let[i,a]of t.allOf.entries())Mc(a,["allOf",String(i)],t);if(Dp(t,[],t))continue;let e=t.allOf;if(!Array.isArray(e)||e.length!==1||!KT(t))return;let r=e[0];if(!G(r))return;let n={...t};delete n.allOf;let o=structuredClone(r),s=t;for(let i of Object.keys(t))delete s[i];hi(t,o,n)}}function BT(t){let e=t.anyOf;if(!Array.isArray(e)||!HT(t))return!1;let r=e.map((c,d)=>({branch:c,index:d})).filter(({branch:c})=>c!==!1);if(r.length!==1)return!1;let{branch:n,index:o}=r[0];if(!G(n)||!Rc(n,t))return!1;let s=UT(t,n);qT(t,o,s);let i={...t};delete i.anyOf;let a=structuredClone(n);for(let c of["$defs","definitions"]){let d=t[c],m=a[c];if(!G(d)||!G(m))continue;let f=s.get(c),g={...d};for(let[b,_]of Object.entries(m))Object.defineProperty(g,f?.get(b)??b,{value:_,writable:!0,enumerable:!0,configurable:!0});a[c]=g,delete i[c]}let l=t;for(let c of Object.keys(t))delete l[c];return hi(t,a,i),!0}function UT(t,e){let r=new Map;for(let n of["$defs","definitions"]){let o=t[n],s=e[n];if(!G(o)||!G(s))continue;let i=new Set([...Object.keys(o),...Object.keys(s)]),a=new Map,l=0;for(let[c,d]of Object.entries(s)){if(!N(o,c)||La(o[c],d))continue;let m="__openai_strict_anyOf_definition_"+l++;for(;i.has(m);)m="__openai_strict_anyOf_definition_"+l++;i.add(m),a.set(c,m)}a.size>0&&r.set(n,a)}return r}function qT(t,e,r){let n=s=>{let i=bo(s);if(i===void 0||i[0]!=="anyOf"||i[1]!==String(e))return s;let a=i.slice(2),l=a[0];if(a.length>1&&(l==="$defs"||l==="definitions")){let c=r.get(l)?.get(a[1]);c!==void 0&&(a[1]=c)}return a.length===0?"#":"#/"+a.map(E_).join("/")},o=s=>{G(s)&&(typeof s.$ref=="string"&&(s.$ref=n(s.$ref)),Ye(s,[],i=>{o(i)}))};o(t)}function w_(t){if(typeof t!="string")throw new TypeError("Received non-string $ref - "+String(t)+"; path=<root>");if(!t.startsWith("#"))throw new Error("External $ref at `<root>` is not supported in strict Structured Outputs: "+JSON.stringify(t))}function WT(t){return Object.keys(t).every(e=>e==="$ref"||e==="$defs"||e==="definitions"||wo.has(e)||kt.has(e))}function S_(t){G(t)&&(Array.isArray(t.type)&&t.type.length===1&&(t.type=t.type[0]),Ye(t,[],e=>{S_(e)}))}function Na(t,e,r=new Set){if(typeof t=="boolean")return t;let n=t.$ref;if(n!==void 0){if(typeof n!="string"||!yi(t)||r.has(n))return!1;let o=un(e,n);return o===void 0?!1:Na(o,e,new Set([...r,n]))}return!(t.type!==void 0&&t.type!=="null"&&!(Array.isArray(t.type)&&t.type.includes("null"))||"const"in t&&t.const!==null||t.enum!==void 0&&(!Array.isArray(t.enum)||!t.enum.includes(null))||t.allOf!==void 0&&(!Array.isArray(t.allOf)||!t.allOf.every(o=>Na(o,e)))||t.anyOf!==void 0&&(!Array.isArray(t.anyOf)||!t.anyOf.some(o=>Na(o,e)))||t.oneOf!==void 0&&(!Array.isArray(t.oneOf)||t.oneOf.filter(o=>Na(o,e)).length!==1)||t.not!==void 0||t.if!==void 0||t.then!==void 0||t.else!==void 0)}function Cc(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!G(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);if(Dp(t,e,r))return Cc(t,e,r);if(ZT(t),GT(t,e,r),$p(t)){if(!N(t,"additionalProperties"))t.additionalProperties=!1;else if(t.additionalProperties!==!1)throw new Error(`Object schema at \`${e.join("/")||"<root>"}\` must set \`additionalProperties: false\` to be compatible with strict Structured Outputs.`)}let n=t.required??[];if(!Array.isArray(n)||n.some(m=>typeof m!="string"))throw new TypeError(`Expected \`required\` to be an array of strings; path=${e.join("/")||"<root>"}`);let o=t.properties;if($p(t)){for(let m of n)if(!G(o)||!N(o,m))throw new Error(`Object schema at \`${e.join("/")||"<root>"}\` requires property \`${m}\` but does not declare it in \`properties\`.`)}if(G(o)){for(let[m,f]of Object.entries(o))if(!Na(f,r)&&!n.includes(m))throw new Error(`Schema field at \`${[...e,"properties",m].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(o)}let s=t.items,i=t.additionalItems;if(Array.isArray(s))throw new TypeError(`Schema at \`${e.join("/")||"<root>"}\` uses tuple-form \`items\`, which cannot be represented in strict Structured Outputs.`);if(i!==void 0)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses unsupported keyword \`additionalItems\` and cannot be represented in strict Structured Outputs.`);let a=t.allOf;if(Array.isArray(a)&&a.length===1&&Lp(t,"allOf")){let m=a[0];if(m===!1)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses \`allOf: [false]\`, which cannot be represented in strict Structured Outputs.`);if(m===!0)delete t.allOf;else{let f=Cc(m,[...e,"allOf","0"],r),g={...t};delete g.allOf,hi(t,f,g),delete t.allOf}}JT(t,r);let l=t;for(let m of jT){if(l[m]!==void 0)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses unsupported keyword \`${m}\` and cannot be represented in strict Structured Outputs.`);delete l[m]}let c=t.type,d=t.items;if((c==="array"||Array.isArray(c)&&c.includes("array"))&&d===void 0)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` declares an array without \`items\`, which cannot be represented in strict Structured Outputs.`);return Ye(t,e,(m,f,g)=>{typeof m=="boolean"&&(g==="additionalProperties"||g==="additionalItems")||Cc(m,f,r)}),t.default===null&&delete t.default,t}function bo(t){if(!t.startsWith("#"))return;let e;try{e=decodeURIComponent(t.slice(1))}catch{return}if(e==="")return[];if(!e.startsWith("/"))return;let r=[];for(let n of e.slice(1).split("/")){if(/~(?:[^01]|$)/.test(n))return;r.push(n.replace(/~1/g,"/").replace(/~0/g,"~"))}return r}function _o(t,e){if(Array.isArray(t)){if(!/^(?:0|[1-9]\d*)$/.test(e))return;let r=Number(e);return N(t,r)?t[r]:void 0}if(!(!G(t)||!N(t,e)))return t[e]}function un(t,e){let r=bo(e);if(r===void 0)return;let n=t;for(let o=0;o<r.length;){if(!G(n))return;let s=r[o];if(b_.includes(s)){n=_o(n,s),o+=1;continue}if(A_.includes(s)){if(n=_o(n,s),o+=1,Array.isArray(n)){if(o>=r.length)return;n=_o(n,r[o]),o+=1}continue}if(x_.includes(s)){let i=_o(n,s);if(o+=1,!G(i)||o>=r.length||(n=_o(i,r[o]),s==="dependencies"&&!gi(n)))return;o+=1;continue}return}return gi(n)?n:void 0}function G(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gi(t){return typeof t=="boolean"||G(t)}function Rc(t,e,r=new Set){if(!G(t))return!1;if(t.$ref!==void 0){if(typeof t.$ref!="string"||!yi(t)||r.has(t.$ref))return!1;let n=un(e,t.$ref);return n===void 0?!1:Rc(n,e,new Set([...r,t.$ref]))}if(t.allOf!==void 0){if(!Array.isArray(t.allOf)||t.allOf.length!==1||!Lp(t,"allOf"))return!1;let n=t.allOf[0];return n!==void 0&&n!==!0&&n!==!1?Rc(n,e,r):!1}return t.type==="object"||Array.isArray(t.type)&&t.type.length===1&&t.type[0]==="object"}function Mp(t,e,r=new Set){if(!G(t))return!1;if(t.$ref!==void 0){if(typeof t.$ref!="string"||!yi(t)||r.has(t.$ref))return!1;let n=un(e,t.$ref);return n===void 0?!1:Mp(n,e,new Set([...r,t.$ref]))}if(t.allOf!==void 0){if(!Array.isArray(t.allOf)||t.allOf.length!==1||!Lp(t,"allOf"))return!1;let n=t.allOf[0];return n!==void 0&&n!==!0&&n!==!1?Mp(n,e,r):!1}return t.type==="array"||Array.isArray(t.type)&&t.type.length===1&&t.type[0]==="array"}function yi(t){return Object.keys(t).every(e=>e==="$ref"||e==="$defs"||e==="definitions"||kt.has(e))}function Lp(t,e){let r=t;return Object.keys(t).every(n=>n===e||(n==="$defs"||n==="definitions")&&G(r[n])||kt.has(n))}function KT(t){return Object.keys(t).every(e=>e==="allOf"||e==="$defs"||e==="definitions"||wo.has(e)||kt.has(e))}function HT(t){return Object.keys(t).every(e=>e==="anyOf"||e==="$defs"||e==="definitions"||e==="type"&&t.type==="object"||wo.has(e)||kt.has(e))}function VT(t){return Object.keys(t).some(e=>Np.has(e))}function $p(t){let e=t.type;return e==="object"||Array.isArray(e)&&e.includes("object")||e===void 0&&VT(t)}function T_(t,e){return t===e||Array.isArray(t)&&t.length===2&&t.includes(e)&&t.includes("null")}function GT(t,e,r){if(t.anyOf===void 0)return;let n=G(t.properties)&&Object.keys(t.properties).length===0,o=Array.isArray(t.required)&&t.required.length===0;if(n&&delete t.properties,o&&delete t.required,!$p(t))return;let s=Object.keys(t).some(i=>Np.has(i));if(T_(t.type,"object")&&!s&&Array.isArray(t.anyOf)&&t.anyOf.every(i=>Rc(i,r))){delete t.type;return}throw new Error("Object anyOf schema at `"+(e.join("/")||"<root>")+"` cannot be represented in strict Structured Outputs without changing Draft 7 validation.")}function JT(t,e){T_(t.type,"array")&&t.items===void 0&&Array.isArray(t.anyOf)&&t.anyOf.every(r=>Mp(r,e))&&delete t.type}function ZT(t){if(!Array.isArray(t.anyOf))return;let e=t.anyOf.filter(r=>r!==!1);e.length>0&&e.length!==t.anyOf.length&&(t.anyOf=e)}function XT(t){let e=(r,n)=>{if(G(r)){if(n.length>0&&r.$id!==void 0)throw new Error("Nested $id at "+JSON.stringify(n.join("/"))+" establishes a separate JSON Schema resource scope and cannot be represented in strict Structured Outputs.");Ye(r,n,(o,s)=>{e(o,s)})}};e(t,[])}function QT(t,e){let r=bo(e);if(r===void 0)return!1;let n=t;for(let[o,s]of r.entries()){if(s==="allOf"&&G(n)&&Array.isArray(n.allOf)&&o<r.length-1)return!0;if(n=_o(n,s),n===void 0)return!1}return!1}function jp(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function E_(t){return encodeURIComponent(jp(t)).replace(/%24/g,"$")}function YT(t){let e=n=>{let o=bo(n);if(o===void 0||o.length===0)return n;let s=[...o],i=t,a=!1;for(let[l,c]of o.entries()){let d=G(i)?i:void 0;if(c==="anyOf"&&l<o.length-1&&d!==void 0&&Array.isArray(d.anyOf)){let m=d.anyOf,f=o[l+1];if(!/^(?:0|[1-9]\d*)$/.test(f))return n;let g=Number(f);if(!N(m,g))return n;let b=m.filter(_=>_!==!1);if(b.length>0&&b.length!==m.length){if(m[g]===!1)return n;let _=m.slice(0,g).filter(x=>x!==!1).length;_!==g&&(s[l+1]=String(_),a=!0)}}if(i=_o(i,c),i===void 0)return n}return a?"#/"+s.map(E_).join("/"):n},r=n=>{G(n)&&(typeof n.$ref=="string"&&(n.$ref=e(n.$ref)),Ye(n,[],o=>{r(o)}))};r(t)}function O_(t,e=!1){let r=new Set,n=l=>{if(G(l)){if(typeof l.$ref=="string"&&QT(t,l.$ref)){let c=bo(l.$ref);(!e||c?.[0]==="allOf")&&r.add(l.$ref)}Ye(l,[],c=>{n(c)})}};if(n(t),r.size===0)return;if(t.$defs!==void 0&&!G(t.$defs))throw new Error("Root schema has invalid $defs and cannot preserve local allOf references.");let o=t.$defs??(t.$defs={}),s=new Map,i=0;for(let l of r){let c=un(t,l);if(!gi(c)){if(e)continue;throw new Error("Local $ref cannot be preserved before allOf flattening: "+JSON.stringify(l))}let d="__openai_strict_allOf_ref_"+i++;for(;N(o,d);)d="__openai_strict_allOf_ref_"+i++;o[d]=structuredClone(c),s.set(l,"#/$defs/"+jp(d))}let a=l=>{G(l)&&(typeof l.$ref=="string"&&(l.$ref=s.get(l.$ref)??l.$ref),Ye(l,[],c=>{a(c)}))};a(t)}function eE(t,e){if(e.length===0)return;let r=new Set,n=l=>{if(G(l)){if(typeof l.$ref=="string"){let c=bo(l.$ref);c!==void 0&&e.some(d=>c.length>=d.length&&d.every((m,f)=>c[f]===m))&&r.add(l.$ref)}Ye(l,[],c=>{n(c)})}};if(n(t),r.size===0)return;if(t.$defs!==void 0&&!G(t.$defs))throw new Error("Root schema has invalid $defs and cannot preserve discarded allOf properties.");let o=t.$defs??(t.$defs={}),s=new Map,i=0;for(let l of r){let c=un(t,l);if(!gi(c))throw new Error("Local $ref cannot be preserved before allOf property removal: "+JSON.stringify(l));let d="__openai_strict_allOf_property_ref_"+i++;for(;N(o,d);)d="__openai_strict_allOf_property_ref_"+i++;o[d]=structuredClone(c),s.set(l,"#/$defs/"+jp(d))}let a=l=>{G(l)&&(typeof l.$ref=="string"&&(l.$ref=s.get(l.$ref)??l.$ref),Ye(l,[],c=>{a(c)}))};a(t)}function Pc(t,e,r){if(!G(t))return;let n=t.$ref;if(n!==void 0){if(typeof n!="string")throw new TypeError(`Received non-string $ref - ${n}; path=${e.join("/")}`);if(!n.startsWith("#"))throw new Error(`External $ref at \`${e.join("/")||"<root>"}\` is not supported in strict Structured Outputs: ${JSON.stringify(n)}`);let o=un(r,n);if(o===void 0||!gi(o))throw new Error(`Local $ref at \`${e.join("/")||"<root>"}\` does not resolve to an object or boolean schema: ${JSON.stringify(n)}`);if(typeof o=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!yi(t))throw new Error(`Schema $ref at \`${e.join("/")||"<root>"}\` has non-annotation siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.`)}Ye(t,e,(o,s)=>{Pc(o,s,r)})}function tE(t,e,r){let n=[t],o=new Set,s=t,i=[];for(;;){for(;s.$ref!==void 0;){let a=s.$ref;if(typeof a!="string"||!yi(s)||o.has(a))return;o.add(a);let l=un(e,a);if(!G(l))return;let c=bo(a);if(c===void 0)return;s=l,i=c,n.push(s)}if(s.allOf!==void 0&&!r.has(s)){let a=s.allOf;if(Mc(s,i,e,r),s.$ref!==void 0||s.allOf!==a)continue}return{schema:s,refChain:n}}}function Mc(t,e,r,n=new Set){if(G(t)&&!n.has(t)){n.add(t);try{for(;;)if(Ye(t,e,(o,s)=>{Mc(o,s,r,n)}),!Dp(t,e,r,n))return}finally{n.delete(t)}}}function Dp(t,e,r,n=new Set){let o=t.allOf;if(!Array.isArray(o)||o.length===0)return!1;let s=o.filter((C,L)=>!o.slice(0,L).some(z=>La(z,C)));if(s.length!==o.length)return t.allOf=s,!0;let i=o.filter(C=>C!==!0);if(i.length!==o.length)return i.length===0?delete t.allOf:t.allOf=i,!0;let a=Rp(t),l=o.map(C=>G(C)?tE(C,r,n):void 0),c=l.map(C=>C?.schema).filter(C=>C!==void 0&&Rp(C));if(!a&&c.length===0||!a&&o.length===1)return!1;let d=()=>{throw new Error(`Object allOf at \`${e.join("/")||"<root>"}\` cannot be merged without changing Draft 7 validation.`)};!a&&["additionalProperties","properties","required","type"].some(C=>C in t)&&d();for(let C of Object.keys(t))C!=="allOf"&&C!=="$defs"&&C!=="definitions"&&!(e.length===0&&wo.has(C))&&!__.has(C)&&d();let m=[];a&&m.push({schema:t,sourcePath:e});for(let[C,L]of o.entries()){G(L)||d();let z=l[C];if(z===void 0)return d();let V=z.schema;Rp(V)?m.push({schema:V,sourcePath:V===L?[...e,"allOf",String(C)]:void 0}):rE(V)||d()}let f={};for(let C of["$defs","definitions"])t[C]!==void 0&&(f[C]=t[C]);if(e.length===0)for(let C of wo)C in t&&(f[C]=t[C]);let g=Object.create(null),b=new Set,_=[],x=[],O=!1,y=!1,S=!1,I=!1,R=C=>{for(let L of kt)L in C&&(L in f||(f[L]=C[L]))};R(t);for(let C of l)if(C!==void 0)for(let L of C.refChain)R(L);for(let{schema:C,sourcePath:L}of m){for(let z of Object.keys(C))z==="allOf"&&C===t||(z==="$defs"||z==="definitions")&&G(C[z])||C===t&&e.length===0&&wo.has(z)||__.has(z)||d();if(C.type!==void 0&&(k_(C.type)||d(),C.type==="object"?S=!0:I=!0),C.properties!==void 0){G(C.properties)||d(),O=!0;for(let[z,V]of Object.entries(C.properties))x.push({key:z,propertySchema:V,sourcePath:L===void 0?void 0:[...L,"properties",z]})}if(C.required!==void 0){(!Array.isArray(C.required)||C.required.some(z=>typeof z!="string"))&&d(),y=!0;for(let z of C.required)b.add(z)}"additionalProperties"in C&&(C.additionalProperties!==!1&&d(),_.push(new Set(Object.keys(C.properties??{}))))}let k;if(_.length>0){k=new Set(_[0]);for(let C of _.slice(1))for(let L of k)C.has(L)||k.delete(L)}let D=k,$=D!==void 0&&[...b].some(C=>!D.has(C)),j=$&&!S&&I,M=x.filter(({key:C,sourcePath:L})=>L!==void 0&&(j||k!==void 0&&!k.has(C))).map(({sourcePath:C})=>C);if(eE(r,M),t===r&&r.$defs!==void 0&&(f.$defs=r.$defs),$){if(j){f.type="null";for(let C of Object.keys(t))delete t[C];return hi(t,f),!0}d()}for(let{key:C,propertySchema:L}of x)k!==void 0&&!k.has(C)||(N(g,C)&&!La(g[C],L)&&d(),g[C]=L);(S||I)&&(f.type=S?"object":["object","null"]),O&&(f.properties=Object.fromEntries(Object.entries(g))),y&&(f.required=[...b]),_.length>0&&(f.additionalProperties=!1);for(let C of Object.keys(t))delete t[C];return hi(t,f),!0}function Rp(t){return t.type!==void 0?k_(t.type):Object.keys(t).some(e=>Np.has(e))}function rE(t){let e=t;return Object.keys(t).every(r=>kt.has(r)||(r==="$defs"||r==="definitions")&&G(e[r]))}function k_(t){return t==="object"||Array.isArray(t)&&t.length===2&&t.includes("object")&&t.includes("null")}function La(t,e){if(t===e)return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((i,a)=>La(i,e[a]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;let r=t,n=e,o=Object.keys(r),s=Object.keys(n);return o.sort(),s.sort(),o.length!==s.length?!1:o.every((i,a)=>i===s[a]&&La(r[i],n[i]))}var nE={ZodString:"string",ZodNumber:"number",ZodBoolean:"boolean",ZodNull:"null",ZodObject:"object",ZodArray:"array"},oE=new Set(["ZodOptional","ZodNullable","ZodDefault","ZodReadonly"]),sE=new Set(["ZodString","ZodNumber","ZodBoolean","ZodNull","ZodEnum","ZodNativeEnum","ZodAny","ZodUnknown","ZodLiteral"]),iE=new Map([["ZodBigInt","encode integers as decimal strings and convert with BigInt after parsing"],["ZodDate","native dates do not have a synchronous JSON representation"],["ZodMap","native maps do not have a synchronous JSON representation"],["ZodSet","native sets do not have a synchronous JSON representation"],["ZodPromise","asynchronous values do not have a synchronous JSON representation"],["ZodEffects","custom transformations and refinements are opaque to JSON Schema"],["ZodPipeline","custom pipelines are opaque to JSON Schema"],["ZodIntersection","intersections cannot prove that both branches produce the same value"],["ZodCatch","catch fallbacks cannot be proven to produce JSON-native values"],["ZodTuple","tuple schemas require unsupported array-valued items"],["ZodRecord","open-ended record schemas require unsupported additionalProperties"]]),aE=new Set(["trim","toLowerCase","toUpperCase"]),lE=new Set(["regex","cuid","cuid2","startsWith","endsWith","includes","emoji","ulid","nanoid"]);function hr(t,e,r){throw new Error(`Zod schema field \`${t}\` uses \`${e}\`, which cannot be represented by strict Structured Outputs: ${r}`)}function $c(t){if(t===null)return{type:"null",values:new Set([null])};if(typeof t=="string")return{type:"string",values:new Set([t])};if(typeof t=="boolean")return{type:"boolean",values:new Set([t])};if(typeof t=="number"&&Number.isFinite(t))return{type:"number",values:new Set([t])}}function C_(t){let e=t.values;if(!e||Array.isArray(e))return[];let r=e,n=Object.keys(r).filter(o=>{let s=r[o];return(typeof s=="string"||typeof s=="number")&&typeof r[String(s)]!="number"}).map(o=>r[o]).filter(o=>typeof o=="string"||typeof o=="number"&&Number.isFinite(o));return["string","number"].map(o=>({type:o,values:new Set(n.filter(s=>typeof s===o))})).filter(o=>o.values.size>0)}function P_(t){let e=Array.isArray(t.values)?t.values.filter(r=>typeof r=="string"):[];return{type:"string",values:new Set(e)}}function cE(t){if(t.typeName==="ZodLiteral"){let e=$c(t.value);return e?[e]:[]}return t.typeName==="ZodEnum"?[P_(t)]:t.typeName==="ZodNativeEnum"?C_(t):[]}function uE(t){let e=new Map;for(let[r,n]of Object.entries(t.shape())){let o=cE(n._def);o.length>0&&o.every(({values:s})=>s!==void 0&&s.size>0)&&e.set(r,o)}return{type:"object",discriminators:e}}function _i(t,e=new Set){let r=t._def;if(e.has(r))return[{type:"unknown"}];if(e.add(r),r.typeName==="ZodObject")return[uE(r)];let n=nE[r.typeName];if(n!==void 0)return[{type:n}];if(r.typeName==="ZodLiteral"){let o=$c(r.value);return o?[o]:[{type:"unknown"}]}return r.typeName==="ZodEnum"?[P_(r)]:r.typeName==="ZodNativeEnum"?C_(r):r.typeName==="ZodUnion"||r.typeName==="ZodDiscriminatedUnion"?[...r.options.values()].flatMap(o=>_i(o,new Set(e))):r.typeName==="ZodNullable"?[..._i(r.innerType,new Set(e)),{type:"null"}]:oE.has(r.typeName)?_i(r.innerType,e):r.typeName==="ZodBranded"?_i(r.type,e):r.typeName==="ZodLazy"?_i(r.getter(),e):[{type:"unknown"}]}function R_(t,e){if(t.type==="unknown"||e.type==="unknown")return!0;if(t.type!==e.type)return!1;if(t.discriminators&&e.discriminators)for(let[n,o]of t.discriminators){let s=e.discriminators.get(n);if(s&&!o.some(i=>s.some(a=>R_(i,a))))return!1}let r=e.values;return!t.values||!r?!0:[...t.values].some(n=>r.has(n))}function dE(t,e){let r=t.map(n=>_i(n));for(let[n,o]of r.entries())for(let s of r.slice(n+1))o.some(i=>s.some(a=>R_(i,a)))&&hr(e,"ZodUnion","ambiguous union branches overlap; use disjoint JSON types, distinct literals, or a discriminated union")}function pE(t,e){switch(t.typeName){case"ZodObject":{let r=Object.entries(t.shape()).map(([n,o])=>({schema:o,path:`${e}.${n}`}));return t.catchall&&t.catchall._def.typeName!=="ZodNever"&&r.push({schema:t.catchall,path:`${e}.<catchall>`}),r}case"ZodArray":return[{schema:t.type,path:`${e}[]`}];case"ZodUnion":case"ZodDiscriminatedUnion":return[...t.options.values()].map((r,n)=>({schema:r,path:`${e}[${n}]`}));case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodReadonly":return[{schema:t.innerType,path:e}];case"ZodBranded":return[{schema:t.type,path:e}];case"ZodLazy":return[{schema:t.getter(),path:e}];default:return}}function M_(t){let e=t.checks??[];return e.some(({kind:r})=>r==="finite"||r==="int")?!0:e.some(({kind:r,value:n})=>r==="min"&&typeof n=="number"&&Number.isFinite(n))&&e.some(({kind:r,value:n})=>r==="max"&&typeof n=="number"&&Number.isFinite(n))}function fE(t,e,r){return t.unknownKeys!=="passthrough"&&(t.catchall===void 0||t.catchall._def.typeName==="ZodNever")&&Object.values(t.shape()).every(n=>r(n,new Set(e)))}function Ao(t,e=new Set){let r=t._def;if(e.has(r))return!0;switch(e.add(r),r.typeName){case"ZodString":case"ZodBoolean":case"ZodNull":case"ZodEnum":case"ZodNativeEnum":return!0;case"ZodLiteral":return $c(r.value)!==void 0;case"ZodNumber":return M_(r);case"ZodArray":return Ao(r.type,e);case"ZodObject":return fE(r,e,Ao);case"ZodUnion":case"ZodDiscriminatedUnion":return[...r.options.values()].every(n=>Ao(n,new Set(e)));case"ZodNullable":case"ZodDefault":case"ZodReadonly":return Ao(r.innerType,e);case"ZodBranded":return Ao(r.type,e);case"ZodLazy":return Ao(r.getter(),e);default:return!1}}function mE(t,e){let r=iE.get(t.typeName);r&&hr(e,t.typeName,r),t.typeName==="ZodLiteral"&&!$c(t.value)&&hr(e,t.typeName,"literal values must be finite JSON primitives"),t.typeName==="ZodNumber"&&t.coerce===!0&&!M_(t)&&hr(e,t.typeName,"number coercion must prove its parsed output is finite"),t.typeName==="ZodDefault"&&!Ao(t.innerType)&&hr(e,t.typeName,"default factory output is not independently guaranteed to be finite and JSON-native; it may contain bigint"),t.typeName==="ZodString"&&t.checks?.some(({kind:n})=>aE.has(n))&&hr(e,t.typeName,"value-changing string checks are not represented in JSON Schema"),t.typeName==="ZodString"&&(t.checks?.filter(({kind:n})=>lE.has(n)).length??0)>1&&hr(e,t.typeName,"multiple pattern-producing checks require unsupported allOf")}function Fp(t,e,r){let n=t._def;if(r.has(n)||(r.add(n),n.typeName==="ZodIntersection"&&e==="$"))return;mE(n,e);let o=pE(n,e);if(!o){sE.has(n.typeName)||hr(e,n.typeName,"this Zod schema is outside the documented JSON-native subset");return}for(let s of o)Fp(s.schema,s.path,r);n.typeName==="ZodObject"&&(n.unknownKeys==="passthrough"||n.catchall!==void 0&&n.catchall._def.typeName!=="ZodNever")&&hr(e,n.typeName,"open object schemas require additionalProperties: false"),n.typeName==="ZodUnion"&&e!=="$"&&dE(o.map(({schema:s})=>s),e)}function $_(t,e){let r=new Set;Fp(t,"$",r);for(let[n,o]of Object.entries(e??{}))Fp(o,`$.definitions.${n}`,r)}function hE(t,e){for(let r=t;r!==null;r=Object.getPrototypeOf(r)){let n=Object.getOwnPropertyDescriptor(r,"toJSON");if(n){if(!("value"in n)||typeof n.value=="function")throw new Error(`Strict Structured Outputs schema field \`${e}\` contains an unsupported \`toJSON\` serialization hook`);return}}}function gE(t,e){if(Object.is(t,-0))throw new TypeError(`Strict Structured Outputs schema field \`${e}\` contains negative zero, which cannot round-trip through JSON`)}function ja(t,e="$",r=new Set){if(t===null||typeof t=="string"||typeof t=="boolean")return;if(typeof t=="number"&&Number.isFinite(t)){gE(t,e);return}if(typeof t!="object")throw new TypeError(`Strict Structured Outputs schema field \`${e}\` contains a non-JSON ${typeof t} value`);if(r.has(t))throw new Error(`Strict Structured Outputs schema field \`${e}\` contains a circular JSON value`);let n=Object.getPrototypeOf(t);if(!Array.isArray(t)&&n!==Object.prototype&&n!==null)throw new Error(`Strict Structured Outputs schema field \`${e}\` contains a non-JSON native object`);if(hE(t,e),r.add(t),Array.isArray(t))for(let o=0;o<t.length;o+=1){let s=Object.getOwnPropertyDescriptor(t,String(o));if(!s)throw new Error(`Strict Structured Outputs schema field \`${e}[${o}]\` contains a sparse array`);if(!("value"in s))throw new Error(`Strict Structured Outputs schema field \`${e}[${o}]\` contains an array accessor`);ja(s.value,`${e}[${o}]`,r)}else for(let o of Object.keys(t)){let s=Object.getOwnPropertyDescriptor(t,o);if(!s||!("value"in s))throw new Error(`Strict Structured Outputs schema field \`${e}.${o}\` contains an accessor`);ja(s.value,`${e}.${o}`,r)}r.delete(t)}function N_(t){return encodeURIComponent(t.replace(/~/g,"~0").replace(/\//g,"~1"))}function yE(t){if(t&&N(t,"__proto__"))throw new Error('schemaDefinitions cannot include "__proto__" as a definition name')}function L_(t,e){let r=new Map([...e].map(([s,i])=>[`#/definitions/${s}`,`#/definitions/${N_(i)}`]));if(r.size===0)return t;let n=new Set,o=s=>{if(!Te(s)||n.has(s))return;n.add(s);let i=s,a=i.$ref;if(typeof a=="string"){let l=r.get(a);l!==void 0&&l!==a&&(i.$ref=l)}Ye(i,[],o)};return o(t),t}function _E(t,e){if(!e)return t;let r=t;for(;N(e,r);)r=`${r}_root`;return r}function wE(t,e){$_(t,e.schemaDefinitions);let r=_E(e.name,e.schemaDefinitions),n=Pp(t,{openaiStrictMode:!0,name:r,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property",...e.schemaDefinitions?{definitions:e.schemaDefinitions}:void 0}),o=L_(n,new Map(Object.keys(e.schemaDefinitions??{}).map(s=>[s,s])));return ja(o),o}function bE(t,e={}){let r=e.schemaDefinitions?Xf():void 0,n=new Map;for(let[i,a]of Object.entries(e.schemaDefinitions??{})){let l=encodeURIComponent(i).replace(/~/g,"%7E");n.set(l,i),r?.add(a,{id:l})}let o=Qf(t,{target:"draft-7",...r?{metadata:r}:void 0,override:({zodSchema:i,jsonSchema:a,path:l})=>{let c=i._zod.def;if(c.type==="object"&&N(c.shape,"__proto__")){let d=[...l,"properties","__proto__"].map(m=>N_(String(m))).join("/");throw new Error(`Zod field at \`#/${d}\` uses unsupported property name \`__proto__\`, which Zod omits from parsed output.`)}if(c.type==="union"&&"discriminator"in c&&Array.isArray(a.oneOf)){if(a.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");a.anyOf=a.oneOf,delete a.oneOf}}}),s=L_(o,n);return s.definitions&&(s.definitions=Object.fromEntries(Object.entries(s.definitions).map(([i,a])=>[n.get(i)??i,a]))),v_(s)}function j_(t){return"_zod"in t}function AE(t,e){let r=wt({type:"json_schema",$parseRaw:void 0},e),n=t.parse;if(typeof n=="function"){let o=n.call(t,r);return j_(t)||ja(o),o}return lm(t,r)}function D_(t,e,r){let n=t,{schemaDefinitions:o,...s}=r??{};return yE(o),Hh({type:"json_schema",json_schema:{...s,name:e,strict:!0,schema:j_(n)?bE(n,{schemaDefinitions:o}):wE(n,{name:e,schemaDefinitions:o})}},i=>AE(t,i))}var F_=["jsonSchema","functionCalling","jsonMode"];function z_(t,e){if(typeof e<"u"&&!F_.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${F_.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 xE(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function B_(t,e,r){if(Yf(t))return D_(t,e,r);if(nl(t))return xE({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:_n(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Jf(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function U_(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 q_={"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},"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},"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-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},"chatgpt-image-latest":{maxInputTokens:0,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:0,reasoningOutput:!1,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.6-sol":{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-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-6-astra":{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.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},"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},"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},"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.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},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-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},"gpt-5.6-luna":{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.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-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},"gpt-image-1.5":{maxInputTokens:0,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:0,reasoningOutput:!1,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,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-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},"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-image-1":{maxInputTokens:0,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:0,reasoningOutput:!1,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-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},"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},"gpt-image-1-mini":{maxInputTokens:0,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:0,reasoningOutput:!1,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-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-image-2":{maxInputTokens:0,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:0,reasoningOutput:!1,imageOutputs:!0,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.6":{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},"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-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.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},"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-5.6-terra":{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-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.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-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},"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},"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-realtime-2.1":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,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},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},"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-5.3-chat-latest":{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.5":{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-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}};var Nc="**REDACTED**";function wi(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var xo=class extends al{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","baseUrl","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}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let n={...r};return"headers"in n&&(n.headers=Nc),"authorization"in n&&(n.authorization=Nc),n})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let n={...r};return"headers"in n&&(n.headers=Nc),"authorization"in n&&(n.authorization=Nc),n})}:t}_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,r=t&&"baseUrl"in t&&typeof t.baseUrl=="string"?t.baseUrl:void 0,n=$u({baseURL:t?.configuration?.baseURL??r??(Ke("OPENAI_API_BASE")||Ke("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??n.apiKey??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,baseURL:n.baseURL},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.13")}_getReasoningParams(t){if(!dr(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&&yn(t.json_schema.schema)?B_(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={baseURL:this.clientConfig.baseURL},r=fr(e),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=mr(n.defaultHeaders),this.client=new F(n)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return ho(t)?Ly(t.metadata.customTool):sl(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ty(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(mi(n)||ho(n))return n;if(ky(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return Po(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(pr(s))]),l=s.name!==void 0?n+await this.getNumTokens(s.name):0,c=i+r+a+l,d=s;if(d._getType()==="function"&&(c-=2),d.additional_kwargs?.function_call&&(c+=3),d?.additional_kwargs.function_call?.name&&(c+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{c+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(d.additional_kwargs.function_call)),c+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return e+=c,c}));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=Ey(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 ht(o)}})}get profile(){return q_[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=z_(this.model,e?.method);if(a==="jsonMode"){n=Pu(o);let l=_n(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...l}}})}else if(a==="jsonSchema"){let l=_n(o),c={name:s??"extract",description:ku(l),schema:yn(o)?o:l,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:c},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:c.name,description:c.description,...l}}}),yn(o)||rl(o)){let d=Pu(o);n=vr.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:d.invoke(m.content))}else n=new rm}else{let l=s??"extract",c=_n(o),d;yn(o)||rl(o)?d={name:l,description:c.description,parameters:c}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(d=o,l=o.name):(l=o.title??l,d={name:l,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:l}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:l,...c}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=nm(o,l)}return om(r,n,i)}};var Da={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=Tu({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=Su(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=Su(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=Tu({dataUrl:t.url}),r=mo(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=mo(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`)}},Lc=({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 d of n??[])try{s.push(il(d,{returnId:!0}))}catch(m){i.push(Co(d,m.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 l={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};t.audio&&(a.audio=t.audio);let c=U_(t.content||"",e.choices?.[0]?.message);return new Y({content:c,tool_calls:s,invalid_tool_calls:i,additional_kwargs:a,response_metadata:l,id:e.id})}default:return new el(t.content||"",t.role??"unknown")}},jc=({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 Ou({content:s,response_metadata:a});if(o==="assistant"){let l=[];if(Array.isArray(t.tool_calls))for(let c of t.tool_calls)l.push({name:c.function?.name,args:c.function?.arguments,id:c.id,index:c.index,type:"tool_call_chunk"});return new xr({content:s,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:a})}else return o==="system"?new tl({content:s,response_metadata:a}):o==="developer"?new tl({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Hf({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new Eu({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Kf({content:s,role:o,response_metadata:a})},zp=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=Vf(()=>{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=mo(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}}}},Bp=({message:t,model:e})=>{let r=pr(t);if(r==="system"&&dr(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 Y.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(Cu):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),Array.isArray(o.content)&&o.content.length===0&&o.tool_calls!=null&&(o.content=null),o}else{if(r==="tool"&&re.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=zp(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},vo=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Bp({message:r});let n=pr(r);n==="system"&&dr(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>Qa(i)?Ya(i,Da):typeof i=="object"&&i!==null&&"type"in i&&(i.type==="tool_use"||i.type==="tool_call"||i.type==="functionCall"||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),Y.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Cu):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),re.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 Dc=class extends xo{constructor(t,e){super(wi(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:Sc(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),dr(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=vo({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let g of i){g.message.response_metadata={...g.generationInfo,...g.message.response_metadata};let b=g.generationInfo?.completion??0;a[b]===void 0?a[b]=g:a[b]=a[b].concat(g)}let l=Object.entries(a).sort(([g],[b])=>parseInt(g,10)-parseInt(b,10)).map(([g,b])=>b),{functions:c,function_call:d}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,c,d),f=await this._getNumTokensFromGenerations(l);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:l,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,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:a,prompt_tokens:l,total_tokens:c,prompt_tokens_details:d,completion_tokens_details:m}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),l&&(n.input_tokens=(n.input_tokens??0)+l),c&&(n.total_tokens=(n.total_tokens??0)+c),(d?.audio_tokens!==null||d?.cached_tokens!==null||d?.cache_write_tokens!=null)&&(n.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens},...d?.cache_write_tokens!=null&&{cache_creation:d?.cache_write_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let g of i?.choices??[]){let b={text:g.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(g.message??{role:"assistant"},i)};b.generationInfo={...g.finish_reason?{finish_reason:g.finish_reason}:{},...g.logprobs?{logprobs:g.logprobs}:{}},Ar(b.message)&&(b.message.usage_metadata=n),b.message=new Y(Object.fromEntries(Object.entries(b.message).filter(([_])=>!_.startsWith("lc_")))),f.push(b)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=vo({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*ll(async function*(l,c){for await(let d of l){if(c?.aborted)return;yield d}}(s,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=vo({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 l of i){if(e.signal?.aborted)return;let c=l?.choices?.[0];if(l.usage&&(a=l.usage),!c)continue;let{delta:d}=c;if(!d)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(d,l,s);s=d.role??s;let f={prompt:e.promptIndex??0,completion:c.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let g={...f};c.finish_reason!=null&&(g.finish_reason=c.finish_reason,g.system_fingerprint=l.system_fingerprint,g.model_name=l.model,g.service_tier=l.service_tier),this.logprobs&&(g.logprobs=c.logprobs);let b=new $i({message:m,text:m.content,generationInfo:g});yield b,await r?.handleLLMNewToken(b.text??"",f,void 0,void 0,void 0,{chunk:b})}if(a){let l={...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},...a.prompt_tokens_details?.cache_write_tokens!=null&&{cache_creation:a.prompt_tokens_details?.cache_write_tokens}},c={...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}},d=new $i({message:new xr({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(l).length>0&&{input_token_details:l},...Object.keys(c).length>0&&{output_token_details:c}}}),text:""});yield d,await r?.handleLLMNewToken(d.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:d})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:r,...n}=e??{},o=this._getClientOptions(n),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,o):await this.client.chat.completions.create(t,o)}catch(i){throw ht(i)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return jc({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Lc({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Q_=Sf(X_(),1),zc="__openai_function_call_ids__",Bc="__openai_custom_tool_call_ids__";function Y_(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 TE(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 bi=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens},...t?.input_tokens_details?.cache_write_tokens!=null&&{cache_creation:t?.input_tokens_details?.cache_write_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}},Fa=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 l={...a};return delete l.parsed_arguments,l}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(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(i.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(Y_),...a.phase!==null?{phase:a.phase}:{}}):l.type==="refusal"?(i.refusal=l.refusal,[]):l));else if(a.type==="function_call"){let l={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(il(l,{returnId:!0}))}catch(c){let d;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(d=c.message),n.push(Co(l,d))}i[zc]??={},a.id&&(i[zc][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let l=a.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(a.type==="custom_tool_call"){let l=Py(a);l?(r.push(l),i[Bc]??={},a.id&&a.call_id&&(i[Bc][a.call_id]=a.id)):n.push(Co(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let l=Ry(a);l?r.push(l):n.push(Co(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 Y({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:bi(t.usage),additional_kwargs:i,response_metadata:s})},Up=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}},Uc=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:[Y_(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let l="phase"in t.item?t.item.phase:void 0;l&&e.push({type:"text",text:"",phase:l,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[zc]={[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[Bc]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="reasoning"&&t.item.encrypted_content)i.reasoning={encrypted_content:t.item.encrypted_content};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 l=Fa(t.response);if(n=bi(t.response.usage),t.response.text?.format?.type==="json_schema"&&l.text)try{i.parsed??=JSON.parse(l.text)}catch{}for(let[c,d]of Object.entries(t.response))c!=="id"&&(c==="output"?s[c]=l.response_metadata.output:s[c]=d)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,l,c]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:l,status:c}}}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 l=t.item.summary?t.item.summary.map((d,m)=>({...d,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...l?{summary:l}:{}};let c=t.item.summary?.map(d=>d.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}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 $i({text:e.map(l=>l.text).join(""),message:new xr({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},qp=t=>{let e=Y.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Tt(()=>{try{let y=pr(t);return y==="system"||y==="developer"||y==="assistant"||y==="user"?y:"assistant"}catch{return"assistant"}}),o=y=>n==="assistant"?{type:"output_text",text:y,annotations:[]}:{type:"input_text",text:y},s,i=new Set,a=new Set,l=new Map,c=new Map;function*d(){if(!s)return;let y=s.content;(typeof y=="string"&&y.length>0||Array.isArray(y)&&y.length>0)&&(yield s),s=void 0}let m=(y,S)=>{s||(s={type:"message",role:n,content:[],...S?{phase:S}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[o(s.content),...y]:[...y]:s.content.push(...y)},f=y=>{if(typeof y=="string")return y;try{return JSON.stringify(y??{})}catch{return"{}"}},g=y=>{let S=Tt(()=>{let I=y.metadata?.detail;return I==="low"||I==="high"||I==="auto"?I:"auto"});if(y.fileId)return{type:"input_image",detail:S,file_id:y.fileId};if(y.url)return{type:"input_image",detail:S,image_url:y.url};if(y.data){let I=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64");return{type:"input_image",detail:S,image_url:`data:${y.mimeType??"image/png"};base64,${I}`}}},b=y=>{if(y.fileId){let S=vc(y);return{type:"input_file",file_id:y.fileId,...S?{filename:S}:{}}}if(y.url){let S=vc(y);return{...S?{filename:S}:{},type:"input_file",file_url:y.url}}if(y.data){let S=mo(y),I=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64");return{type:"input_file",file_data:`data:${y.mimeType??"application/octet-stream"};base64,${I}`,filename:S}}},_=y=>{let S=Tt(()=>{if(Array.isArray(y.summary)){let k=y.summary?.map(D=>D?.text).filter(D=>typeof D=="string")??[];if(k.length>0)return k}return y.reasoning?[y.reasoning]:[]}),I=S.length>0?S.map(k=>({type:"summary_text",text:k})):[{type:"summary_text",text:""}],R=y.encrypted_content;return{type:"reasoning",...y.id?{id:y.id}:{},summary:I,...typeof R=="string"?{encrypted_content:R}:{}}},x=y=>({type:"function_call",name:y.name??"",call_id:y.id??"",arguments:f(y.args)}),O=y=>{let S=f(y.output),I=y.status==="success"?"completed":y.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:y.toolCallId??"",output:S,...I?{status:I}:{}}};for(let y of t.contentBlocks)if(y.type==="text"){let S=Tt(()=>{if("extras"in y&&typeof y.extras=="object"&&y.extras!==null&&"phase"in y.extras)return y.extras.phase});m([o(y.text)],S)}else if(y.type!=="invalid_tool_call"){if(y.type==="reasoning")yield*d(),yield _(y);else if(y.type==="tool_call"){yield*d();let S=y.id??"";S&&(i.add(S),l.delete(S)),yield x(y)}else if(y.type==="tool_call_chunk"){if(y.id){let S=l.get(y.id)??{name:y.name,args:[]};y.name&&(S.name=y.name),y.args&&S.args.push(y.args),l.set(y.id,S)}}else if(y.type==="server_tool_call"){yield*d();let S=y.id??"";S&&(a.add(S),c.delete(S)),yield x(y)}else if(y.type==="server_tool_call_chunk"){if(y.id){let S=c.get(y.id)??{name:y.name,args:[]};y.name&&(S.name=y.name),y.args&&S.args.push(y.args),c.set(y.id,S)}}else if(y.type==="server_tool_call_result")yield*d(),yield O(y);else if(y.type!=="audio")if(y.type==="file"){let S=b(y);S&&m([S])}else if(y.type==="image"){let S=g(y);S&&m([S])}else if(y.type==="video"){let S=b(y);S&&m([S])}else y.type==="text-plain"?y.text&&m([o(y.text)]):y.type==="non_standard"&&e&&(yield*d(),yield y.value)}yield*d();for(let[y,S]of l){if(!y||i.has(y))continue;let I=S.args.join("");!S.name&&!I||(yield{type:"function_call",call_id:y,name:S.name??"",arguments:I})}for(let[y,S]of c){if(!y||a.has(y))continue;let I=S.args.join("");!S.name&&!I||(yield{type:"function_call",call_id:y,name:S.name??"",arguments:I})}}return Array.from(r())},Ai=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return qp(n);let s=n.additional_kwargs,i=pr(n);if(i==="system"&&dr(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 c=a.content.find(f=>f.type==="input_image");if(c)return c;let d=a.content.find(f=>f.type==="computer_screenshot");if(d)return d;let m=a.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id: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 l=Array.isArray(a.content)&&a.content.every(c=>typeof c=="object"&&c!==null&&"type"in c&&(c.type==="input_file"||c.type==="input_image"||c.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:l?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(o?.output!=null&&Array.isArray(o.output)&&o.output.length>0&&o.output.every(_=>typeof _=="object"&&_!=null&&"type"in _&&typeof _.type=="string")){let _=o.output;return e?(0,Q_.toResponseInputItems)(_):_}let a=[],l=s?.reasoning,c=!!l?.encrypted_content;if(l&&(!e||c)){let _=Up(l);a.push(_)}let{content:d}=n;if(s?.refusal&&(typeof d=="string"&&(d=[{type:"output_text",text:d,annotations:[]}]),d=[...d,{type:"refusal",refusal:s.refusal}]),typeof d=="string"||d.length>0){let _={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Tt(()=>typeof d=="string"?d:d.flatMap(x=>{if(x.type==="text"){let O=x;return{type:"output_text",text:O.text,annotations:(O.annotations??[]).map(TE)}}return x.type==="output_text"||x.type==="refusal"?x:[]})),phase:Tt(()=>{if(Array.isArray(d))return d.find(x=>"phase"in x&&typeof x.phase=="string")?.phase})};a.push(_)}let m=s?.[zc],f=s?.[Bc];Y.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(_=>$y(_,f)?{type:"custom_tool_call",id:"call_id"in _&&typeof _.call_id=="string"?_.call_id:f?.[_.id??""]??"",call_id:_.id??"",input:_.args.input,name:_.name}:My(_)?{type:"computer_call",id:_.call_id,call_id:_.id??"",action:_.args.action}:{type:"function_call",name:_.name,arguments:JSON.stringify(_.args),call_id:_.id,...e?{}:{id:m?.[_.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(_=>({type:"function_call",name:_.function.name,call_id:_.id,arguments:_.function.arguments,...e?{}:{id:m?.[_.id]}})));let g=o?.output?.length?o?.output:s.tool_outputs,b=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(g!=null){let _=g?.filter(x=>b.includes(x.type));_.length>0&&a.push(..._)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],l=n.content.flatMap(c=>{if(c.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:c.approval_request_id,approve:c.approve}),c.type==="configuration_update"&&a.push({type:"configuration_update",reasoning:c.reasoning}),Qa(c)){if(c.type==="file"){let d=vc(c);if(c.source_type==="url")return{type:"input_file",file_url:c.url,...d?{filename:d}:{}};if(c.source_type==="id")return{type:"input_file",file_id:c.id,...d?{filename:d}:{}};if(c.source_type==="base64")return{type:"input_file",file_data:`data:${c.mime_type??""};base64,${c.data}`,filename:mo(c)}}return Ya(c,Da)}return c.type==="text"?{type:"input_text",text:c.text}:c.type==="image_url"?{type:"input_image",image_url:Tt(()=>{if(typeof c.image_url=="string")return c.image_url;if(typeof c.image_url=="object"&&c.image_url!==null&&"url"in c.image_url)return c.image_url.url}),detail:Tt(()=>{if(typeof c.image_url=="string")return"auto";if(typeof c.image_url=="object"&&c.image_url!==null&&"detail"in c.image_url)return c.image_url.detail})}:c.type==="input_text"||c.type==="input_image"||c.type==="input_file"?c:[]});return l.length>0&&a.push({type:"message",role:i,content:l}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Wp(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,i=0,a=!1,l,c,d,m,f=new Set,g=(x,O)=>{let y=s.get(x);if(y!==void 0)return{index:y,isNew:!1};let S=i++;return s.set(x,S),o.set(S,{...O}),{index:S,isNew:!0}},b=function*(){a||(a=!0,yield{event:"message-start",id:l})},_=function*(x){if(f.has(x))return;let O=o.get(x);O&&(f.add(x),yield{event:"content-block-finish",index:x,content:sm(O)})};for await(let x of t){if(x.type==="response.created"){l=x.response.id,yield*b(),yield{event:"provider",provider:n,name:"response.created",payload:{model:x.response.model,id:x.response.id}};continue}if(x.type==="response.output_text.delta"){yield*b();let{index:O,isNew:y}=g(`text:${x.output_index}:${x.content_index}`,{type:"text",text:""});y&&(yield{event:"content-block-start",index:O,content:{type:"text",text:""}});let S=o.get(O);S.text=(S.text??"")+x.delta,yield{event:"content-block-delta",index:O,delta:{type:"text-delta",text:x.delta}};continue}if(x.type==="response.reasoning_summary_text.delta"){yield*b();let{index:O,isNew:y}=g(`reasoning:${x.output_index}:${x.summary_index}`,{type:"reasoning",reasoning:""});y&&(yield{event:"content-block-start",index:O,content:{type:"reasoning",reasoning:""}});let S=o.get(O);S.reasoning=(S.reasoning??"")+x.delta,yield{event:"content-block-delta",index:O,delta:{type:"reasoning-delta",reasoning:x.delta}};continue}if(x.type==="response.output_item.added"&&(x.item.type==="function_call"||x.item.type==="custom_tool_call")){yield*b();let O=`tool:${x.output_index}`,y=x.item.type==="custom_tool_call",S=x.item.type==="function_call"?x.item.arguments??"":x.item.input??"",{index:I,isNew:R}=g(O,{type:"tool_call_chunk",id:x.item.call_id,name:x.item.name,args:S,index:x.output_index,...y?{isCustomTool:!0}:{}});if(R&&(yield{event:"content-block-start",index:I,content:{type:"tool_call_chunk",id:x.item.call_id,name:x.item.name,args:S,index:x.output_index}}),S){let k=o.get(I);yield{event:"content-block-delta",index:I,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(x.type==="response.function_call_arguments.delta"||x.type==="response.custom_tool_call_input.delta"){yield*b();let{index:O,isNew:y}=g(`tool:${x.output_index}`,{type:"tool_call_chunk",args:"",index:x.output_index,...x.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});y&&(yield{event:"content-block-start",index:O,content:{type:"tool_call_chunk",args:"",index:x.output_index}});let S=o.get(O);S.args=(S.args??"")+x.delta,yield{event:"content-block-delta",index:O,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(x.type==="response.output_item.done"&&(x.item.type==="function_call"||x.item.type==="custom_tool_call")){yield*b();let O=`tool:${x.output_index}`,y=x.item.type==="function_call"?x.item.arguments??"":x.item.input??"",{index:S,isNew:I}=g(O,{type:"tool_call_chunk",id:x.item.call_id,name:x.item.name,args:y,index:x.output_index});if(I)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:x.item.call_id,name:x.item.name,args:y,index:x.output_index}};else{let R=o.get(S);R.args=y,R.id=x.item.call_id,R.name=x.item.name}yield*_(S);continue}if(x.type==="response.completed"||x.type==="response.incomplete"){yield*b(),l=x.response.id,d=EE(x.response.status,x.type),m={model_provider:n,id:x.response.id,model:x.response.model,status:x.response.status},r&&x.response.usage&&(c=bi(x.response.usage),yield{event:"usage",usage:c});continue}x.type!=="response.image_generation_call.partial_image"&&(yield*b(),yield{event:"provider",provider:n,name:x.type,payload:x})}a||(yield{event:"message-start"});for(let[x]of o)f.has(x)||(yield*_(x));yield{event:"message-finish",reason:d,...c?{usage:c}:{},...m?{responseMetadata:m}:{}}}function EE(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var qc=class extends xo{constructor(t,e){super(wi(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:Cy(t?.tool_choice)?t?.tool_choice:(()=>{let o=Sc(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:Ai({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:o.output_text,message:Fa(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:Ai({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Wp(async function*(i,a){for await(let l of i){if(a?.aborted)return;yield l}}(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:Ai({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=Uc(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 ht(o)}}async completionWithRetry(t,e){let{maxRetries:r,...n}=e??{},o=this._getClientOptions(n);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,o):await this.client.responses.create(t,o)}catch(s){throw ht(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(mi(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(ho(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(sl(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 Tc(n)&&r.push(Ny(n));return r}};var Wc=class ew extends xo{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=wi(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new qc(n),this.completions=n?.completions??new Dc(n)}_useResponsesApi(e){let r=e?.tools?.some(mi),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(Tc)||e?.tools?.some(ho);return this.useResponsesApi||r||n||o||vy(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 ew(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Kc=class extends em{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=Ru(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 l=0;l<i.length;l+=1)o.push(a[l].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={baseURL:this.clientConfig.baseURL},n=fr(r),o={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=mr(o.defaultHeaders),this.client=new F(o)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw ht(r)}})}};var PE=p.object({type:p.literal("screenshot")}),RE=p.object({type:p.literal("click"),x:p.number(),y:p.number(),button:p.enum(["left","right","wheel","back","forward"]).default("left")}),ME=p.object({type:p.literal("double_click"),x:p.number(),y:p.number(),button:p.enum(["left","right","wheel","back","forward"]).default("left")}),$E=p.object({type:p.literal("drag"),path:p.array(p.object({x:p.number(),y:p.number()}))}),NE=p.object({type:p.literal("keypress"),keys:p.array(p.string())}),LE=p.object({type:p.literal("move"),x:p.number(),y:p.number()}),jE=p.object({type:p.literal("scroll"),x:p.number(),y:p.number(),scroll_x:p.number(),scroll_y:p.number()}),DE=p.object({type:p.literal("type"),text:p.string()}),FE=p.object({type:p.literal("wait"),duration:p.number().optional()}),zE=p.union([PE,RE,ME,$E,NE,LE,jE,DE,FE]),sQ=p.object({action:zE});var BE=p.object({type:p.literal("exec"),command:p.array(p.string()),env:p.record(p.string(),p.string()).optional(),working_directory:p.string().optional(),timeout_ms:p.number().optional(),user:p.string().optional()}),cQ=p.union([BE]);var fQ=p.object({commands:p.array(p.string()).describe("Array of shell commands to execute"),timeout_ms:p.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:p.number().optional().describe("Optional maximum number of characters to return from each command")});var UE=p.object({type:p.literal("create_file"),path:p.string(),diff:p.string()}),qE=p.object({type:p.literal("update_file"),path:p.string(),diff:p.string()}),WE=p.object({type:p.literal("delete_file"),path:p.string()}),yQ=p.union([UE,qE,WE]);var rw={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Hp={default:"text-embedding-ada-002"},Kp=new Map,Hc=null,ZE=()=>{let t=tw.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},nw=async t=>{let e=ZE();Kp.size===0&&(Hc||(Hc=(async()=>{try{(await VE(`${e}/models`)).data.models.forEach(n=>Kp.set(n.name,n))}catch(n){throw Hc=null,n}})()),await Hc);let r=Kp.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},XE=async(t="default")=>await nw(rw[t]),ow=async(t="default")=>await nw(Hp[t]),vi=(t,e)=>e,sw=(t,e)=>({...t,...e}),iw=(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(`
75
+
76
+ `);return o[o.length-1]?.trim()===r?t:`${t}
77
+
78
+ ${r}`},aw=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),pn=()=>({agentExecutionContext:B({reducer:sw,default:aw}),outputMessage:B({reducer:iw,default:()=>""}),summary:B({reducer:vi,default:()=>""}),status:B({reducer:vi})}),Vp=()=>({...pn(),sharedStatePatch:B({reducer:vi})}),QE=B.Root({agentExecutionContext:B({default:aw,reducer:sw}),currentIntent:B({default:()=>"none",reducer:vi}),lastExecutedAgent:B({default:()=>"",reducer:vi}),requiresFollowUp:B({default:()=>!0,reducer:vi}),stepCount:B({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:B({default:()=>"",reducer:iw})});var YE=t=>typeof t=="string"&&t.length>0?t:void 0,eO=()=>Of(),tO=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,rO=t=>{let e=t?.configurable;return{conversationId:YE(e?.thread_id),abortSignal:t?.signal,requestId:eO(),requestSource:tO(JE.applicationName)}},lw=async({config:t})=>{let e=tw.getDefault(),r=(await GE.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:i,requestId:a,requestSource:l}=rO(t),c=new Headers(o?.headers);for(let m of[...c.keys()]){let f=m.toLowerCase();(f==="authorization"||f==="api-key"||f.startsWith("x-stainless-"))&&c.delete(m)}r&&r.length>0&&c.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(l&&l.length>0&&c.set("X-Esri-Request-Source",l),s&&s.length>0&&c.set("X-Esri-Conversation-Id",s),a.length>0&&c.set("X-Esri-Request-Id",a));let d=i&&o?.signal?AbortSignal.any([i,o.signal]):o?.signal??i;return await fetch(n,{...o,headers:c,signal:d})}},Gp=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=rw[e],s=await XE(e);return new Wc({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await lw({config:n})}})},cw=async(t={})=>{let{tier:e="default",config:r}=t,n=Hp[e],o=await ow(e);return new Kc({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:await lw({config:r})},batchSize:2048,maxConcurrency:10})},nO=p.object({id:p.string().min(1),name:p.string().min(1),description:p.string().min(1)});p.array(nO);var uw="0.1",xi=1536,dw="openai",pw=Hp.default,fw=`Name: {name}
79
+ Title: {title}
80
+ Description: {description}`,mw=`Name: {name}
81
+ Alias: {alias}
82
+ Description: {description}`,hw=p.object({schemaVersion:p.literal(uw),modified:p.number().int().nonnegative(),embeddings:p.object({modelProvider:p.literal(dw),model:p.literal(pw),dimensions:p.literal(xi),templates:p.object({layer:p.string().default(fw),field:p.string().default(mw)})}),layers:p.array(p.object({id:p.string().min(1),name:p.string().min(1),title:p.string().catch(""),description:p.string().catch(""),vector:p.array(p.number()).length(xi,{message:`Layer vector must be exactly ${xi} dimensions`}),fields:p.array(p.object({name:p.string().min(1),alias:p.string().catch(""),description:p.string().catch(""),vector:p.array(p.number()).length(xi,{message:`Field vector must be exactly ${xi} dimensions`})}))})).default([])});var gw=(t,e)=>{let r=im.fromTemplate(t);return am.fromMessages([r,...e])},oO=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=gw(e,o??[]),a=await Gp({modelTier:r,temperature:n,config:s});return i.pipe(a)},Vc=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,config:i}=t,a=await(await oO({promptText:e,modelTier:r,temperature:n,messages:o,config:i})).invoke(s??{},i);if(typeof a=="string")return a;let l=a.content;return typeof l=="string"?l:JSON.stringify(l)},za=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i,config:a}=t,l=gw(e,o??[]),c=(await Gp({modelTier:r,temperature:n,config:a})).withStructuredOutput(i);return await l.pipe(c).invoke(s??{},a)};var sO=p.object({name:p.string(),description:p.string(),valueType:p.string(),alias:p.string()}),BY=p.object({fields:p.array(sO)});var UY=p.object({title:p.string(),description:p.string(),name:p.string().nullable()});var yw=async t=>{try{return await(await cw()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var ww=t=>Array.isArray(t)&&t.every(Mi),aO=t=>typeof t=="object"&&t!=null&&"messages"in t&&ww(t.messages),lO=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,gr=class extends cm{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 Mi(i)&&i.getType()==="tool"||hn(i)?i:new re({status:"success",name:n.name,content:typeof i=="string"?i:JSON.stringify(i),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||Xa(o))throw o;return new re({status:"error",content:`Error: ${o.message}
83
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(lO(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(ww(t))s=t;else if(aO(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(l=>l.getType()==="tool").map(l=>l.tool_call_id)),a;for(let l=s.length-1;l>=0;l-=1){let c=s[l];if(Ar(c)){a=c;break}}if(a==null||!Ar(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(l=>l.id==null||!i.has(l.id)).map(l=>this.runTool(l,e,t))??[])}if(!r.some(hn))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)hn(s)?s.graph===Gt.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Bf(i))?o?o.goto.push(...s.goto):o=new Gt({graph:Gt.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var B7=B.Root({llmInputMessages:B({reducer:(t,e)=>Ni([],e),default:()=>[]})});var Ba=(t,e)=>e??t,WO=B.Root({...Vp(),intent:B({reducer:Ba}),vectorSearchLayerResults:B({reducer:Ba,default:()=>[]}),vectorSearchFieldResults:B({reducer:Ba}),navigationInternalState:B({reducer:Ba,default:()=>({toolCallMessage:void 0})})});async function KO(t,e){let r=Io.getDefault().helperServices,n=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Jp.assetsPath?.endsWith("/")?Jp.assetsPath:`${Jp.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await dO(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 pO({url:s,width:24,height:24}),l=new uO({geometry:i.location,symbol:a});e.graphics.removeAll(),e.graphics.add(l),await e.goTo(i.extent);let c={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:c}}}}var HO=["mapView"];function Kt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=HO.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function VO({address:t},e){let{mapView:r}=Kt(e);return await KO(t,r)}var GO=p.object({address:p.string().describe("The full address or place name to locate.")}),JO=H(VO,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:GO});async function ZO(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 XO({bookmarkName:t},e){let{mapView:r}=Kt(e);return await Promise.resolve(ZO(t,r))}var QO=p.object({bookmarkName:p.string().describe("The name of the bookmark to navigate to.")}),YO=H(XO,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:QO});async function ek(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 l={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:l}}}}catch(i){return console.error("Error in goToFeatures:",i),{text:`Error: ${i instanceof Error?i.message:"Unknown error"}`,where:o}}}async function tk({layerId:t,where:e},r){let{mapView:n}=Kt(r);return await ek(t,e,n)}var rk=p.object({layerId:p.string().describe("The layerId of the layer to zoom to."),where:p.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.")}),nk=H(tk,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:rk});async function ok(t){let e=new fO({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 sk(t,e){let{mapView:r}=Kt(e);return await ok(r)}var ik=p.object({}),ak=H(sk,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:ik});async function lk(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 ck(t,e){let{mapView:r}=Kt(e);return await lk(r)}var uk=p.object({}),dk=H(ck,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:uk});async function pk(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 fk({layerId:t},e){let{mapView:r}=Kt(e);return await pk(t,r)}var mk=p.object({layerId:p.string().describe("The id of the layer to navigate to")}),hk=H(fk,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:mk});async function gk(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function yk({scale:t},e){let{mapView:r}=Kt(e);return await gk(t,r)}var _k=p.object({scale:p.number().describe("The map scale of the view to go to.")}),wk=H(yk,{name:"goToScale",description:"Go to the specified view scale.",schema:_k});async function bk(t,e,r){let n={target:new Ow({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 Ak({center:t,zoom:e,scale:r},n){let{mapView:o}=Kt(n);return await bk(t,o,{zoom:e,scale:r})}var xk=p.object({center:p.object({longitude:p.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:p.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:p.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:p.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),vk=H(Ak,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:xk});async function Ik(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function Sk({zoom:t},e){let{mapView:r}=Kt(e);return await Ik(t,r)}var Tk=p.object({zoom:p.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Ek=H(Sk,{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:Tk}),Sw=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 yr(t){let e=Object.entries(Sw).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
84
+ Available prompts:
85
+ ${Object.keys(Sw).join(`
86
+ `)}`);return await e[1]()}var Ti=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function Ok(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=hO({basemapTheme:await xw(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=gO({basemapTheme:await xw(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(l=>l.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:i}}async function kk(t){return await mO(t)}async function Ck({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:s?"chart-size":"chart",fields:n,layer:a,view:i,colorSchemeTags:o};try{let c=await Ok(l),d=await kk(c);return a.renderer=d.renderer,a.visible=!0,`Chart renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var Pk=["mapView"];function Ct(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=Pk.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function Rk({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await Ck({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Mk=p.object({layerId:p.string().describe("The id of the layer to apply the chart renderer to"),fields:p.array(p.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),includeSize:p.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),$k=H(Rk,{name:"chart",description:`Label: Charts
87
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
88
+ Keywords: pie, chart, all categories, breakdown, proportion
89
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
90
+ Fields: This style requires 2-8 number fields.
91
+
92
+ Label: Charts and Size
93
+ 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.
94
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
95
+ 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.
96
+ Fields: This style requires 2-8 number fields.`,schema:Mk});function Nk(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,i=e[0],a;return s&&(a=sf({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 Lk(t){return await yO(t)}async function jk({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:"color-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let c=Nk(l),d=await Lk(c);return a.renderer=d.renderer,a.visible=!0,`Color-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying color-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function Dk({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await jk({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Fk=p.object({layerId:p.string().describe("The id of the layer to apply the color-age renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),theme:p.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),zk=H(Dk,{name:"color-age",description:`Label: Age (color)
97
+ 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.
98
+ Keywords: since, age, how old, how long
99
+ Example: Show the age of each feature based on its reported date.
100
+ Fields: This style requires at least one field with a date type.`,schema:Fk});function Bk(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,i=e[1],a=e[0],l;return o&&(l=sf({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:l}}async function Uk(t){return await _O(t)}async function qk({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:"color",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let c=Bk(l),d=await Uk(c);return a.renderer=d.renderer,a.visible=!0,`Color renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying color renderer: ${c instanceof Error?c.message:String(c)}`}}async function Wk({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await qk({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Kk=p.object({layerId:p.string().describe("The id of the layer to apply the color renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the color renderer"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),theme:p.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Hk=H(Wk,{name:"color",description:`Label: Counts and Amounts (color)
101
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
102
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
103
+ Example: Color each feature based on the population density.
104
+ 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:Kk});function Vk(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,i,a,l=e[0];return o&&(a=sf({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:l,normalizationField:i,theme:s,colorOptions:{colorScheme:a}}}async function Gk(t){return await wO(t)}async function Jk({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:"color-size-univariate",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let c=Vk(l),d=await Gk(c);return a.renderer=d.renderer,a.visible=!0,`Color-size-univariate renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying color-size-univariate renderer: ${c instanceof Error?c.message:String(c)}`}}async function Zk({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await Jk({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Xk=p.object({layerId:p.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:p.array(p.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),theme:p.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),Qk=H(Zk,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
105
+ Description: Vary symbol size and color based on the values of two numeric attributes.
106
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
107
+ 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.
108
+ 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:Xk});function Yk(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=AO({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 eC(t){return await bO(t)}async function tC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(l=>l.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 l=Yk(a),c=await eC(l);return i.renderer=c.renderer,i.visible=!0,`Dot Density renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying dot density renderer: ${l instanceof Error?l.message:String(l)}`}}async function rC({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ct(n);return await Ve({type:"show-legend",data:{layerIds:[t]}},n),await tC({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var nC=p.object({layerId:p.string().describe("The id of the layer to apply the dot density renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use")}),oC=H(rC,{name:"dot-density",description:`Dot Density
109
+ Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
110
+ **Use cases:**
111
+ - Population distribution visualization
112
+ - Comparing multiple categories within areas
113
+ - Showing spatial distribution patterns
114
+ **Examples:**
115
+ - Show the density of the population based on various race/ethnic groups
116
+ - Visualize distribution of different crops across regions
117
+ - Display demographic patterns within census tracts
118
+ **Fields:** Requires 2-8 number fields.
119
+ **Keywords:** density, how much, how many, total, number, amount`,schema:nC});function sC(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i=e[0];return o&&(s=vO({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:i,heatmapScheme:s}}async function iC(t){return await xO(t)}async function aC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(l=>l.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 l=sC(a),c=await iC(l);return i.renderer=c.renderer,i.visible=!0,`Heatmap renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying heatmap renderer: ${l instanceof Error?l.message:String(l)}`}}async function lC({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ct(n);return await Ve({type:"show-legend",data:{layerIds:[t]}},n),await aC({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var cC=p.object({layerId:p.string().describe("The id of the layer to apply the heatmap renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use")}),uC=H(lC,{name:"heatmap",description:`Label: Heat Map
120
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
121
+ Keywords: density, heatmap, hot spots, pattern, cluster
122
+ Example: Create a heatmap
123
+ Fields: This typically requires zero or one field of type number.`,schema:cC});function dC(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s&&(i=SO({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 pC(t){return await IO(t)}async function fC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:s?"predominance-size":"predominance",fields:n,layer:a,view:i,colorSchemeTags:o};try{let c=dC(l),d=await pC(c);return a.renderer=d.renderer,a.visible=!0,`Predominance renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying predominance renderer: ${c instanceof Error?c.message:String(c)}`}}async function mC({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await fC({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var hC=p.object({layerId:p.string().describe("The id of the layer to apply the predominance renderer to"),fields:p.array(p.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),includeSize:p.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),gC=H(mC,{name:"predominance",description:`Label: Predominant category
124
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
125
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
126
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
127
+ Fields: This style relies on 2-10 number fields.
128
+
129
+ Label: Predominant category and Size
130
+ 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.
131
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
132
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
133
+ Fields: This style relies on 2-10 number fields.`,schema:hC});function yC(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i={field:e[0]},a={field:e[1]};return o&&(s=EO({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:i,field2:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function _C(t){return await TO(t)}async function wC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(l=>l.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 l=yC(a),c=await _C(l);return i.renderer=c.renderer,i.visible=!0,`Relationship renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying relationship renderer: ${l instanceof Error?l.message:String(l)}`}}async function bC({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ct(n);return await Ve({type:"show-legend",data:{layerIds:[t]}},n),await wC({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var AC=p.object({layerId:p.string().describe("The id of the layer to apply the relationship renderer to"),fields:p.array(p.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use")}),xC=H(bC,{name:"relationship",description:`Label: Relationship
134
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
135
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
136
+ Example: Show the relationship between tree height and carbon storage
137
+ Fields: This style requires two number fields.`,schema:AC});function vC(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 IC(t){return await OO(t)}async function SC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:"size-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let c=vC(l),d=await IC(c);return a.renderer=d.renderer,a.visible=!0,`Size-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying size-age renderer: ${c instanceof Error?c.message:String(c)}`}}async function TC({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await SC({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var EC=p.object({layerId:p.string().describe("The id of the layer to apply the size-age renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),theme:p.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),OC=H(TC,{name:"size-age",description:`Label: Age (size)
138
+ 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.
139
+ Keywords: since, age, how old, how long
140
+ Example: Change the size of features so older features are larger than new features.
141
+ Fields: This style requires at least one field with a date type.`,schema:EC});function kC(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 CC(t){return await kO(t)}async function PC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:"size",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let c=kC(l),d=await CC(c);return a.renderer=d.renderer,a.visible=!0,`Size renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying size renderer: ${c instanceof Error?c.message:String(c)}`}}async function RC({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await PC({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var MC=p.object({layerId:p.string().describe("The id of the layer to apply the size renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),theme:p.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),$C=H(RC,{name:"size",description:`Label: Counts and Amounts (size)
142
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
143
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
144
+ Example: Vary the size of each point based on the total population.
145
+ 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.
146
+
147
+ Label: Continuous Timeline (size)
148
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
149
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
150
+ Example: Vary the size of each feature based on the date a ticket was completed.
151
+ Fields: This style requires a single field with a date type.`,schema:MC});function NC(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],i=e[1],a=e[2],l;return o&&(l=PO({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:i,field3:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:l}}async function LC(t){return await CO(t)}async function jC({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(c=>c.id===r);if(!a)return`Could not find layer for id: ${r}`;let l={styleName:"type",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let c=NC(l),d=await LC(c);return a.renderer=d.renderer,a.visible=!0,`Type renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(c){return`Error applying type renderer: ${c instanceof Error?c.message:String(c)}`}}async function DC({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ct(o);return await Ve({type:"show-legend",data:{layerIds:[t]}},o),await jC({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var FC=p.object({layerId:p.string().describe("The id of the layer to apply the type renderer to"),fields:p.array(p.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:p.array(p.string()).optional().describe("Optional color scheme tags to use"),theme:p.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),zC=H(DC,{name:"type",description:`Label: Types (unique symbols)
152
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
153
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
154
+ Example: Color each feature based on the region it belongs to
155
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:FC}),BC=B.Root({...pn(),vectorSearchLayerIds:B(),vectorSearchFieldResults:B(),layerFieldInfo:B(),selectedLayerId:B()}),UC=B.Root({...pn(),vectorSearchLayerIds:B(),vectorSearchFieldResults:B(),layerFieldInfo:B(),queryResponse:B(),dataExplorationMessages:B({reducer:Ni,default:()=>[]})}),qC=["mapView"];function fn(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=qC.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var WC=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."},KC=async(t,e)=>{let{mapView:r}=fn(e);return WC(r)},Xee=H(KC,{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:p.object({})}),HC=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."},VC=async(t,e)=>{let{mapView:r}=fn(e);return await HC(r)},Qee=H(VC,{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:p.object({})}),Tw=750;function Xc(t){return"point"in t&&t.point!==void 0}function Ua(t){return"layerId"in t&&t.layerId!==void 0}var eu=async(t,e)=>{if(Xc(t)){let{point:r}=t;return{geometry:new Ow({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Ua(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:Tw+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Tw)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(l=>l.geometry).filter(l=>!!l);if(!i.length)return{error:"No valid geometries found for the matched geometry layer features."};let a=i.length===1?i[0]:Cw.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"}},GC=async(t,e,r,n,o,s)=>{let i=t.map?.allLayers.find(l=>l.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:l,count:c}=await i.queryExtent(a);return!l||c===0?{success:!1,error:`No features found for filter (where: ${a.where}${n?", spatial filter used":""})`}:(await t.goTo(l),{success:!0})}catch(l){return{success:!1,error:l instanceof Error?l.message:String(l)}}},JC=async(t,e,r,n,o,s)=>{let i=e.map?.allLayers.find(m=>m.id===t.layerId);if(!i)return`Could not find target layer with ID: ${t.layerId}`;let a;if(o){let m=await eu(o,e);if("error"in m)return m.error;a=m.geometry}if(i.featureEffect=null,i.featureEffect=new RO({filter:new kw({...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 l=t.objectIds?.length?`${i.objectIdField} IN (${t.objectIds.join(",")})`:t.where,c=await GC(e,t.layerId,l,a,o?.distance,o?.units),d=i.title??t.layerId;return c.success?`Applied feature effects to target layer "${i.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${c.error}`},ZC=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],mn=p.enum(ZC),XC=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}=fn(s);return await JC(t,i,n,o,e,r)},QC=p.object({layerId:p.string().describe("The layerId of the layer containing the geometry by which to filter."),where:p.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:p.number().optional().describe("The buffer distance around the geometry."),units:mn.optional().describe("The units for the distance buffer.")}),YC=p.object({point:p.object({x:p.number().describe("X coordinate (longitude) from navigation result"),y:p.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:p.object({wkid:p.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:p.number().optional().describe("Optional buffer distance around the point."),units:mn.optional().describe("The units for the distance buffer.")}),eP=p.object({targetLayer:p.object({layerId:p.string().describe("The layerId of the layer on which to set a feature effect."),where:p.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:p.array(p.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:p.union([QC,YC]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:p.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:p.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:p.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.")}),Yee=H(XC,{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:eP}),tP=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Rw=t=>{if(!t)return!1;let e=t.toLowerCase();return tP.has(e)},Xp=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},rP=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,nP=t=>{if(typeof t=="string"&&t)return t;let e=Xp(t);return e?e.toISOString().slice(0,10):null};var oP=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Rw(n))return t;if(n==="date-only"){let s=nP(t);return s?MO(s,Gc("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return $O(t,Gc("long-time"));let s=Xp(t);return s?vw(s,{...Gc("long-time"),timeZone:"UTC"}):t}let o=Xp(t);return o?vw(o,{...Gc("short-date-short-time"),timeZone:rP(r)}):t},Mw=(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},sP=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,iP=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},aP=(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}},lP=(t,e,r)=>{let n=iP(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=sP(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},$w=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,Nw=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?aP(r,s):s?.type==="date-time"?!n||Rw(n)?lP(r,s,o):r:oP(r,n,o)},cP=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Mw(e,r,t)??r;return Nw(t,e,s,o?.type,n)},uP=(t,e)=>$w(t,e),Lw=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(i=>i.attributes[n]),s=e.features.map(i=>{let a=i.attributes,l={};return t.fields.forEach(c=>{if(!Object.hasOwn(a,c.name))return;let d=a[c.name];if(c.name===n){l[c.name]=d;return}let m=Mw(c.name,d,t)??d,f=$w(t,c.name);l[f]=Nw(t,c.name,m,c.type,r)}),l});return{objectIds:o,attributes:s}},dP=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},pP=async(t,e,r,n)=>{let o=n.map?.allLayers.find(d=>d.id===t),s=dP(o,e,r.where),i=(await o.queryFeatures(s)).features[0],a=i?i.attributes[e]:null,l=cP(o,e,a,n.timeZone),c=uP(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${c} = ${l}`,details:{fieldName:e,fieldAlias:c!==e?c:void 0,value:l,where:r.where}}};async function fP({layerId:t,fieldName:e,query:r},n){let{mapView:o}=fn(n),s=await pP(t,e,r,o);return JSON.stringify(s,null,2)}var mP=p.object({layerId:p.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:p.string().describe("The name of the field/attribute from which to get a field value."),query:p.object({where:p.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),hP=H(fP,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:mP}),af=(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 Qc(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var gP=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:i}=t,a=o.map?.allLayers.find(O=>O.id===e.layerId);if(!a)throw new Error(`Layer '${e.layerId}' not found.`);let l=await o.whenLayerView(a),c=s.get(e.layerId)?.fieldRegistry.get(r),d=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let m,f;if(i){let O=await eu(i,o);if("error"in O)throw new Error(O.error);if(!O.geometry)throw Ua(i)?new Error(`No features found matching: ${i.where}`):new Error("Failed to create geometry");if(Ua(i)){let y=o.map?.allLayers.find(S=>S.id===i.layerId);m={geometryLayerName:y?.title??y?.id,geometryLayerId:i.layerId,geometryWhere:i.where,distance:i.distance,units:i.units,applied:!0}}else Xc(i)&&(m={point:i.point,distance:i.distance,units:i.units,applied:!0});f=new kw({geometry:O.geometry,distance:i.distance,units:i.units,spatialRelationship:"intersects"})}let g=af(l,[r],!1),b=null,_=null,x=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let O={layer:a,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:Qc(a.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};b=await NO(O);let y=["string","small-integer","integer"],S=c.domain?.type==="coded-value"?c.domain:null;(y.includes(c.type)||S)&&(_=(await LO({layer:a,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:Qc(a.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort((I,R)=>R.count-I.count).slice(0,x)),_&&c.domain?.type==="coded-value"&&(_=_.map(I=>({...I,value:S?S.getName(I.value)??I.value:I.value})))}catch(O){console.error("Statistics error:",O)}return{tool:"getStatistics",layerName:a.title??e.layerId,summary:`${n} = ${typeof b?.[n]=="number"?b[n]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:n,statistic:b?.[n]??null,summaryStatistics:b,uniqueValues:_,where:e.where,spatialFilterInfo:m}}};async function yP({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Ti(o,"layersAndFieldsRegistry"),{mapView:i}=fn(o),a=await gP({targetLayer:t,fieldName:e,statisticType:r,mapView:i,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(a,null,2)}var _P=p.object({layerId:p.string().describe("The layerId of the layer containing the geometry by which to filter."),where:p.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:p.number().optional().describe("The buffer distance around the geometry."),units:mn.optional().describe("The units for the distance buffer.")}),wP=p.object({point:p.object({x:p.number().describe("X coordinate (longitude) from navigation result"),y:p.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:p.object({wkid:p.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:p.number().optional().describe("Optional buffer distance around the point."),units:mn.optional().describe("The units for the distance buffer.")}),bP=p.object({targetLayer:p.object({layerId:p.string().describe("The layerId of the layer containing the field from which to get a value."),where:p.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:p.union([_P,wP]).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:p.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:p.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),AP=H(yP,{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.
156
+
157
+ USE THIS TOOL FOR:
158
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
159
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
160
+ - Questions requiring a mathematical aggregation across many features
161
+
162
+ DO NOT USE FOR:
163
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
164
+ - "Show / list / find features" \u2014 use queryFeatures instead
165
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
166
+
167
+ 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:bP}),xP=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),vP=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,l;if(n){let f=await eu(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"}`}};l=f.geometry}else o&&(l=r.extent.clone());let c=e.groupByFields&&e.groupByFields.length>0,d=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])];try{let f;if(c){let _=new jO({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:l,spatialRelationship:l?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new DO({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(_)}else{let _=s.createQuery();_.where=Qc(s.definitionExpression,t.where||"1=1"),_.outFields=m.length?m:["*"],_.orderByFields=e.orderByFields,_.returnGeometry=!1,_.num=e.topCount,l&&(_.geometry=l,_.spatialRelationship="intersects"),n?.distance&&(_.distance=n.distance),n?.units&&(_.units=n.units),_.outSpatialReference=r.spatialReference;let x=[...new Set([...t.outFields,...xP(e.orderByFields)])],O=af(i,x,o??!1);try{f=O?await i.queryFeatures(_):await s.queryFeatures(_)}catch(y){console.warn("Client-side query failed, falling back to server:",y),f=await s.queryFeatures(_)}}let g=f.features.map(_=>_.attributes[d]),{attributes:b}=Lw(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:a,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:b,objectIds:g,objectIdField:d,where:t.where,orderByFields:e.orderByFields,...c&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:a,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},IP=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=fn(o),i=await vP(t,e,s,r,n);return JSON.stringify(i,null,2)},SP=p.object({layerId:p.string().describe("The layerId of the layer containing the geometry by which to filter."),where:p.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:p.number().optional().describe("The buffer distance around the geometry."),units:mn.optional().describe("The units for the distance buffer.")}),TP=p.object({point:p.object({x:p.number().describe("X coordinate (longitude) from navigation result"),y:p.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:p.object({wkid:p.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:p.number().optional().describe("Optional buffer distance around the point."),units:mn.optional().describe("The units for the distance buffer.")}),EP=p.object({targetLayer:p.object({layerId:p.string().describe("The layerId of the layer containing the field from which to get a value."),where:p.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:p.array(p.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:p.array(p.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:p.union([SP,TP]).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:p.object({topCount:p.number().describe("Number of top features to return per group."),orderByFields:p.array(p.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:p.array(p.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:p.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).")}),OP=H(IP,{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:EP}),Zp=25,kP=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),CP=async(t,e,r,n)=>{let o=e.map?.allLayers.find(x=>x.id===t.layerId),s=await e.whenLayerView(o),i=o.title??t.layerId,a;if(r){let x=await eu(r,e);if("error"in x){let O={error:x.error};if(Ua(r)){let y=e.map?.allLayers.find(S=>S.id===r.layerId);O.geometryLayerName=y?.title??y?.id,O.geometryLayerId=r.layerId,O.geometryWhere=r.where}else Xc(r)&&(O.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"Geometry lookup failed",details:O}}if(!x.geometry){let O={};if(Ua(r)){let y=e.map?.allLayers.find(S=>S.id===r.layerId);O.error=`No features found matching: ${r.where}`,O.geometryLayerName=y?.title??y?.id,O.geometryLayerId=r.layerId,O.geometryWhere=r.where}else Xc(r)&&(O.error="Failed to create point geometry",O.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"No features found for geometry filter",details:O}}a=x.geometry}else n&&(a=e.extent.clone());let l=[...new Set([...t.outFields,...kP(t.orderByFields)])],c=af(s,l,n??!1),d=o.objectIdField,m=o.createQuery();m.where=Qc(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,d])],m.orderByFields=t.orderByFields,a&&(m.geometry=a,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,g;try{f=c?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=Zp&&(g=c?await s.queryFeatures(m):await o.queryFeatures(m))}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await o.queryFeatureCount(m),f>0&&f<=Zp&&(g=await o.queryFeatures(m))}let{objectIds:b,attributes:_}=g?Lw(o,g,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,...b&&{objectIds:b,objectIdField:d},..._&&{attributes:_},...f>Zp&&{note:`${f} features found.`}}}};async function PP({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=fn(n),s=await CP(t,o,e,r);return JSON.stringify(s,null,2)}var RP=p.object({layerId:p.string().describe("The layerId of the layer containing the geometry by which to filter."),where:p.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:p.number().optional().describe("The buffer distance around the geometry."),units:mn.optional().describe("The units for the distance buffer.")}),MP=p.object({point:p.object({x:p.number().describe("X coordinate (longitude) from navigation result"),y:p.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:p.object({wkid:p.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:p.number().optional().describe("Optional buffer distance around the point."),units:mn.optional().describe("The units for the distance buffer.")}),$P=p.object({targetLayer:p.object({layerId:p.string().describe("The layerId of the layer containing the field from which to get a value."),where:p.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:p.array(p.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:p.array(p.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:p.union([RP,MP]).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:p.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).")}),NP=H(PP,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
168
+
169
+ USE THIS TOOL FOR:
170
+ - "Show / display / list features where..." \u2014 finding and listing features
171
+ - "How many X are Y?" \u2014 counting features that match a condition
172
+ - "Which features..." / "Find features..." \u2014 identifying specific features
173
+ - Spatial queries \u2014 finding features near/within/intersecting other features
174
+ - Any question where the user wants to SEE or COUNT matching features
175
+
176
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:$P}),jw=[hP,AP,OP,NP];var ete=new gr(jw,{handleToolErrors:!1});var LP=B.Root({...pn(),helpInternalState:B({reducer:Ba,default:()=>({toolCallMessage:void 0})})}),jP=(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(`
177
+ `);return`**${r.layerItem.title}** has ${n.length} field(s):
178
+
179
+ ${o}`},DP=async({layerTitle:t},e)=>{let r=Ti(e,"layersAndFieldsRegistry");return jP(r,t)},FP=H(DP,{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:p.object({layerTitle:p.string().describe("The title or partial title of the layer to list fields for.")})}),zP=B.Root({...pn(),intent:B({reducer:(t,e)=>e}),arcgisKnowledgeMessages:B({reducer:Ni,default:()=>[]}),arcgisKnowledgeToolResult:B({reducer:(t,e)=>e,default:()=>null})});function Dw(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 Ei(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function tu(t){!t||Ei(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function Wa(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)&&Dw(r),{view:r}}async function Oi(t){let e=t?.configurable?.context;if(BP(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 Iw(n)}}else{Dw(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 Iw(n)}}}}function BP(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 Qp=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Yc.fromDataModel(e)}},Yc=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(qa.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Yp.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:UP(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}.
180
+ Relationship Types: ${n}.`}},qa=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=qP(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:WP(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}},Yp=class extends qa{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=qa.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},UP=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},qP=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function WP(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 ru(t){return t?.signal}async function KP(t,e){let r=await yr("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
181
+
182
+ Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
183
+
184
+ Attempt Number: ${e.attemptCount}
185
+ Execution Error: ${e.executionError}
186
+ Failed Query:
187
+ ${e.failedGraphQuery}`:`${t} ${r}`}async function HP(t,e,r,n){let{graphQuery:o,explanation:s}=await lf(t,e,r,n);return{graphQuery:o,explanation:s}}async function lf(t,e,r,n,o){let s={message:await KP(t,o),context:new Qp(e)},i=ru(n);await fe({text:"Attempting to generate a cypher query from your prompt..."},n);let a=await Aw(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json","X-Esri-Authorization":`Bearer ${bw.findCredential(Io.getDefault().url)?.token??""}`},signal:i});if(a.httpStatus!==200)throw new Error(`Graph query service returned an error: ${a.httpStatus}`,{cause:a.data});let l=!1,c=Date.now(),d=a.data.sequenceNumber,m="",f="",g=1;for(;!l;){await new Promise(_=>setTimeout(_,1e3)),await fe({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,g)}`},n),g=g%3+1;let b=await Aw(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:a.data.conversationId,inquiryId:a.data.inquiryId,ackSequenceNumber:d}),headers:{"Content-Type":"application/json","X-Esri-Authorization":`Bearer ${bw.findCredential(Io.getDefault().url)?.token??""}`},signal:i});if(b.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${b.httpStatus}`,{cause:b.data});if(b.data.context?.kind){if(b.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${b.data.message}`,{cause:b.data});m=b.data.context.graphQuery,f=b.data.message||"",l=!0}else if(!b.data.hasMore)l=!0;else if(Date.now()-c>6e4)throw new Error("Graph query service polling timed out after 1 minute.");d=b.data.sequenceNumber}return{graphQuery:m,explanation:f}}function VP(t,e){Ii(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function Ii(t,e){if(!(!t||typeof t!="object")){if(JP(t))for(let r of t.path)Ii(r,e);else if(GP(t))e(t);else if(Array.isArray(t))for(let r of t)Ii(r,e);else if(ZP(t))for(let r of Object.values(t.properties??{}))Ii(r,e)}}function GP(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function JP(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function ZP(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function XP(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 l=t.getMemberIdsByType(a.name);i.push(...l)}return{entityIds:r,relationshipIds:n}}function QP(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,l]of s)for(let c of a){let d=o.namedTypeDefinitions.get(c.name);if(!d){i=!1,n.push(c.name);continue}if(!d.useAllData){i=!1,n.push(c.name);for(let[m]of d.members||[])l.push(m)}}return{allNamedTypesFullyDynamic:i,bindParameters:r,nonDynamicTypes:n}}var Si=3;function Fw(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 ki(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 YP=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:i})=>{let a=null,l=r,c=new AbortController,d=o?.signal,m=()=>{c.abort(d?.reason)};d&&(d.aborted?c.abort(d.reason):d.addEventListener("abort",m,{once:!0}));try{let f=await zO(t,e,o);a=f.resultHeader;let g=f.resultRowsStream.getReader(),b=0,_=Date.now(),x=!1;for(;;){let{done:O,value:y}=await g.read();if(O)break;if(!x&&i&&Date.now()-_>i)return c.abort(),{type:"timeout"};for(let S of y){if(b++,s&&b>s)return c.abort(),{type:"success",rowLimitReached:!0,resultHeader:a,processedResult:l};l=n(l,S)}}}catch(f){return c.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:ki(f),error:f}}finally{d?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:a,processedResult:l}};async function zw({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:l,config:c}){let d;for(let m=1;m<=Si;m++){let f;try{f=await lf(t,r.dataModel,n,c,d)}catch(x){return{type:"generation-error",errorMessage:ki(x),error:x}}await fe({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},c);let g=await eR(f.graphQuery,e),b=await YP({kg:r,queryParams:new Pw({openCypherQuery:f.graphQuery,bindParameters:g}),targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:l}),_=b.type==="aborted"?"Query execution was aborted.":b.type==="timeout"?"Query execution timed out.":b.type==="error"?`Query failed with error: ${b.errorMessage}`:"";if(b.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:b.rowLimitReached,resultHeader:b.resultHeader,processedResult:b.processedResult};if(b.type==="aborted")return{type:"aborted",errorMessage:_,graphQuery:f.graphQuery,explanation:f.explanation};if(m>=Si)return b.type==="timeout"?{type:"timeout",errorMessage:_,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:_,error:b.error,graphQuery:f.graphQuery,explanation:f.explanation};d={failedGraphQuery:f.graphQuery,executionError:_,attemptCount:m},await fe({text:`Attempt ${m} failed with error: ${_}. Retrying...`},c)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Si} attempts.`)}var eR=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await qO(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},tR=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 l=o??1/0;try{for(let c of a){let d=l-i.length;if(d<=0)break;let m=(await BO(t,new UO({searchQuery:e,typeCategoryFilter:c,namedTypesFilter:n??void 0,num:d}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:g,value:b}=await m.read();if(g){f=!0;break}for(let _ of b)for(let x of _)i.push(x)}}}catch(c){let d=ki(c);return s?.signal?.aborted?{type:"aborted",errorMessage:d,error:c}:{type:"error",errorMessage:d,error:c}}return{type:"success",results:i}},Bw="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Uw({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(Bw),!Ei(e)){let d=await yr("arcgis_knowledge_current_lc_context"),m=XP(e.map,r);return o.push(d),{enhancedPrompt:o.join(`
188
+
189
+ `),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:i,bindParameters:a,nonDynamicTypes:l}=QP(s,r);if(i)return{enhancedPrompt:o.join(`
190
+
191
+ `),bindParameters:a,allNamedTypesFullyDynamic:!0};let c=(await yr("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(l));return o.push(c),{enhancedPrompt:o.join(`
192
+
193
+ `),bindParameters:a,allNamedTypesFullyDynamic:i}}async function rR(t,e,r,n,o,s){let{view:i}=o,a=await zw({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,g)=>{for(let b of g)VP(b,f);return f},requestOptions:{signal:ru(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:l,explanation:c,processedResult:d}=a,m=Array.from(d.values());return await fe({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Ei(i)&&i?.map?(await i.map.addRecords(m),await tu(i),{generatedQuery:l,explanation:c,addedIdTypePairs:m}):(await i?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:l,explanation:c,addedIdTypePairs:m})}var Jc="addRecords",nR=p.object({prompt:p.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.")}),oR=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Oi(e),n=Wa(e),{view:o}=n,s=Io.getDefault().helperServices,{enhancedPrompt:i,bindParameters:a,allNamedTypesFullyDynamic:l}=await Uw({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(l)return{toolName:Jc,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:c,explanation:d,addedIdTypePairs:m}=await rR(i,a,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Jc,status:"success",summary:`Records added successfully. Cypher Query used: ${c}
194
+
195
+ Number of records added: ${m.length}`,details:{generatedQuery:c,explanation:d,addedIdTypePairs:m}}}catch(c){let d=ki(c);return{toolName:Jc,status:"error",errorMessage:`Failed to add records to the link chart. ${d}`,error:c}}},sR=H(oR,{name:Jc,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.
196
+
197
+ example prompts:
198
+ - "add all suppliers and the parts they produce to the link chart"
199
+ - "show me the competitors of company x and add them to the link chart"
200
+ - "add the relationships between company x and company y to the link chart"
201
+ - "expand all the companies"
202
+ - "expand company x through all the buildings it owns"
203
+ - "connect company x and company y"
204
+ - "connect all buildings on the link chart"
205
+ `,schema:nR});async function iR(t,e){return await e.map?.applyLayout(t),await tu(e),{appliedLayout:t}}var ef="applyLayout",aR=p.object({layout:p.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")}),lR=async({layout:t},e)=>{let{view:r}=Wa(e);if(Ei(r))return{toolName:ef,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await iR(t,r);return{toolName:ef,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},cR=H(lR,{name:ef,description:"Apply a diagram layout to the link chart",schema:aR});async function uR(t,e){return e.map?.changeNonspatialDataDisplay(t),await tu(e),{appliedNonspatialDataDisplayMode:t}}var tf="changeNonspatialVisibility",dR=p.object({setting:p.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),pR=async({setting:t},e)=>{let{view:r}=Wa(e);if(Ei(r))return{toolName:tf,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await uR(t,r);return{toolName:tf,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},fR=H(pR,{name:tf,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:dR});async function mR(t,e,r,n,o){let s,i="";for(let a=1;a<=Si;a++){let{graphQuery:l,explanation:c}=await lf(t,e.dataModel,r,o,s);try{await fe({text:`Attempting to create link chart from derived query: ${l}`},o);let d=await FO.fromCypherQuery(e,new Pw({openCypherQuery:l}));await fe({text:"Link chart created successfully, loading..."},o),await d.load();let m=n.map;return n.map=d,await n.when(),await Ew.whenOnce(()=>!n.updating),d.entityCount===0&&d.relationshipCount===0?(n.map===d&&(n.map=m),d.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
206
+ ${l}
207
+
208
+ Explanation: ${c}`}):(await tu(n),{type:"success",graphQuery:l,explanation:c})}catch(d){let m=ki(d);if(a>=Si){i=m;break}s={failedGraphQuery:l,executionError:m,attemptCount:a},await fe({text:`Attempt ${a} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Si} attempts. Last error: ${i}`}}var Zc="createLinkChart",hR=p.object({prompt:p.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.")}),gR=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Oi(e),{view:n}=Wa(e);if(Ei(n))return{toolName:Zc,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=Io.getDefault().helperServices,s=await mR(`${t}
209
+
210
+ ${Bw}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:Zc,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:i,explanation:a}=s;return{toolName:Zc,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
211
+ ${i}
212
+
213
+ Explanation: ${a}`,details:{generatedQuery:i,explanation:a}}}},yR=H(gR,{name:Zc,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:hR}),rf="queryGraphData",_R=p.object({prompt:p.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.")}),wR=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Oi(e),n=Io.getDefault().helperServices,o=t,s=null,i=null;try{({view:i}=Wa(e))}catch{}i&&({enhancedPrompt:o,bindParameters:s}=await Uw({prompt:t,view:i,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let a=await zw({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(_,x)=>(_.push(x),_),requestOptions:{signal:ru(e),timeout:e?.timeout},config:e});if(a.type!=="success"){let _=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;return{toolName:rf,status:"error",errorMessage:`Failed to query the knowledge graph. ${_}`,error:"error"in a?a.error:null}}let{graphQuery:l,explanation:c,processedResult:d,resultHeader:m}=a,f=m.headerKeys;for(let _ of d)for(let x of _)Ii(x,O=>Fw(O));let g=50,b=d.slice(0,g).map(_=>JSON.stringify(_));return{toolName:rf,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
214
+
215
+ \`\`\`cypher
216
+ ${l}
217
+ \`\`\`
218
+
219
+ Query Results:
220
+ ${b.length} result(s) found.
221
+
222
+ Column Headers: ${f.join(", ")}
223
+
224
+ ${b.length>g?`Showing top ${g} results:
225
+
226
+ `:`Results:
227
+
228
+ `}${b.join(`
229
+ `)}
230
+ `,details:{generatedQuery:l,explanation:c,resultHeader:{headerKeys:f,exceededTransferLimit:m.exceededTransferLimit,outSpatialReference:m.outSpatialReference},queryResults:d}}},bR=H(wR,{name:rf,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:_R}),nf="generateCypher",AR=p.object({prompt:p.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),xR=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Oi(e),n=Io.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await HP(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:nf,status:"success",summary:`Generated Graph Query:
231
+ ${o}
232
+
233
+ Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=ki(o);return{toolName:nf,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},vR=H(xR,{name:nf,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:AR}),IR=t=>{let e=t.dataModel,r=new Map;for(let a of e.searchIndexes)if(a.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[l,c]of a.searchProperties.entries()){let d=r.get(l)??new Set;c.propertyNames.forEach(m=>d.add(m)),r.set(l,d)}let n=e.entityTypes.filter(a=>r.has(a.name)),o=e.relationshipTypes.filter(a=>r.has(a.name)),s=`Entity Types:
234
+ ${n.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
235
+ `)}`,i=`Relationship Types:
236
+ ${o.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
237
+ `)}`;return`${s}
238
+
239
+ ${i}`};async function SR(t,e,r){let n=await yr("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:IR(e)},s=p.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),i=p.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=p.array(p.enum(e.dataModel.entityTypes.map(c=>c.name).concat(e.dataModel.relationshipTypes.map(c=>c.name)))).min(1),l=p.object({query:p.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 za({promptText:n,inputVariables:o,schema:l,config:r})}var of="searchGraphData",TR=p.object({prompt:p.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.")}),ER=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Oi(e);await fe({text:"Generating search query for the user inquiry"},e);let n=await SR(t,r,e);await fe({text:"Executing graph search with generated search query"},e);let o=await tR({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:ru(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:of,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let a of o.results)Ii(a,l=>Fw(l));let s=10,i=o.results.slice(0,s);return{toolName:of,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
240
+ Query: ${n.query}
241
+ Type Category Filter: ${n.typeCategoryFilter}
242
+ Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
243
+ Result Limit: ${n.resultLimit??"No limit"}
244
+
245
+ Search Results: ${o.results.length} result(s) found.
246
+
247
+ ${o.results.length>s?`Showing top ${s} results:
248
+
249
+ `:""}${i.map(a=>JSON.stringify(a)).join(`
250
+ `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},OR=H(ER,{name:of,description:`
251
+ 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.
252
+ Example prompts:
253
+ - "Find 'Bradley'"
254
+ - "find the person john smith"
255
+ - "find all people named smith"
256
+ - "Find all references to 'delayed parts shipment'"
257
+ - "Find all reports authored by someone with the title of 'Researcher'"
258
+ - "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".
259
+ - "Search for all john smiths and show their global ids`,schema:TR});var yte=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
260
+ 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.
261
+
262
+ Supported actions:
263
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
264
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
265
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
266
+ - **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
267
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
268
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
269
+ - **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").
270
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
271
+
272
+ _Example: “Zoom to Texas”_
273
+ _Example: “Go to the water mains layer”_
274
+ _Example: “Zoom to to the extent of my link chart”_
275
+ _Example: “Center the map on San Francisco at scale 50000”_
276
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
277
+ _Example: “Go to the Downtown bookmark”_
278
+ _Example: “Where is Mount Rainier?”_`;var Vte=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.
279
+ _Example: “Color points by sales amount”_
280
+ _Example: “Show population density with a color gradient”_
281
+ _Example: “Create a relationship map between height and depth”_
282
+ _Example: “Vary circle sizes according to population”_`;var yre=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).
283
+ 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.
284
+ _Example: “Only show stations where Brand is Shell”_
285
+ _Example: “Make Shell stations stand out on the map”_
286
+ _Example: “Gray out all stations that aren’t Shell”_
287
+ 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.
288
+ _Example: “How many features are there?”_
289
+ _Example: “What’s the average population?”_
290
+ _Example: “Which values are in the status field?”_
291
+
292
+ 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 $re=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
293
+
294
+ _Example: “Tell me about this map”_
295
+ _Example: “List all layers in this map”_
296
+ _Example: “List fields in protected areas layer”_
297
+ _Example: “What agents are available to me?”_
298
+ _Example: “What can you do?”_
299
+ _Example: “What can I ask”_
300
+
301
+ 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.
302
+
303
+ 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.
304
+ _Example: "Create a chart"_
305
+ _Example: "Create a table"_`;var Qre=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).
306
+ 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.
307
+ 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,
308
+ 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
309
+ 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.
310
+ This agent is designed to handle requests that manipulate the specific link chart.
311
+ 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,
312
+ and can alternatively use those queries to create a new link chart visualization from the results if requested.
313
+
314
+ Supported actions:
315
+ - **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.
316
+ - **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.
317
+ - **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.
318
+ - **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
319
+ - **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.
320
+ - **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.
321
+ - **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.
322
+
323
+ _example: "Change the layout to hierarchical-bottom-to-top"_
324
+ _example: "Apply radial-root-centric layout"_
325
+ _example: "Show nonspatial data"_
326
+ _example: "Hide nonspatial data"_
327
+ _example: "Turn off nonspatial visibility"_
328
+ _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
329
+ _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
330
+ _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
331
+ _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
332
+ _example: "Find all people who work for Microsoft and put them on a new link chart"_
333
+ _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
334
+ _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
335
+ _example: "Find all the products supplied by Supplier X and add them to my visualization"_
336
+ _example: "Expand the link chart from 'Entity D' to show its direct connections"_
337
+ _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
338
+ _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
339
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
340
+ _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
341
+ _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
342
+ _example: "Find John Smith and all people he has made phone calls to in the last year"_
343
+ _example: "What is the average age of all people who work for Esri?"_`;var PR=(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 l=t[a],c=e[a];r+=l*c,n+=l*l,o+=c*c}let s=Math.sqrt(n*o);if(s===0)return 0;let i=r/s;return Math.max(-1,Math.min(1,i))},qw=Vc,_r=za;var Pt=fe,Ww=yw,Kw=PR;var ou=()=>pn();var uf={};wu(uf,{JsonPatchError:()=>de,_areEquals:()=>Ga,applyOperation:()=>So,applyPatch:()=>Pi,applyReducer:()=>LR,deepClone:()=>$R,getValueByPointer:()=>cu,validate:()=>Vw,validator:()=>uu});var RR=(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)}})(),MR=Object.prototype.hasOwnProperty;function iu(t,e){return MR.call(t,e)}function au(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)iu(t,o)&&n.push(o);return n}function $e(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function lu(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 Ht(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Ha(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function su(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(su(t[e]))return!0}else if(typeof t=="object"){for(var n=au(t),o=n.length,s=0;s<o;s++)if(su(t[n[s]]))return!0}}return!1}function Hw(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(`
344
+ `)}var Va=(function(t){RR(e,t);function e(r,n,o,s,i){var a=this.constructor,l=t.call(this,Hw(r,{name:n,index:o,operation:s,tree:i}))||this;return l.name=n,l.index=o,l.operation=s,l.tree=i,Object.setPrototypeOf(l,a.prototype),l.message=Hw(r,{name:n,index:o,operation:s,tree:i}),l}return e})(Error);var de=Va,$R=$e,Ci={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=cu(r,this.path);n&&(n=$e(n));var o=So(r,{op:"remove",path:this.from}).removed;return So(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=cu(r,this.from);return So(r,{op:"add",path:this.path,value:$e(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Ga(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},NR={add:function(t,e,r){return lu(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:Ci.move,copy:Ci.copy,test:Ci.test,_get:Ci._get};function cu(t,e){if(e=="")return t;var r={op:"_get",path:e};return So(t,r),r.value}function So(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):uu(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=cu(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Ga(t,e.value),i.test===!1)throw new de("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 de("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=$e(t));var a=e.path||"",l=a.split("/"),c=t,d=1,m=l.length,f=void 0,g=void 0,b=void 0;for(typeof r=="function"?b=r:b=uu;;){if(g=l[d],g&&g.indexOf("~")!=-1&&(g=Ha(g)),o&&(g=="__proto__"||g=="prototype"&&d>0&&l[d-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&&(c[g]===void 0?f=l.slice(0,d).join("/"):d==m-1&&(f=e.path),f!==void 0&&b(e,0,t,f)),d++,Array.isArray(c)){if(g==="-")g=c.length;else{if(r&&!lu(g))throw new de("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);lu(g)&&(g=~~g)}if(d>=m){if(r&&e.op==="add"&&g>c.length)throw new de("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=NR[e.op].call(e,c,g,t);if(i.test===!1)throw new de("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(d>=m){var i=Ci[e.op].call(e,c,g,t);if(i.test===!1)throw new de("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(c=c[g],r&&d<m&&(!c||typeof c!="object"))throw new de("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Pi(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new de("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=$e(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=So(t,e[i],r,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function LR(t,e,r){var n=So(t,e);if(n.test===!1)throw new de("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function uu(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new de("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Ci[t.op]){if(typeof t.path!="string")throw new de("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new de('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 de("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 de("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")&&su(t.value))throw new de("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 de("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 de("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=Vw([i],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new de("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new de("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Vw(t,e,r){try{if(!Array.isArray(t))throw new de("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Pi($e(e),$e(t),r||!0);else{r=r||uu;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(o){if(o instanceof de)return o;throw o}}function Ga(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(!Ga(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],!Ga(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var mf={};wu(mf,{compare:()=>WR,generate:()=>df,observe:()=>qR,unobserve:()=>UR});var pf=new WeakMap,jR=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),DR=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function FR(t){return pf.get(t)}function zR(t,e){return t.observers.get(e)}function BR(t,e){t.observers.delete(e.callback)}function UR(t,e){e.unobserve()}function qR(t,e){var r=[],n,o=FR(t);if(!o)o=new jR(t),pf.set(t,o);else{var s=zR(o,e);n=s&&s.observer}if(n)return n;if(n={},o.value=$e(t),e){n.callback=e,n.next=null;var i=function(){df(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(){df(n),clearTimeout(n.next),BR(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 DR(e,n)),n}function df(t,e){e===void 0&&(e=!1);var r=pf.get(t.object);ff(r.value,t.object,t.patches,"",e),t.patches.length&&Pi(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function ff(t,e,r,n,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=au(e),i=au(t),a=!1,l=!1,c=i.length-1;c>=0;c--){var d=i[c],m=t[d];if(iu(e,d)&&!(e[d]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var f=e[d];typeof m=="object"&&m!=null&&typeof f=="object"&&f!=null&&Array.isArray(m)===Array.isArray(f)?ff(m,f,r,n+"/"+Ht(d),o):m!==f&&(a=!0,o&&r.push({op:"test",path:n+"/"+Ht(d),value:$e(m)}),r.push({op:"replace",path:n+"/"+Ht(d),value:$e(f)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+Ht(d),value:$e(m)}),r.push({op:"remove",path:n+"/"+Ht(d)}),l=!0):(o&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),a=!0)}if(!(!l&&s.length==i.length))for(var c=0;c<s.length;c++){var d=s[c];!iu(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+Ht(d),value:$e(e[d])})}}}function WR(t,e,r){r===void 0&&(r=!1);var n=[];return ff(t,e,n,"",r),n}var Sne=Object.assign({},uf,mf,{JsonPatchError:Va,deepClone:$e,escapePathComponent:Ht,unescapePathComponent:Ha});var VR=Tf`: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 gt(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
345
+ Available prompts:
346
+ ${Object.keys(t).join(`
347
+ `)}`);return await r[1]()}function hu(t){return t?.configurable?.context?.translations}function Zw(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 Xw(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var GR=p.object({needsContext:p.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:p.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),Gw=t=>t?.signal?.aborted??!1,Qw=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 JR(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">&#91;$1&#93;</a></sup>')}function ZR(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function Yw(t){let e=(t??"").trim();if(!e)return"en";let r=e.split(/[-_]/)[0]?.toLowerCase();return r?r.slice(0,2):"en"}function XR(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,l,c)=>{let d=c.slice(0,l);return/<img[^>]*alt\s*=\s*["'][^"']*$/i.test(d)?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 QR(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function eb(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function yf(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 YR=t=>new Promise(e=>setTimeout(e,t));async function e0(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 gt(Qw,"transformQuery"),i=await _r({promptText:s,modelTier:"advanced",temperature:0,schema:GR,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return i.rewrittenQuery.trim()}catch{}return r}var t0=B.Root({...ou(),solutionResponse:B({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:B({reducer:(t,e)=>e??null,default:()=>null}),conversationId:B({reducer:(t,e)=>e??t,default:()=>null})}),r0=()=>new He(t0).addNode("initializeAgent",o0).addNode("askSolutionsQuestions",n0).addEdge(We,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",le),tb=async(t,e,r,n)=>{if(!t)return;let o=eb(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:Yw(r),use_llm:!1}}}}};n&&(s.conversationId=n),yf(s,o,e??"")},n0=async(t,e)=>{if(Gw(e))return{};let r=hu(e),n=t.documentSkillUrl,o=[],s=await e0(t,e);await Pt({text:r.agentProgress.explorerAgentSearching},e);let i=await yf({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:Yw(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},l="",c=async d=>{let m=d.context?.results?.[0]?.reply??"";if(m!==""){let g=JR(m),b=ZR(g),_=XR(b,e);l=_.source,o=[...o,..._.allMatches.filter(x=>!o.some(O=>O.solution.id===x.solution.id))]}let f=d.context?.results?.[0]?.status?.currentStatusStep;if(f){let g="";f===1?g=r.agentProgress.explorerAgentReading:f===2?g=r.agentProgress.explorerAgentReviewing:f===3&&(g=r.agentProgress.explorerAgentPreparing),await Pt({text:g},e)}};for(await c(i);a.hasMore;){if(Gw(e))return{};await YR(500),i=await yf({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 c(i)}return eb(e?.configurable?.context.portal)&&tb(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?Xw(o[0].solution.id):Zw(o)),{outputMessage:l,summary:l,status:"success",solutionResponse:a,conversationId:a.conversationId}},o0=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=QR(e.configurable.context.portal)),{documentSkillUrl:r}};await gt(Qw,"solutions_explorer_description");var rb=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"},s0=t=>{let e=rb(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)}},i0=t=>rb(t)==="human",a0=(t,e=3)=>t.filter(r=>i0(r)).slice(-e).map(s0),l0=(t,e=" ")=>a0(t).map(r=>r.content).join(e).trim(),c0={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?"},u0={builderMessages:c0},mu=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],l=this.response.items.find(c=>c.id===i);if(l){l.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(l=>l.id===s.id);if(a&&a.type!==s.type)if(this.newDesign){let l=a.type;a.type=s.type,this._logAutoFix(`Layer '${s.id}' type '${l}' 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=dl(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=pl(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=dl(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=pl(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=dl(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=pl(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 l=s.name;s.name=this._makeUniqueName(s.name,o),this._logAutoFix(`Layer '${e.name}' field '${l}' 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 l=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${l}' 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 l=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${l}' 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(um.has(e.name.toLowerCase()))if(this.newDesign){let l=e.name;e.name=this._getUniqueTruncatedFieldName(l,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${l}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(dm.has(e.name.toLowerCase()))if(this.newDesign){let l=e.name;e.name=this._getUniqueTruncatedFieldName(l,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${l}' 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 l=e.type;a==="globalid"?e.type="guid":a==="oid"?e.type="integer":e.type="string",this._logAutoFix(`Field '${e.name}' had unsupported type '${l}'. 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 l=Math.max(...e.choiceList.map(c=>c.length));l>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 ${l} characters. Auto-fixing to ${l}.`),e.length=l):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${l} 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(!fm(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}`,l=Math.max(1,n-a.length);s=`${o.slice(0,l)}${a}`,i+=1}return s}_sanitizeItemName(e,r=t.NAME_MAX_LENGTH){let n=(e??"").replace(new RegExp(pm.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}},d0=p.object({key:p.string().describe("Stable key identifier for the string."),value:p.string().describe("Display value for the string."),description:p.string().describe("Explanation of where/how the string is used.")}),p0=p.object({id:p.string().describe("ArcGIS item id (32 hex characters)."),title:p.string().describe("Item title."),description:p.string().describe("Item description."),type:p.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.")}),Jw=p.object({name:p.string().describe("Field name."),type:p.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:p.string().describe("Field alias for display."),description:p.string().describe("Field description."),choiceList:p.array(p.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:p.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),f0=p.object({id:p.number().int().describe("Layer/table id within the feature service."),type:p.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),typeMutable:p.boolean().describe("Indicates whether the layer type can be changed."),name:p.string().describe("Layer/table name."),description:p.string().describe("Layer/table description."),customFields:p.array(Jw).describe("User/business fields specific to the solution."),requiredFields:p.array(Jw).describe("Fields required for solution functionality (e.g., relationship keys).")}),m0=p.object({itemId:p.string().describe("ArcGIS item id for the feature layer."),addLayers:p.boolean().describe("Indicates whether new layers can be added during solution design."),layers:p.array(f0)}),wf=p.object({response:p.string().describe("Conversational response to the user's query."),solution:p.object({itemId:p.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:p.string().describe("Title of the solution."),description:p.string().describe("Description of the solution."),tags:p.array(p.string()).describe("Keywords/tags associated with the solution."),strings:p.array(d0).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:p.array(p0).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:m0.describe("Primary feature layer item and its schema/layers/tables details.")}),h0=p.object({op:p.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:p.string().describe("RFC 6901 JSON Pointer to the target location."),value:p.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:p.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.")}),g0=p.object({response:p.string().describe("Conversational response describing the accepted design changes."),patches:p.array(h0).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),y0=p.object({response:p.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),_0=p.object({assistantResponse:p.string().describe("Natural-language response for the user."),isValidUpdate:p.boolean().describe("True only when the request is in scope for supported design updates.")}),w0=p.object({matchedTitles:p.array(p.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),b0=p.object({templateId:p.string().min(1).describe("Template id from the available template list."),confidence:p.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:p.string().min(1).describe("Short action\u2011oriented description of the template in the user's use case/workflow, starting with a verb.")}),A0=p.object({assistantResponse:p.string().nullable().describe("Natural-language response for the user."),isValidUseCase:p.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:p.array(b0).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),x0=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
348
+ `):"No validation errors were provided.",v0=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await _r({promptText:await gt(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:y0,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:x0(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},bf=t=>t in Ro,I0=5,S0=.8,T0=.5,E0="Web Mapping Application",O0="Embeddings",du=null,gf=null,pu=null,fu=null,k0="Build",To=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)}),C0=u0.builderMessages,pe=t=>t?.signal?.aborted??!1,Se=(t,e,r)=>hu(e)?.builderMessages?.[t]??C0[t],nb=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},P0=async(t,e,r)=>{if(!t)return null;let n=`type:"${E0}" AND typekeywords:${O0} AND group:${t}`;return(await Iu({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function R0(t,e,r,n){try{let o=await P0(t,e,r);if(!o||pe(n))return null;let s=new HR({id:o.id});return await s.load(),pe(n)?null:await s.fetchData("json")}catch{return null}}var M0=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${k0} AND group:${t}`;return(await Iu({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},$0=async(t,e,r)=>{try{let n=await Ff(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}},Eo=(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},ob=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Nu({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},Af=async t=>{if(gf){Object.entries(gf).forEach(([i,a])=>{Ro[i]&&(Ro[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=ib(t),n=ab(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await M0(r,e,n),s={};pe(t)||(await Promise.all(o.map(async i=>{let a=i.properties?.templateInfo;if(!a||typeof a!="object")return;let l=a.id;if(typeof l!="string"||s[l])return;let c=await $0(i.id,e,n);if(!c||pe(t))return;let{buildSolution:d,params:m}=c;if(typeof d=="object"&&d!==null&&"solution"in d){let g=d.solution;g.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,g.item=i}let f={...a,buildSolution:d};s[l]=Eo(new Nu(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(d),params:m?structuredClone(m):null}),Ro[l]={...a,initialTemplate:s[l]}})),gf=s)},sb=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},ib=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},ab=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},N0=async t=>{await Promise.all([cb(t),Af(t)])},lb=async t=>{let e=sb(t);(!pu||e&&e!==fu)&&(fu=e??fu,pu=N0(t).catch(r=>{throw pu=null,fu=null,r})),await pu};async function cb(t){if(du)return du;let e=ib(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=ab(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new KR(n?{url:n}:void 0).load(),pe(t))return null;let o=sb(t)??void 0,s=await R0(e,o,r,t);return pe(t)?null:s?(du=s.items,du):null}var L0=()=>Object.entries(Ro).map(([t,e])=>`ID: ${t}
349
+ Label: ${e.label}
350
+ Description: ${e.description}`).join(`
351
+
352
+ `),j0=t=>{let e=t?.configurable?.context?.solutionDesignJson;if(typeof e!="string"||!e.trim())return null;try{let r=JSON.parse(e),n=Eo({response:"",...r},{itemId:r?.solution?.itemId??null}),o=wf.safeParse(n);if(!o.success)return null;let{response:s,...i}=o.data,a=r.templateId,l=typeof a=="string"&&bf(a)?a:null;return Eo(i,{sourceBuildSolution:r.sourceBuildSolution,templateId:l,params:r.params??null})}catch{return null}},D0=B.Root({...ou(),templateDescription:B({reducer:(t,e)=>typeof e=="string"||e===null?e:t??null,default:()=>null}),currentDesign:B({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),assessment:B({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),selectedTemplate:B({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),updateAssessment:B({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),existingMatches:B({reducer:(t=[],e)=>e===void 0?t:e??[],default:()=>[]}),continueBuilding:B({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null})}),F0=(t,e)=>{if(pe(e))return{};let r=j0(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},z0=async(t,e)=>{if(pe(e))return{};await Pt({text:Se("understandingRequest",e)},e),await lb(e);let r=t.agentExecutionContext.userRequest,n=L0(),o=t.agentExecutionContext.messages.slice(-11),s=await _r({promptText:await gt(To,"assessBuildRequest"),modelTier:"advanced",temperature:0,schema:A0,messages:o,inputVariables:{query:r,availableTemplates:n}}),i=s.matchedTemplates.filter(m=>bf(m.templateId)),a={...s,matchedTemplates:i},[l,c]=i,d=l&&l.confidence>=S0&&(c===void 0||l.confidence-c.confidence>=T0)?l.templateId:null;return{assessment:a,selectedTemplate:d,existingMatches:[],continueBuilding:null}},B0=t=>{let e=t.assessment?.assistantResponse??"";return{outputMessage:e,summary:e,status:"success"}},U0=async(t,e)=>{if(pe(e))return{};let{currentDesign:r}=t;if(!r)return{updateAssessment:{assistantResponse:"",isValidUpdate:!0}};await Pt({text:Se("understandingRequest",e)},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);return{updateAssessment:await _r({promptText:await gt(To,"assessUpdateRequest"),modelTier:"advanced",temperature:0,schema:_0,messages:o,inputVariables:{currentDesign:JSON.stringify(ju(r)),query:n}})}},q0=(t,e)=>{let r=t.updateAssessment?.assistantResponse??Se("applyChangeFailed",e);return{outputMessage:r,summary:r,status:"success"}},W0=(t,e)=>{if(pe(e))return{};let{hitlResponse:r}=e.configurable,n="selectTemplate",o=t.assessment?.matchedTemplates.filter(l=>bf(l.templateId))??[],s=o.map(l=>`${l.templateDescription}`);if(r?.agentId!=="solutionBuilder"||r.id!==n){let l={agentId:"solutionBuilder",id:n,kind:"singleSelection",message:Se("selectTemplatePrompt",e),metadata:[...s]};throw new Za(l)}let i=String(r.payload??""),a=s.findIndex(l=>l===i);return{selectedTemplate:(a>=0?o[a]:void 0)?.templateId??o[0]?.templateId??null}},K0=async(t,e)=>{if(pe(e))return{};await Pt({text:Se("searchingExistingSolutions",e)},e);let r=t.agentExecutionContext.userRequest,n=l0(t.agentExecutionContext.messages)||r,o=await cb(e);if(pe(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 Ww([n]);if(pe(e))return{};let i=o.map(d=>({solution:d,score:Kw(s,d.embedding)}));i.sort((d,m)=>m.score-d.score);let a=i.slice(0,I0);if(!a.length)return{existingMatches:[]};let l=a.map(({solution:d})=>`${d.title}
353
+ Snippet: ${d.snippet}
354
+ Description: ${d.description}`).join(`
355
+
356
+ `),c=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await _r({promptText:await gt(To,"findExistingSolution"),modelTier:"fast",temperature:0,schema:w0,messages:c,inputVariables:{query:r,candidates:l}})).matchedTitles.map(d=>a.find(({solution:m})=>m.title===d)).filter(d=>d!==void 0)}},H0=(t,e)=>{if(pe(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?Xw(r[0].solution.id):Zw(r);let a=Se("existingSolutionMatch",e),l=[Se("continueBuildingYes",e),Se("continueBuildingNo",e)],c={agentId:"solutionBuilder",id:o,kind:"singleSelection",message:a,metadata:l};throw new Za(c)}let s=String(n.payload??"").trim(),i=Se("continueBuildingNo",e);return{continueBuilding:s!==i}},V0=(t,e)=>{let r=Se("continueBuildingDeclined",e);return{outputMessage:r,summary:r,status:"success"}},ub=async(t,e)=>{if(pe(e))return{};if(await lb(e),pe(e))return{};let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await Pt({text:Se("creatingDesign",e)},e);let o=Li(t.selectedTemplate);if(o?.initialTemplate||(await Af(e),o=Li(t.selectedTemplate)),pe(e))return{};if(!o?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let s=Eo(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 _r({promptText:await gt(To,"designSolution"),modelTier:"advanced",temperature:0,schema:wf,messages:i,inputVariables:{currentDesign:JSON.stringify(Lu(s)),templateInstructions:o.instructions,query:n}});if(await Pt({text:" of design solution 1"},e),pe(e))return{};let{response:l,featureLayer:c,...d}=a,m=Du(c,s.featureLayer),f=Eo({...d,featureLayer:m},{itemId:s?.solution?.itemId,sourceBuildSolution:s.sourceBuildSolution,templateId:t.selectedTemplate??null,params:s.params??null}),g=new mu(f,o.initialTemplate);if(!g.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:g.issues,llmResponse:a}),{outputMessage:Se("createDesignFailed",e)};let b=f.sourceBuildSolution,_=ob(f,b);if(!_.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:_.error,llmResponse:a,design:f});let x=Se("createDesignFailed",e);return{outputMessage:x,summary:x,status:"success"}}return pe(e)?{}:(nb(f),{outputMessage:l,summary:l,status:"success",currentDesign:f})},G0=async(t,e)=>{if(pe(e))return{};let{currentDesign:r}=t;if(!r)return ub(t,e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);await Pt({text:Se("updatingDesign",e)},e);let s;try{s=await _r({promptText:await gt(To,"updateDesign"),modelTier:"advanced",temperature:0,schema:g0,messages:o,inputVariables:{currentDesign:JSON.stringify(ju(r)),query:n}})}catch(k){console.warn("[SolutionBuilder] updateDesign structured prompt failed:",k);let D=Se("applyChangeFailed",e);return{outputMessage:D,summary:D,status:"success"}}let{response:i,patches:a}=s;if(!a||a.length===0)return{outputMessage:i,summary:i,status:"success"};let l=k=>{try{return JSON.parse(k)}catch{let D=k.replace(/[\u0000-\u001F]/g,$=>{switch($){case"\b":return"\\b";case"\f":return"\\f";case`
357
+ `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+$.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(D)}catch{return k}}},c=[...a.map(k=>({op:k.op,path:k.path.replace(/\/+$/,""),...k.value!=null&&k.value!==""?{value:l(k.value)}:{},...k.from!=null&&k.from!==""?{from:k.from}:{}}))].sort((k,D)=>k.op!=="remove"||D.op!=="remove"?0:D.path.localeCompare(k.path,void 0,{numeric:!0})),d=structuredClone(Lu(r));try{Pi(d,c,!0)}catch(k){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:k,llmResponse:s,patches:c,patchTarget:d});let D=Se("applyChangeFailed",e);return{outputMessage:D,summary:D,status:"success"}}let m=Eo({response:"",...d},{itemId:r.solution?.itemId??null}),f=wf.safeParse(m);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:m});let k=Se("applyChangeFailed",e);return{outputMessage:k,summary:k,status:"success"}}let{response:g,featureLayer:b,..._}=f.data,x=Du(b,r.featureLayer),O=Eo({..._,featureLayer:x},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),y=Li(t.selectedTemplate);if(y?.initialTemplate||(await Af(e),y=Li(t.selectedTemplate)),pe(e))return{};if(!y?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let S=new mu(O,y.initialTemplate,!1);if(!S.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:S.issues,llmResponse:s,patchedDesign:O});let k=await v0({query:n,validationIssues:S.issues,recentMessages:o,fallbackMessage:Se("applyChangeFailed",e),promptModules:To});return{outputMessage:k,summary:k,status:"success"}}let I=O.sourceBuildSolution,R=ob(O,I);if(!R.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:R.error,llmResponse:s,design:O});let k=Se("applyChangeFailed",e);return{outputMessage:k,summary:k,status:"success"}}return pe(e)?{}:(nb(O),{outputMessage:i,summary:i,status:"success",currentDesign:O})},J0=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",Z0=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",X0=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",Q0=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",Y0=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",eM=()=>new He(D0).addNode("syncCurrentDesignFromContext",F0).addNode("assessBuildRequest",z0).addNode("assessUpdateRequest",U0).addNode("invalidBuildExit",B0).addNode("invalidUpdateExit",q0).addNode("selectTemplateHIL",W0).addNode("findExistingSolutions",K0).addNode("confirmContinueBuildingHIL",H0).addNode("declineContinueBuildingExit",V0).addNode("designSolution",ub).addNode("updateDesign",G0).addEdge(We,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",J0,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",Z0,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",X0,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",le).addEdge("invalidUpdateExit",le).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Q0,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",Y0,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",le).addEdge("designSolution",le).addEdge("updateDesign",le);await gt(To,"description");var tM=p.object({tool:p.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:p.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:p.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),gu=t=>t?.signal?.aborted??!1,xf=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)}),rM=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}},vf=(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)},db=B.Root({...ou(),selectedTool:B({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:B({reducer:(t,e)=>e??null,default:()=>null})}),nM=async(t,e)=>{if(gu(e))return{};let r=hu(e);await Pt({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=rM(e),a=await gt(xf,"classifyIntent"),l=await _r({promptText:a,modelTier:"advanced",temperature:0,schema:tM,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:l.tool,intentRationale:l.rationale}},oM=async(t,e)=>{if(gu(e))return{};let r=await r0().compile().invoke(t,e);return vf(e,"explorer"),r},sM=async(t,e)=>{if(gu(e))return{};let r=await eM().compile().invoke(t,e);return vf(e,"builder"),r},iM=async(t,e)=>{if(gu(e))return{};let r=hu(e),n=t.agentExecutionContext.userRequest;await Pt({text:r?.executingSolutionsAssistantAgent},e);let o=await gt(xf,"assistantResponse"),s=t.agentExecutionContext.messages.slice(-11),i=await qw({promptText:o,modelTier:"advanced",temperature:0,messages:s,inputVariables:{query:n}});return vf(e,"assistant"),{outputMessage:i,summary:i,status:"success"}},aM=t=>t.selectedTool??"other",lM=()=>new He(db).addNode("classifyIntent",nM).addNode("routeToExplorer",oM).addNode("routeToBuilder",sM).addNode("assistantResponse",iM).addEdge(We,"classifyIntent").addConditionalEdges("classifyIntent",aM,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",le).addEdge("routeToBuilder",le).addEdge("assistantResponse",le),cM=await gt(xf,"description"),uM={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:cM,createGraph:lM,workspace:db},dM="https://links.esri.com/solutions/agol-organizational-account",pM="https://links.esri.com/solutions/configure-assistants",_f=class extends $f{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=Lf({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=Rf(),this._configContextConsumer=vu({context:jf,subscribe:!0,callback:e=>{e?.portalURL&&(hf.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=vu({context:Df,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=zf(this._chatStartTime);this._telemetry?.logEvent({category:Ri.ASSISTANT,action:"Chat",dimensions:[n],metrics:[o]}),this._chatStartTime=null}},this.closeAssistant=Au(),this.assistantProcessing=Au(),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??"",l=i?.userMessage??i?.userMessage??s??o??"";this._sendFeedback(r.content,l,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=VR}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(){hf.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(hf.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||(tb(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 br`<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??xu} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return br`<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">${mm(this._translations.noPermissionMessage.replace("{{orgUrl}}",dM).replace("{{configAI}}",pM))}</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)]),br`<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?br`${!this._isMobile&&br`<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:Ri.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&&br`<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??xu} .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)}} ${Mf(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:Ri.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=${uM} .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&&br`<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:Ri.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((d,m)=>m.id-d.id).find(d=>d.role==="user"&&d.id<=e.id)?.content||null,s=n.find(d=>typeof d=="string"&&d.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 l=a[1].trim(),c=a[2].trim();return{agentPicked:l,taskAssigned:c,userMessage:o}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};Nf("arcgis-solutions-assistant",_f);return _f},"config","identity/IdentityManager","portal/Portal","portal/Portal","request","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer","portal/Portal","portal/PortalItem",a,b)