@arcgis/portal-components 5.2.0-next.4 → 5.2.0-next.41

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 (207) hide show
  1. package/dist/cdn/2C475EKD.js +2 -0
  2. package/dist/cdn/3J46PXFF.js +3 -0
  3. package/dist/cdn/3MBOA5WF.js +2 -0
  4. package/dist/cdn/{GQFWFZXP.js → 3OBIA66A.js} +1 -1
  5. package/dist/cdn/3Z3ZPFGJ.js +2 -0
  6. package/dist/cdn/5NMFQE4U.js +2 -0
  7. package/dist/cdn/{7WZHZP6U.js → 63THOLAY.js} +9 -3
  8. package/dist/cdn/6AGZRMJC.js +2 -0
  9. package/dist/cdn/6DYBW2C6.js +2 -0
  10. package/dist/cdn/6RK4FBHZ.js +2 -0
  11. package/dist/cdn/6W2IHKCA.js +2 -0
  12. package/dist/cdn/7E5GJIZV.js +2 -0
  13. package/dist/cdn/AL57LV4E.js +2 -0
  14. package/dist/cdn/{LQ3DMZ3K.js → AXM6XCZD.js} +1 -1
  15. package/dist/cdn/AYR65LXN.js +65 -0
  16. package/dist/cdn/BUJPYZSX.js +2 -0
  17. package/dist/cdn/{DKBTJJMW.js → C7ZFXRPS.js} +1 -1
  18. package/dist/cdn/D76KMXZD.js +2 -0
  19. package/dist/cdn/DFTUMKSN.js +3 -0
  20. package/dist/cdn/DZJMNZY6.js +451 -0
  21. package/dist/cdn/EI6BAXCQ.js +2 -0
  22. package/dist/cdn/EVMYGWC6.js +637 -0
  23. package/dist/cdn/FXIP4QXJ.js +2 -0
  24. package/dist/cdn/GE75KDIM.js +2 -0
  25. package/dist/cdn/GJTJLK6T.js +2 -0
  26. package/dist/cdn/GKOXTQHB.js +2 -0
  27. package/dist/cdn/GQMPPCEL.js +2 -0
  28. package/dist/cdn/GXJU3U7U.js +2 -0
  29. package/dist/cdn/HMBSJR37.js +2 -0
  30. package/dist/cdn/HZ5W3DBR.js +2 -0
  31. package/dist/cdn/{V2EOXGK2.js → I234NUZ5.js} +1 -1
  32. package/dist/cdn/I5HSJRM3.js +2 -0
  33. package/dist/cdn/IBP5XPD5.js +2 -0
  34. package/dist/cdn/IC65R4QE.js +2 -0
  35. package/dist/cdn/IHSJ4MKS.js +2 -0
  36. package/dist/cdn/IJ3CLFAU.js +22 -0
  37. package/dist/cdn/IWUJRI4G.js +2 -0
  38. package/dist/cdn/{ZTHTFEYA.js → IXVR3KMC.js} +1 -1
  39. package/dist/cdn/{QNUYUNEY.js → JS45DWQ3.js} +1 -1
  40. package/dist/cdn/{DHHSKOUY.js → JV23HJTE.js} +1 -1
  41. package/dist/cdn/{LAFNDBTQ.js → JYIPREIH.js} +1 -1
  42. package/dist/cdn/JZKBUYPV.js +2 -0
  43. package/dist/cdn/KM5XGRXL.js +2 -0
  44. package/dist/cdn/{3PAHY5KA.js → KNRJ3WXR.js} +1 -1
  45. package/dist/cdn/L4DRNGOL.js +2 -0
  46. package/dist/cdn/{F6V7MLPY.js → L6KBBJEC.js} +1 -1
  47. package/dist/cdn/NJ2WDAJM.js +2 -0
  48. package/dist/cdn/NWIIOJEG.js +2 -0
  49. package/dist/cdn/{53MSUMA3.js → OT4PZJNB.js} +17 -1
  50. package/dist/cdn/POIXW2OA.js +2 -0
  51. package/dist/cdn/QE4CNVDQ.js +34 -0
  52. package/dist/cdn/{AQWTJKUH.js → QKCV7CY2.js} +10 -8
  53. package/dist/cdn/RKNDXSVK.js +2 -0
  54. package/dist/cdn/SLTFLCVR.js +99 -0
  55. package/dist/cdn/SUPKZF5M.js +2 -0
  56. package/dist/cdn/{GT26WGJS.js → SXZRHHXC.js} +1 -1
  57. package/dist/cdn/TJAX7J4T.js +2 -0
  58. package/dist/cdn/{DXCPWJU4.js → TKCE4WYE.js} +1 -1
  59. package/dist/cdn/U3FVMN32.js +2 -0
  60. package/dist/cdn/UZLQALHY.js +2 -0
  61. package/dist/cdn/{RR4BIAPA.js → V4EYW3O6.js} +1 -1
  62. package/dist/cdn/{74XFARCV.js → VW7DSKPH.js} +1 -1
  63. package/dist/cdn/W2SYL7IJ.js +71 -0
  64. package/dist/cdn/{W6PSG4GX.js → W4FGRGLV.js} +10 -5
  65. package/dist/cdn/{SYJSVUUR.js → W4SAWMXS.js} +1 -1
  66. package/dist/cdn/WBZLQZYR.js +134 -0
  67. package/dist/cdn/WGZZB2DJ.js +2 -0
  68. package/dist/cdn/WO23VQK3.js +2 -0
  69. package/dist/cdn/{2UUZHENH.js → WSNLUGEP.js} +1 -1
  70. package/dist/cdn/WSWHK6LB.js +2 -0
  71. package/dist/cdn/{WOZDQW3S.js → WX65MRDH.js} +1 -1
  72. package/dist/cdn/XEK22IDA.js +2 -0
  73. package/dist/cdn/ZPIXIG3Z.js +2 -0
  74. package/dist/cdn/ZVFNCDG5.js +2 -0
  75. package/dist/cdn/assets/portal-browser/t9n/messages.en.json +1 -0
  76. package/dist/cdn/assets/portal-group-badges/t9n/messages.en.json +1 -0
  77. package/dist/cdn/assets/portal-group-card/t9n/messages.en.json +1 -0
  78. package/dist/cdn/assets/portal-item-type/icons/parquetfeaturelayer16.svg +1 -0
  79. package/dist/cdn/assets/portal-item-type/icons/parquetfeaturelayer32.svg +1 -0
  80. package/dist/cdn/assets/portal-item-type/icons/storymapframe16.svg +1 -0
  81. package/dist/cdn/assets/portal-item-type/icons/storymapframe32.svg +1 -0
  82. package/dist/cdn/assets/portal-item-type/t9n/messages.en.json +1 -1
  83. package/dist/cdn/assets/portal-user-popup/t9n/messages.en.json +1 -0
  84. package/dist/cdn/index.js +1 -1
  85. package/dist/cdn/main.css +1 -1
  86. package/dist/chunks/dom.js +36 -0
  87. package/dist/chunks/functionalities.js +5 -4
  88. package/dist/chunks/groups.js +7 -83
  89. package/dist/chunks/item2.js +86 -0
  90. package/dist/chunks/portal.js +48 -8
  91. package/dist/chunks/store.js +18 -0
  92. package/dist/chunks/ui.js +10 -0
  93. package/dist/chunks/user2.js +26 -25
  94. package/dist/components/arcgis-portal-ai-assistant/agents/types.d.ts +11 -2
  95. package/dist/components/arcgis-portal-ai-assistant/customElement.d.ts +4 -2
  96. package/dist/components/arcgis-portal-ai-assistant/customElement.js +797 -488
  97. package/dist/components/arcgis-portal-ai-assistant-interrupt/customElement.js +10 -10
  98. package/dist/components/arcgis-portal-browser/customElement.d.ts +235 -0
  99. package/dist/components/arcgis-portal-browser/customElement.js +201 -0
  100. package/dist/components/arcgis-portal-browser/index.d.ts +1 -0
  101. package/dist/components/arcgis-portal-browser/index.js +6 -0
  102. package/dist/components/arcgis-portal-browser/utils/store.d.ts +31 -0
  103. package/dist/components/arcgis-portal-browser/utils/types.d.ts +18 -0
  104. package/dist/components/arcgis-portal-browser-actions/customElement.d.ts +187 -0
  105. package/dist/components/arcgis-portal-browser-actions/customElement.js +70 -0
  106. package/dist/components/arcgis-portal-browser-actions/index.d.ts +1 -0
  107. package/dist/components/arcgis-portal-browser-actions/index.js +6 -0
  108. package/dist/components/arcgis-portal-browser-actions/types.d.ts +9 -0
  109. package/dist/components/arcgis-portal-browser-filter/customElement.d.ts +226 -0
  110. package/dist/components/arcgis-portal-browser-filter/customElement.js +32 -0
  111. package/dist/components/arcgis-portal-browser-filter/index.d.ts +1 -0
  112. package/dist/components/arcgis-portal-browser-filter/index.js +4 -0
  113. package/dist/components/arcgis-portal-browser-filter-date/customElement.d.ts +233 -0
  114. package/dist/components/arcgis-portal-browser-filter-date/customElement.js +117 -0
  115. package/dist/components/arcgis-portal-browser-filter-date/index.d.ts +1 -0
  116. package/dist/components/arcgis-portal-browser-filter-date/index.js +5 -0
  117. package/dist/components/arcgis-portal-browser-filter-status/customElement.d.ts +193 -0
  118. package/dist/components/arcgis-portal-browser-filter-status/customElement.js +56 -0
  119. package/dist/components/arcgis-portal-browser-filter-status/index.d.ts +1 -0
  120. package/dist/components/arcgis-portal-browser-filter-status/index.js +5 -0
  121. package/dist/components/arcgis-portal-browser-filters/customElement.d.ts +7 -0
  122. package/dist/components/arcgis-portal-browser-filters/customElement.js +29 -0
  123. package/dist/components/arcgis-portal-browser-filters/index.d.ts +1 -0
  124. package/dist/components/arcgis-portal-browser-filters/index.js +2 -0
  125. package/dist/components/arcgis-portal-browser-pagination/customElement.d.ts +194 -0
  126. package/dist/components/arcgis-portal-browser-pagination/customElement.js +51 -0
  127. package/dist/components/arcgis-portal-browser-pagination/index.d.ts +1 -0
  128. package/dist/components/arcgis-portal-browser-pagination/index.js +2 -0
  129. package/dist/components/arcgis-portal-browser-search/customElement.d.ts +195 -0
  130. package/dist/components/arcgis-portal-browser-search/customElement.js +65 -0
  131. package/dist/components/arcgis-portal-browser-search/index.d.ts +1 -0
  132. package/dist/components/arcgis-portal-browser-search/index.js +3 -0
  133. package/dist/components/arcgis-portal-browser-sort/customElement.d.ts +196 -0
  134. package/dist/components/arcgis-portal-browser-sort/customElement.js +93 -0
  135. package/dist/components/arcgis-portal-browser-sort/index.d.ts +1 -0
  136. package/dist/components/arcgis-portal-browser-sort/index.js +9 -0
  137. package/dist/components/arcgis-portal-browser-sort/utils.d.ts +3 -0
  138. package/dist/components/arcgis-portal-browser-top-bar/customElement.d.ts +184 -0
  139. package/dist/components/arcgis-portal-browser-top-bar/customElement.js +51 -0
  140. package/dist/components/arcgis-portal-browser-top-bar/index.d.ts +1 -0
  141. package/dist/components/arcgis-portal-browser-top-bar/index.js +3 -0
  142. package/dist/components/arcgis-portal-browser-view/customElement.d.ts +21 -0
  143. package/dist/components/arcgis-portal-browser-view/customElement.js +30 -0
  144. package/dist/components/arcgis-portal-browser-view/index.d.ts +1 -0
  145. package/dist/components/arcgis-portal-browser-view/index.js +5 -0
  146. package/dist/components/arcgis-portal-group-badges/customElement.d.ts +102 -0
  147. package/dist/components/arcgis-portal-group-badges/customElement.js +50 -0
  148. package/dist/components/arcgis-portal-group-badges/index.d.ts +1 -0
  149. package/dist/components/arcgis-portal-group-badges/index.js +3 -0
  150. package/dist/components/arcgis-portal-group-badges/types.d.ts +3 -0
  151. package/dist/components/arcgis-portal-group-card/customElement.d.ts +167 -0
  152. package/dist/components/arcgis-portal-group-card/customElement.js +183 -0
  153. package/dist/components/arcgis-portal-group-card/index.d.ts +1 -0
  154. package/dist/components/arcgis-portal-group-card/index.js +8 -0
  155. package/dist/components/arcgis-portal-group-thumbnail/customElement.d.ts +32 -0
  156. package/dist/components/arcgis-portal-group-thumbnail/customElement.js +153 -0
  157. package/dist/components/arcgis-portal-group-thumbnail/index.d.ts +1 -0
  158. package/dist/components/arcgis-portal-group-thumbnail/index.js +3 -0
  159. package/dist/components/arcgis-portal-item-type/customElement.d.ts +2 -0
  160. package/dist/components/arcgis-portal-item-type/customElement.js +45 -37
  161. package/dist/components/arcgis-portal-mentionable-text-area/customElement.js +1 -1
  162. package/dist/components/arcgis-portal-replacement-item-redirect/customElement.js +53 -42
  163. package/dist/components/arcgis-portal-user-popup/customElement.d.ts +111 -0
  164. package/dist/components/arcgis-portal-user-popup/customElement.js +224 -0
  165. package/dist/components/arcgis-portal-user-popup/index.d.ts +1 -0
  166. package/dist/components/arcgis-portal-user-popup/index.js +5 -0
  167. package/dist/components/arcgis-portal-voice-input/customElement.d.ts +1 -1
  168. package/dist/docs/api.json +1 -1
  169. package/dist/docs/docs.json +1 -1
  170. package/dist/docs/vscode.html-custom-data.json +1 -1
  171. package/dist/docs/web-types.json +1 -1
  172. package/dist/index.d.ts +122 -2
  173. package/dist/loader.js +19 -4
  174. package/dist/types/group.d.ts +13 -13
  175. package/dist/types/item.d.ts +77 -2
  176. package/dist/types/lumina.d.ts +93 -1
  177. package/dist/types/preact.d.ts +108 -1
  178. package/dist/types/react.d.ts +123 -1
  179. package/dist/types/search.d.ts +27 -0
  180. package/dist/types/stencil.d.ts +93 -1
  181. package/dist/types/tracking.d.ts +10 -0
  182. package/dist/types/user.d.ts +2 -2
  183. package/package.json +11 -11
  184. package/dist/cdn/5DPWJ7DI.js +0 -2
  185. package/dist/cdn/5VSDGPHH.js +0 -2
  186. package/dist/cdn/72N3KAXN.js +0 -2
  187. package/dist/cdn/ANPXRYLV.js +0 -5
  188. package/dist/cdn/B7633S2A.js +0 -422
  189. package/dist/cdn/BEHLBKKM.js +0 -2
  190. package/dist/cdn/CI5ENGVT.js +0 -2
  191. package/dist/cdn/EVDOPN3G.js +0 -54
  192. package/dist/cdn/G47ZZQYL.js +0 -2
  193. package/dist/cdn/GAHILDQF.js +0 -45
  194. package/dist/cdn/GHQ3ZW4U.js +0 -2
  195. package/dist/cdn/GNOZCQ34.js +0 -2
  196. package/dist/cdn/JNRN6DTV.js +0 -2
  197. package/dist/cdn/K3HS2LQ7.js +0 -2
  198. package/dist/cdn/KEKBRUUC.js +0 -2
  199. package/dist/cdn/N6G6Z7BF.js +0 -516
  200. package/dist/cdn/OQDPULPD.js +0 -2
  201. package/dist/cdn/RNLVNDGG.js +0 -2
  202. package/dist/cdn/SM4GWLRA.js +0 -66
  203. package/dist/cdn/TMYTUOSS.js +0 -2
  204. package/dist/cdn/YG5YYL6X.js +0 -2
  205. package/dist/cdn/YIMNOUTF.js +0 -2
  206. package/dist/cdn/YL7PGYWC.js +0 -5
  207. package/dist/cdn/YMPTDKT6.js +0 -2
@@ -0,0 +1,637 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
+ import a from"./HMBSJR37.js";import"./6W2IHKCA.js";import{a as pu,b as mu,d as fu,e as hu,f as gu}from"./6AGZRMJC.js";import{a as To,b as Rl}from"./I234NUZ5.js";import{a as Ml}from"./AXM6XCZD.js";import"./IBP5XPD5.js";import"./D76KMXZD.js";import{J as Io,K as vo,L as Pl,R as Ol,h as Sl,j as Dr,m as kl,v as Cl,y as El}from"./JV23HJTE.js";import{$ as Ja,Aa as D,Ba as I,Ca as Qa,Da as He,Db as au,Ea as Br,Fa as Ne,Ga as kt,Ha as Je,Ia as ks,J as zl,Ja as Yl,K as it,Ka as Xl,L as jl,La as Cs,Lb as Ct,M as bs,Ma as Ya,Mb as ti,N as Ga,Na as Kr,O as Wa,Oa as Xa,Ob as Ee,P as xs,Pa as eu,Q as Va,Qa as tu,Qb as Po,R as ko,Ra as ru,S as F,Sa as nu,Sb as Os,T as Ha,Ta as Eo,U as Ll,Ua as Es,Ub as Oo,V as $,Va as ou,Vb as Ms,W as vt,Wa as Gr,Wb as _e,X as lt,Xa as Wr,Y as As,Ya as v,Z as Dl,Za as j,_ as Fl,_a as ei,a as ge,aa as ke,b as L,ba as Is,ca as Ul,da as vs,ea as ql,f as Ie,fa as $e,g as $l,ga as Fr,ha as Bl,ia as Za,ib as M,j as ae,ja as Kl,k as ye,ka as Co,la as Tt,ma as Gl,na as Wl,oa as Vl,pa as Ur,qa as Hl,ra as ut,rb as Ps,s as ws,sa as Jl,ta as St,ua as Ts,ub as su,va as Ce,wa as qr,x as Nl,xa as Zl,y as So,ya as Ss,za as Ql}from"./DZJMNZY6.js";import"./UZLQALHY.js";export default $arcgis.t(([AG,vG,Sp,oy,sy,wy,PG,MG,qH,Bx,Dp,zr,il,Wp,,Fp,Iy,{addressToLocations:vy},Ty,Sy,Vp,{createRenderer:ky},{getSchemesByTag:Cy,getSchemes:Ey},{getBackgroundColorTheme:Up},{createAgeRenderer:Py,createContinuousRenderer:Oy},{getSchemesByTag:yl},{createContinuousRenderer:My},{createRenderer:Ry},{getSchemesByTag:$y},{createRenderer:Ny},{getSchemesByTag:zy},{createRenderer:jy},{getSchemesByTag:Ly},{createRenderer:Dy},{getSchemesByTag:Fy},{createAgeRenderer:Uy,createContinuousRenderer:qy},{createRenderer:By},{getSchemesByTag:Ky},Gy,Hp,Jp,{formatDateOnly:Wy,convertDateFormatToIntlOptions:Ma,formatTimeOnly:Vy,formatDate:qp},Hy,Jy,Zy,Qy,Yy,Zp,,{fetchKnowledgeGraph:Bp,executeQueryStreaming:Xy,executeSearchStreaming:e_},t_,{getBindParametersFromCypherQuery:r_},,,,,,,,,,,,,,,,,,,,,,,,,qV,KV,,,,,,,,,,,,,Kx,um,{a:iu,b:lu,c:uu,d:cu,e:du}])=>{var m=v;async function ri(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 ql(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var oe=async(t,e)=>{await ri("trace_message",t,e)},ve=async(t,e)=>{await ri("graph_ux_suggestion",t,e)};var $s={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},_u=Object.keys($s);async function Cm(t,e){let r;if(e)r=$s[e];else{let n=Object.entries($s).find(([,o])=>o.className===t);r=n?n[1]:void 0}if(r)try{return(await import(r.package))[r.className]}catch(n){let o=n;if("code"in o&&o.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in o&&typeof o.message=="string"){let s=(o.message.startsWith("Error: ")?o.message.slice(7):o.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function Em(t,e,r={}){let n=e||Pm(t);if(!n)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);let o=$s[n];if(!o){let i=_u.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
10
+
11
+ Supported model providers are: ${i}`)}let{modelProvider:s,...a}=r;return new(await Cm(o.className,n))({model:t,...a})}function Pm(t){return t.startsWith("gpt-3")||t.startsWith("gpt-4")||t.startsWith("gpt-5")||t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4")?"openai":t.startsWith("claude")?"anthropic":t.startsWith("command")?"cohere":t.startsWith("accounts/fireworks")?"fireworks":t.startsWith("gemini")?"google-vertexai":t.startsWith("amazon.")?"bedrock":t.startsWith("mistral")?"mistralai":t.startsWith("sonar")||t.startsWith("pplx")?"perplexity":void 0}var yu=class Rs extends Eo{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields==="any"?this._configurableFields="any":this._configurableFields=e.configurableFields??["model","modelProvider"],e.configPrefix?this._configPrefix=e.configPrefix.endsWith("_")?e.configPrefix:`${e.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(e){let r=this._getCacheKey(e),n=this._modelInstanceCache.get(r);if(n)return n;let o={...this._defaultConfig,...this._modelParams(e)},s=await Em(o.model,o.modelProvider,o);for(let[a,i]of Object.entries(this._queuedMethodOperations))a in s&&typeof s[a]=="function"&&(s=await s[a](...i));return this._modelInstanceCache.set(r,s),s}async _generate(e,r,n){return(await this._getModelInstance(r))._generate(e,r??{},n)}bindTools(e,r){let n={...this._queuedMethodOperations};return n.bindTools=[e,r],new Rs({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(e,...r)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[e,...r],new Rs({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(e){let r=e?.configurable??{},n={};for(let[o,s]of Object.entries(r))if(o.startsWith(this._configPrefix)){let a=this._removePrefix(o,this._configPrefix);n[a]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([o])=>this._configurableFields.includes(o)))),n}_removePrefix(e,r){return e.startsWith(r)?e.slice(r.length):e}withConfig(e){let r={...e||{}},n=this._modelParams(r),o=Object.fromEntries(Object.entries(r).filter(([s])=>s!=="configurable"));return o.configurable=Object.fromEntries(Object.entries(r.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new Ne({config:r,bound:new Rs({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,r){let n=await this._getModelInstance(r),o=Fr(r);return n.invoke(e,o)}async stream(e,r){let n=new Kl({generator:await(await this._getModelInstance(r)).stream(e,r),config:r});return await n.setup,Za.fromAsyncGenerator(n)}async batch(e,r,n){return super.batch(e,r,n)}async*transform(e,r){let n=await this._getModelInstance(r),o=Fr(r);yield*n.transform(e,o)}async*streamLog(e,r,n){let o=await this._getModelInstance(r),s=Fr(r);yield*o.streamLog(e,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,r,n){if(r?.version==="v1"||r?.version==="v2"){let a=this,i=r;async function*u(){let l=await a._getModelInstance(i),c={...Fr(i),version:i.version,...i.encoding!==void 0?{encoding:i.encoding}:{}},p;i.version==="v1"&&i.encoding==="text/event-stream"||i.version==="v1"||i.version==="v2"&&i.encoding,p=l.streamEvents(e,c,n);for await(let d of p)yield d}return Za.fromAsyncGenerator(u())}let o=this;async function*s(){let a=await o._getModelInstance(r),i=Fr(r);yield*a.streamEvents(e,i)}return new ru(s())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let r=e??{};if(r.configurable){let{configurable:n}=r,o={};for(let[s,a]of Object.entries(n))s.startsWith("__pregel_")||(o[s]=a);r={...r,configurable:o}}return JSON.stringify(r)}};async function Et(t,e){let{configurableFields:r,configPrefix:n,modelProvider:o,profile:s,...a}={configPrefix:"",...e??{}};if(o===void 0&&t?.includes(":")){let[c,...p]=t.split(":"),d=p.length===0?[c]:[c,p.join(":")];_u.includes(d[0])&&([o,t]=d)}let i=Array.isArray(r)?[...r]:r;!t&&i===void 0&&(i=["model","modelProvider"]),n&&i===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...a},l;return i===void 0?l=new yu({defaultConfig:{...u,model:t,modelProvider:o},configPrefix:n,profile:s}):(t&&(u.model=t),o&&(u.modelProvider=o),l=new yu({defaultConfig:u,configPrefix:n,configurableFields:i,profile:s})),await l._getModelInstance(),l}var Ns=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},zs=class extends Error{toolNames;constructor(t){super(`The model has called multiple tools: ${t.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=t}},Mo=class extends Error{toolName;errors;constructor(t,e){super(`Failed to parse structured output for tool '${t}':${e.map(r=>`
12
+ - ${r}`).join("")}.`),this.toolName=t,this.errors=e}},js=class extends Error{toolCall;toolError;constructor(t,e){let r=t instanceof Error?t:new Error(String(t)),n=JSON.stringify(e.args);super(`Error invoking tool '${e.name}' with kwargs ${n} with error: ${r.stack}
13
+ Please fix the error and try again.`),this.toolCall=e,this.toolError=r}},Ro=class wu extends Error{static"~brand"="MiddlewareError";constructor(e,r){let n=e instanceof Error?e.message:String(e);super(n),this.name=e instanceof Error?e.name:`${r[0].toUpperCase()+r.slice(1)}Error`,e instanceof Error&&(this.cause=e)}static wrap(e,r){return Nl(e)?e:new wu(e,r)}static isInstance(e){return e instanceof Error&&"~brand"in e&&e["~brand"]==="MiddlewareError"}};function $o(t){return"invoke"in t&&typeof t.invoke=="function"&&"_streamResponseChunks"in t}function Vr(t){return typeof t=="object"&&t!=null&&"_queuedMethodOperations"in t&&"_getModelInstance"in t&&typeof t._getModelInstance=="function"}var bu=!0,Om=0,je=class ni{constructor(e,r,n){this.schema=e,this.tool=r,this.options=n}get name(){return this.tool.function.name}static fromSchema(e,r){function n(s){return s??`extract-${++Om}`}if(Tt(e)||ut(e)){let s=He(e);return new ni(s,{type:"function",function:{name:n(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},r)}let o;return typeof e.name=="string"&&typeof e.parameters=="object"&&e.parameters!=null?o=e:o={name:n(e.title),description:e.description??"",parameters:e.schema||e},new ni(He(e),{type:"function",function:o},r)}parse(e){let r=new Qa(this.schema).validate(e);if(!r.valid)throw new Mo(this.name,r.errors.map(n=>n.error));return e}},Pt=class xu{_schemaType;schema;strict;constructor(e,r){if("schema"in e&&typeof e.schema=="object"&&e.schema!==null&&!("type"in e)){let n=e;this.schema=n.schema,this.strict=n.strict??bu}else this.schema=e,this.strict=r??bu}static fromSchema(e,r){return new xu(He(e),r)}parse(e){let r;if(typeof e.content=="string")r=e.content;else if(Array.isArray(e.content)){for(let n of e.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){r=n.text;break}}if(!(!r||r===""))try{let n=JSON.parse(r);return new Qa(this.schema).validate(n).valid?n:void 0}catch{}}};function Au(t,e,r){if(!t)return[];if(typeof t=="object"&&t!==null&&"__responseFormatUndefined"in t)return[];if(Array.isArray(t)){if(t.every(o=>o instanceof je||o instanceof Pt))return t;if(t.every(o=>Tt(o)))return t.map(o=>je.fromSchema(o,e));if(t.every(o=>Ce(o)))return t.map(o=>je.fromSchema(o,e));if(t.every(o=>typeof o=="object"&&o!==null&&!Ce(o)&&!Tt(o)))return t.map(o=>je.fromSchema(o,e));throw new Error(`Invalid response format: list contains mixed types.
14
+ All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(t instanceof je||t instanceof Pt)return[t];let n=Mm(r);if(Tt(t))return n?[Pt.fromSchema(t)]:[je.fromSchema(t,e)];if(Ce(t))return n?[Pt.fromSchema(t)]:[je.fromSchema(t,e)];if(typeof t=="object"&&t!==null&&"properties"in t)return n?[Pt.fromSchema(t)]:[je.fromSchema(t,e)];throw new Error(`Invalid response format: ${String(t)}`)}function Mm(t){return!t||!$o(t)||!("profile"in t)||typeof t.profile!="object"||!t.profile?!1:"structuredOutput"in t.profile&&t.profile.structuredOutput===!0}function Ze(t){if(!(!t||typeof t=="function"))return t.canJumpTo}function Ot(t){return typeof t=="function"?t:t.hook}function Rm(t,e){if(t.length<e.length||t.length>e.length+1)return!1;for(let r=0;r<e.length;r+=1)if(t[r]!==e[r])return!1;return!0}function $m(t){let e;try{e=JSON.parse(t)}catch{return!1}return!Array.isArray(e)||e.length===0?!1:e.every(r=>{if(r==null||typeof r!="object")return!1;let n=r;return typeof n.id=="string"&&"value"in n})}function Nm(t){if(t==null||typeof t!="object")return!1;let e=t;return e.type!=="constructor"||!Array.isArray(e.id)?!1:e.id[e.id.length-1]==="ToolMessage"}function zm(t){return F.isInstance(t)?t.content:Nm(t)?t.kwargs?.content:t}function No(t){return()=>{let e=Ps.local(),r=new Map;function n(o,s,a){if(r.has(o))return;let i=typeof a=="string"?JSON.parse(a):a,u,l,c,p,d=new Promise((w,_)=>{u=w,l=_}),g=new Promise(w=>{c=w}),y=new Promise(w=>{p=w});r.set(o,{resolveOutput:u,rejectOutput:l,resolveStatus:c,resolveError:p}),e.push({name:s,callId:o,input:i,output:d,status:g,error:y})}return{__native:!0,init:()=>({toolCalls:e}),process(o){if(!Rm(o.params.namespace,t))return!0;if(o.method==="messages"){let s=o.params.data;if(s.event==="content-block-finish"){let a=s.contentBlock??s.content_block;a?.type==="tool_call"&&n(String(a.id??""),String(a.name??""),a.args??a.input)}}if(o.method==="tools"){let s=o.params.data,a=s.tool_call_id;s.event==="tool-started"&&n(a,s.tool_name??"unknown",s.input);let i=a?r.get(a):void 0;if(i){if(s.event==="tool-finished")i.resolveOutput(zm(s.output)),i.resolveStatus("finished"),i.resolveError(void 0),r.delete(a);else if(s.event==="tool-error"){let u=s.message??"unknown error";if($m(u))return!0;i.rejectOutput(new Error(u)),i.resolveStatus("error"),i.resolveError(u),r.delete(a)}}}return!0},finalize(){for(let o of r.values())o.resolveStatus("finished"),o.resolveError(void 0),o.resolveOutput(void 0);r.clear(),e.close()},fail(o){for(let s of r.values())s.resolveStatus("error"),s.resolveError(o instanceof Error?o.message:String(o)),s.rejectOutput(o);r.clear(),e.fail(o)}}}}function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zo(t){return t.join("\0")}function Iu(t,e){if(e.length>t.length)return!1;for(let r=0;r<e.length;r+=1)if(t[r]!==e[r])return!1;return!0}function Ls(t=[]){return()=>{let e=Ps.local(),r=new Map,n=new Map,o=new Map,s=new Map,a=t.length;function i(d,g){let y=zo(d);if(r.has(y))return;let w=(Qe(g)&&Qe(g.metadata)?g.metadata:void 0)?.lc_agent_name;r.set(y,typeof w=="string"?w:void 0)}function u(d){if(!Qe(d))return;let g=d.id;if(typeof g!="string")return;let y=d.input,w;if(Qe(y)&&Qe(y.tool_call)){let _=y.tool_call.id;typeof _=="string"&&(w=_)}else if(Array.isArray(y)){for(let _ of y)if(Qe(_)&&typeof _.id=="string"){w=_.id;break}}w!=null&&n.set(g,w)}function l(d){let g=o.get(zo(d));if(typeof g=="string"&&g.length>0)return{type:"toolCall",tool_call_id:g};let y=d[d.length-1],w=y.indexOf(":");if(w===-1)return;let _=y.slice(w+1);if(_.length===0)return;let f=n.get(_);if(!(typeof f!="string"||f.length===0))return{type:"toolCall",tool_call_id:f}}function c(d){if(d.length!==a+1||!Iu(d,t))return;let g=zo(d);if(s.has(g))return;let y=r.get(g);if(typeof y!="string"||y.length===0)return;let w=su(d),_=w.init(),f=No(d)(),A=f.init(),T=Ls(d)(),E=T.init(),G,q,P=new Promise((Q,te)=>{G=Q,q=te});s.set(g,{key:g,path:d,name:y,messages:w,toolCall:f,nested:T,resolveOutput:G,rejectOutput:q,latestValues:void 0,done:!1}),e.push({name:y,cause:l(d),output:P,messages:_.messages,toolCalls:A.toolCalls,subagents:E.subagents})}function p(d,g){d.done||(d.done=!0,g.type==="resolve"?d.resolveOutput(d.latestValues):d.rejectOutput(g.error),d.messages.finalize?.(),d.toolCall.finalize?.(),d.nested.finalize?.())}return{__native:!0,init:()=>({subagents:e}),process(d){let g=d.params.namespace,y=d.params.data,w=d.method==="tasks"&&Qe(y)&&"result"in y;d.method==="tools"&&Qe(y)&&y.event==="tool-started"&&typeof y.tool_call_id=="string"&&y.tool_call_id.length>0&&o.set(zo(g),y.tool_call_id),d.method==="tasks"&&!w&&(i(g,y),u(y),c(g));for(let _ of s.values())if(!_.done&&Iu(g,_.path)&&(_.messages.process(d),_.toolCall.process(d),_.nested.process(d),zo(g)===_.key)){if(d.method==="values"&&Qe(y))_.latestValues=y;else if(d.method==="lifecycle"&&Qe(y)){let f=y.event;f==="completed"||f==="interrupted"?p(_,{type:"resolve"}):f==="failed"&&p(_,{type:"reject",error:new Error(`Subagent ${_.name} failed`)})}}return!0},finalize(){for(let d of s.values())p(d,{type:"resolve"});e.close()},fail(d){for(let g of s.values())p(g,{type:"reject",error:d});e.fail(d)}}}}var oi=Symbol.for("langgraph-zod");oi in globalThis||(globalThis[oi]=new WeakSet);function vu(t){let e=globalThis[oi];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return Ms(r,{jsonSchemaExtra:n})},reducer(n,o){return Ms(r,{default:Ss(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{vu(I.ZodType.prototype),vu(v.ZodType.prototype)}catch(t){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:t})}var Tu=class extends Wl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=Ss(t);n!=null&&(r.default=n)}return super.add(t,...e)}},Lm=new Tu(Oo);function Su(t=!0,e,r=[]){let n={jumpTo:new ti},o={},s={},a=i=>{if(Ee.isInstance(i)){for(let[l,c]of Object.entries(i.fields))if(!(l in n)){if(n[l]=c,l.startsWith("_"))continue;Ct.isInstance(c)?(o[l]=c.inputSchema||c.valueSchema,s[l]=c.valueSchema):(o[l]=c,s[l]=c)}return}let u=qr(i);for(let[l,c]of Object.entries(u)){let p=l.startsWith("_");if(!(l in n)){if(Ur(c)){let d=Oo.get(c);if(d?.reducer){d.reducer.schema?(n[l]=new Ct(c,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),p||(o[l]=d.reducer.schema,s[l]=c)):(n[l]=new Ct(c,{reducer:d.reducer.fn}),p||(o[l]=c,s[l]=c));continue}}n[l]=c,p||(o[l]=c,s[l]=c)}}};e&&(Ee.isInstance(e)||Ce(e))&&a(e);for(let i of r)i.stateSchema&&(Ee.isInstance(i.stateSchema)||Ce(i.stateSchema))&&a(i.stateSchema);return t&&(s.structuredResponse=new ti),{state:new Ee({messages:Os,...n}),input:new Ee({messages:Os,...o}),output:new Ee({messages:Os,...s})}}var si=/<name>(.*?)<\/name>/s,ai=/<content>(.*?)<\/content>/s;function Dm(t,e){if(Ee.isInstance(t)){let r={};for(let n of Object.keys(t.fields))n in e&&(r[n]=e[n]);return r}if(ut(t))return St(t,e);throw new Error(`Invalid state schema type: ${typeof t}`)}function Cu(t){if(!$.isInstance(t)||lt.isInstance(t)||!t.name)return t;let{name:e}=t;if(typeof t.content=="string")return new $({...t.lc_kwargs,content:`<name>${e}</name><content>${t.content}</content>`,name:void 0});let r=[],n=0;for(let o of t.content)typeof o=="string"?(n+=1,r.push(`<name>${e}</name><content>${o}</content>`)):typeof o=="object"&&"type"in o&&o.type==="text"?(n+=1,r.push({...o,text:`<name>${e}</name><content>${o.text}</content>`})):r.push(o);return n||r.unshift({type:"text",text:`<name>${e}</name><content></content>`}),new $({...t.lc_kwargs,content:r,name:void 0})}function Eu(t){if(!$.isInstance(t)||!t.content)return t;let e=[],r;if(Array.isArray(t.content))e=t.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(si),s=n.text.match(ai);return o&&(!s||s[1]==="")?(r=o[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let o=n.text.match(si),s=n.text.match(ai);return!o||!s?n:(r=o[1],{...n,text:s[1]})}return n});else{let n=t.content,o=n.match(si),s=n.match(ai);if(!o||!s)return t;r=o[1],e=s[1]}return new $({...Object.keys(t.lc_kwargs??{}).length>0?t.lc_kwargs:t,content:e,name:r})}function er(t){return Br.isRunnable(t)}function ku(t){return $o(t)?"bindTools"in t&&typeof t.bindTools=="function":!1}var ii=(t,e,r={})=>{if(ku(t))return t.bindTools(e,r);if(Ne.isRunnableBinding(t)&&ku(t.bound)){let n=t.bound.bindTools(e,r);return Ne.isRunnableBinding(n)?new Ne({bound:n.bound,config:{...t.config,...n.config},kwargs:{...t.kwargs,...n.kwargs},configFactories:n.configFactories??t.configFactories}):new Ne({bound:n,config:t.config,kwargs:t.kwargs,configFactories:t.configFactories})}return null};function Ds(t){if(typeof t=="function")return;let e=t;if(kt.isRunnableSequence(e)&&(e=e.steps.find(r=>Ne.isRunnableBinding(r))||e),!Vr(e)){if(Ne.isRunnableBinding(e)){let r=e.kwargs!=null&&typeof e.kwargs=="object"&&"tools"in e.kwargs&&Array.isArray(e.kwargs.tools)&&e.kwargs.tools.length>0,n=e.config!=null&&typeof e.config=="object"&&"tools"in e.config&&Array.isArray(e.config.tools)&&e.config.tools.length>0;if(r||n)throw new Ns}if("tools"in e&&e.tools!==void 0&&Array.isArray(e.tools)&&e.tools.length>0)throw new Ns}}function li(t){return!!($.isInstance(t)&&t.tool_calls&&t.tool_calls.length>0)}function Pu(t){if(t==null)return new ke("");if(ke.isInstance(t))return t;if(typeof t=="string")return new ke({content:[{type:"text",text:t}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof t}`)}async function Ou(t,e,r={}){let n=ii(t,e,r);if(n)return n;if(Vr(t)){let o=ii(await t._getModelInstance(),e,r);if(o)return o}if(kt.isRunnableSequence(t)){let o=t.steps.findIndex(s=>Ne.isRunnableBinding(s)||$o(s)||Vr(s));if(o>=0){let s=ii(t.steps[o],e,r);if(s){let a=t.steps.slice();return a.splice(o,1,s),kt.from(a)}}}throw new Error(`llm ${t} must define bindTools method.`)}function Fm(t){if(t.length===0)return;if(t.length===1)return t[0];function e(n,o){return async(s,a)=>n(s,async u=>o(u,a))}let r=t[t.length-1];for(let n=t.length-2;n>=0;n--)r=e(t[n],r);return r}function Mu(t){let e=t.filter(r=>r.wrapToolCall);if(e.length!==0)return Fm(e.map(r=>{let n=r.wrapToolCall;return async(s,a)=>{let i=s.state,u=async l=>{let c={...i,...l.state};return a({...l,state:c})};try{let l=await n({...s,state:{messages:i.messages,...r.stateSchema?Dm(r.stateSchema,{...i}):{}}},u);if(!F.isInstance(l)&&!ye(l))throw new Error(`Invalid response from "wrapToolCall" in middleware "${r.name}": expected ToolMessage or Command, got ${typeof l}`);return l}catch(l){throw Ro.wrap(l,r.name)}}}))}var Um=["tags","metadata","runName","maxConcurrency","recursionLimit","configurable"];function Ru(t){let e={};for(let r of Um){let n=t[r];n!==void 0&&(e[r]=n)}return e}async function $u(t,e){let r={};for(let n of t){if(!n.stateSchema)continue;let o;if(Ee.isInstance(n.stateSchema)){let i={};for(let[u,l]of Object.entries(n.stateSchema.fields))Ct.isInstance(l)?i[u]=l.inputSchema||l.valueSchema:i[u]=l;o=v.object(i)}else if(Ce(n.stateSchema))o=n.stateSchema;else continue;let s=await Jl(Ql(o,i=>i.startsWith("_")),e);if(s.success){Object.assign(r,s.data);continue}let a=s.error.issues.filter(i=>i.code==="invalid_type").map(i=>` - ${i.path.join(".")}: Required`).join(`
15
+ `);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
16
+ ${a}
17
+
18
+ To fix this, either:
19
+ 1. Provide default values in your middleware's state schema using .default():
20
+ stateSchema: z.object({
21
+ myField: z.string().default("default value")
22
+ })
23
+
24
+ 2. Or make the fields optional using .optional():
25
+ stateSchema: z.object({
26
+ myField: z.string().optional()
27
+ })
28
+
29
+ 3. Or ensure you pass these values when invoking the agent:
30
+ agent.invoke({
31
+ messages: [...],
32
+ ${s.error.issues[0]?.path.join(".")}: "value"
33
+ })`)}return r}function Nu(t){let e={messages:v.custom(()=>[]),structuredResponse:v.any().optional()};if(!t)return v.object(e);let r;if(Ee.isInstance(t)){r={};for(let[o,s]of Object.entries(t.fields))Ct.isInstance(s)?r[o]=s.inputSchema||s.valueSchema:r[o]=s}else if(Ce(t))r=qr(t);else return v.object(e);let n={...e};for(let[o,s]of Object.entries(r))o.startsWith("_")?n[o]=s.optional():n[o]=s;return v.object(n)}function zu(t){if(Ce(t))return Zl(t);if(Ee.isInstance(t)){let e={};for(let[r,n]of Object.entries(t.fields)){let o;Ct.isInstance(n)?o=n.inputSchema||n.valueSchema:o=n,e[r]=Ur(o)?o.optional():v.any().optional()}return v.object(e)}return v.object({})}function Le(t){if(t){if(["model_request","tools",L].includes(t))return t;if(t==="model")return"model_request";if(t==="tools")return"tools";if(t==="end")return L;throw new Error(`Invalid jump target: ${t}, must be "model", "tools" or "end".`)}}function Fs(...t){return AbortSignal.any(t.filter(e=>e!=null&&typeof e=="object"&&"aborted"in e&&typeof e.aborted=="boolean"))}var Hr=class extends Br{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(t){super(),this.name=t.name??t.func.name,this.func=t.func,this.config=t.tags?{tags:t.tags}:void 0,this.recurse=t.recurse??this.recurse}getState(){return this.#e}setState(t){this.#e={...this.#e,...t}}async invoke(t,e){let r=$e(this.config,e),n=await vs.runWithConfig(r,async()=>this.func(t,r));return Br.isRunnable(n)&&this.recurse?await vs.runWithConfig(r,async()=>n.invoke(t,r)):(this.#e=n,n)}};function ju(t,e){let r,n;if(e==="inline")r=Cu,n=Eu;else throw new Error(`Invalid agent name mode: ${e}. Needs to be one of: "inline"`);function o(s){return s.map(r)}return kt.from([Je.from(o),t,Je.from(n)])}function qm(t){return $.isInstance(t)||ye(t)||typeof t=="object"&&t!==null&&"structuredResponse"in t&&"messages"in t}var ce="model_request",Lu=class extends Hr{#e;#r;constructor(t){super({name:t.name??"model",func:(e,r)=>this.#t(e,r)}),this.#e=t,this.#r=t.systemMessage}async#o(t,e=this.#e.responseFormat){if(!e)return;let r;Vr(t)?r=await t._getModelInstance():typeof t!="string"&&(r=t);let n=Au(e,void 0,r);if(n.length!==0)return n.every(o=>o instanceof Pt)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(o=>o instanceof je).reduce((o,s)=>(o[s.name]=s,o),{})}}async#t(t,e){let r=t.messages.at(-1);if(r&&F.isInstance(r)&&r.name&&this.#e.shouldReturnDirect.has(r.name))return[new ae({update:{messages:[]}})];let{response:n,lastAiMessage:o,collectedCommands:s}=await this.#a(t,e);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:u,messages:l}=n;return{messages:[...t.messages,...l],structuredResponse:u}}let a=[],i=$.isInstance(n)?n:o;return i&&(i.name=this.name,i.lc_kwargs.name=this.name,this.#u(t,i)?a.push(new ae({update:{messages:[new $({content:"Sorry, need more steps to process this request.",name:this.name,id:i.id})]}})):a.push(new ae({update:{messages:[i]}}))),ye(n)&&!s.includes(n)&&a.push(n),a.push(...s),a}#s(){if(typeof this.#e.model=="string")return Et(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(t,e,r={}){let n=await this.#s(),o=e,s=this.#r,a=null,i=[],u=async d=>{Ds(d.model);let g=await this.#o(d.model,d.responseFormat),y=await this.#c(d.model,d,g),w=[...s.text===""?[]:[s],...d.messages],_=Fs(this.#e.signal,e.signal),f=await Bl(y.invoke(w,{...e,signal:_}),_);if(a=f,g?.type==="native"){let E=g.strategy.parse(f);if(E)return{structuredResponse:E,messages:[f]};if(!f.tool_calls||f.tool_calls.length===0)throw new Mo(typeof g.strategy.schema?.title=="string"?g.strategy.schema.title:"providerStrategy",["Model output did not satisfy the provided response schema."]);return f}if(!g||!f.tool_calls)return f;let A=f.tool_calls.filter(E=>E.name in g.tools);if(A.length===0)return f;if(A.length>1)return this.#i(f,A,g);let T=g.tools[A[0].name]?.options?.toolMessageContent;return this.#l(f,A[0],g,T??r.lastMessage)},l=this.#e.wrapModelCallHookMiddleware??[],c=u;for(let d=l.length-1;d>=0;d--){let g=l[d],y=Array.isArray(g)?g[0]:g;if(y.wrapModelCall){let w=c,_=y;c=async f=>{let A=s,T=_.contextSchema?St(_.contextSchema,o?.context||{}):o?.context,E=Object.freeze({context:T,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal}),G={...f,state:{...y.stateSchema?St(zu(y.stateSchema),t):{},messages:t.messages},runtime:E},q=async P=>{s=A;let Q=P.tools??[],te=new Map(this.#e.toolClasses.filter(er).map(H=>[H.name,H])),Y=Q.filter(H=>er(H)&&!te.has(H.name)),X=Q.filter(H=>{if(!er(H))return!1;let B=te.get(H.name);return B!=null&&B!==H});if(Y.length>0&&!this.#e.middleware?.some(H=>H.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${_.name}": ${Y.map(H=>H.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(X.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${_.name}": ${X.map(H=>H.name).join(", ")}. This is not supported.`);let C=P,U=P.systemPrompt!==s.text,ee=P.systemMessage!==s;if(U&&ee)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");U&&(s=new ke({content:[{type:"text",text:P.systemPrompt}]}),C={...P,systemPrompt:s.text,systemMessage:s}),ee&&(s=new ke({...P.systemMessage}),C={...P,systemPrompt:s.text,systemMessage:s});let J=await w(C);return ye(J)&&a?(i.includes(J)||i.push(J),a):J};if(!_.wrapModelCall)return q(G);try{let P=await _.wrapModelCall(G,q);if(!qm(P))throw new Error(`Invalid response from "wrapModelCall" in middleware "${_.name}": expected AIMessage or Command, got ${typeof P}`);return $.isInstance(P)?a=P:ye(P)&&i.push(P),P}catch(P){throw Ro.wrap(P,_.name)}}}}s=this.#r;let p={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:t.messages,tools:this.#e.toolClasses,state:t,runtime:Object.freeze({context:o?.context,store:o.store,configurable:o.configurable,writer:o.writer,interrupt:o.interrupt,signal:o.signal})};return{response:await c(p),lastAiMessage:a,collectedCommands:i}}#i(t,e,r){let n=new zs(e.map(o=>o.name));return this.#n(n,t,e[0],r)}#l(t,e,r,n){let o=r.tools[e.name];try{let s=o.parse(e.args);return{structuredResponse:s,messages:[t,new F({tool_call_id:e.id??"",content:JSON.stringify(s),name:e.name}),new $(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#n(s,t,e,r)}}async#n(t,e,r,n){let o=Object.values(n.tools).at(0)?.options?.handleError,s=r.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(o===!1)throw t;if(o===void 0||typeof o=="boolean"&&o||Array.isArray(o)&&o.some(a=>a instanceof zs))return new ae({update:{messages:[e,new F({content:t.message,tool_call_id:s})]},goto:ce});if(typeof o=="string")return new ae({update:{messages:[e,new F({content:o,tool_call_id:s})]},goto:ce});if(typeof o=="function"){let a=await o(t);if(typeof a!="string")throw new Error("Error handler must return a string.");return new ae({update:{messages:[e,new F({content:a,tool_call_id:s})]},goto:ce})}return new ae({update:{messages:[e,new F({content:t.message,tool_call_id:s})]},goto:ce})}#u(t,e){let r=$.isInstance(e)&&e.tool_calls?.every(o=>this.#e.shouldReturnDirect.has(o.name)),n="remainingSteps"in t?t.remainingSteps:void 0;return!!(n&&(n<1&&r||n<2&&li(t.messages.at(-1))))}async#c(t,e,r){let n={},o=Object.values(r&&"tools"in r?r.tools:{}),s=[...e?.tools??this.#e.toolClasses,...o.map(u=>u.tool)],a=e?.toolChoice||(o.length>0?"any":void 0);if(r?.type==="native"){let u=e?.modelSettings?.strict??r?.strategy?.strict??!0,l={name:r.strategy.schema?.name??"extract",description:Ts(r.strategy.schema),schema:r.strategy.schema,strict:u};Object.assign(n,{response_format:{type:"json_schema",json_schema:l},outputConfig:{format:{type:"json_schema",schema:r.strategy.schema}},responseSchema:r.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:r.strategy.schema},strict:e?.modelSettings?.strict})}let i=await Ou(t,s,{...n,...e?.modelSettings,tool_choice:a});return this.#e.includeAgentName==="inline"?ju(i,this.#e.includeAgentName):i}getState(){let t=super.getState();return{messages:[],...t&&!ye(t)?t:{}}}};var Du=(t,e)=>`Error: ${t} is not a valid tool, try one of [${e.join(", ")}].`,Te="tools",Fu=t=>Array.isArray(t)&&t.every(Va.isInstance),Bm=t=>typeof t=="object"&&t!=null&&"messages"in t&&Fu(t.messages),Km=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t;function Gm(t,e){return t instanceof js?new F({content:t.message,tool_call_id:e.id,name:e.name}):new F({content:`${t}
34
+ Please fix your mistakes.`,tool_call_id:e.id,name:e.name})}var Uu=class extends Hr{tools;trace=!1;signal;handleToolErrors=Gm;wrapToolCall;constructor(t,e){let{name:r,tags:n,handleToolErrors:o,signal:s,wrapToolCall:a}=e??{};super({name:r,tags:n,func:(i,u)=>this.run(i,u)}),this.options=e,this.tools=t,this.handleToolErrors=o??this.handleToolErrors,this.signal=s,this.wrapToolCall=a}#e(t,e,r){if(So(t)||this.signal?.aborted||r&&this.handleToolErrors!==!0||!this.handleToolErrors)throw t;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(t,e);if(n&&F.isInstance(n))return n;throw t}else if(this.handleToolErrors)return new F({name:e.name,content:`${t}
35
+ Please fix your mistakes.`,tool_call_id:e.id});throw t}async runTool(t,e,r){let n=e,o={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(u=>u.name===t.name),a=async u=>{let{toolCall:l,tool:c}=u,p=c??this.tools.find(g=>g.name===l.name);if(p===void 0){let g=this.tools.map(y=>y.name);return new F({content:Du(l.name,g),tool_call_id:l.id,name:l.name,status:"error"})}let d=p;try{let g=await d.invoke({...l,type:"tool_call"},{...e,config:e,toolCallId:l.id,state:e.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Fs(this.signal,e.signal)});return F.isInstance(g)||ye(g)?g:new F({name:d.name,content:typeof g=="string"?g:JSON.stringify(g),tool_call_id:l.id})}catch(g){throw g instanceof Ll?new js(g,l):g}},i={toolCall:t,tool:s,state:r,runtime:o};if(this.wrapToolCall)try{return await this.wrapToolCall(i,a)}catch(u){return this.#e(u,t,!0)}if(!s){let u=this.tools.map(l=>l.name);return new F({content:Du(t.name,u),tool_call_id:t.id,name:t.name,status:"error"})}try{return await a(i)}catch(u){return this.#e(u,t,!1)}}async run(t,e){let r;if(Km(t)){let{lg_tool_call:s,jumpTo:a,...i}=t;r=[await this.runTool(t.lg_tool_call,e,i)]}else{let s;if(Fu(t))s=t;else if(Bm(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if($.isInstance(l)){i=l;break}}if(!$.isInstance(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(ye))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ye(s)?s.graph===ae.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>Wm(a))?o?o.goto.push(...s.goto):o=new ae({graph:ae.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};function Wm(t){return t instanceof Ie}var Vm=class{},Hm=class{},Rt=class extends Hr{constructor(t){super(t)}async invokeMiddleware(t,e){let r={};if(this.middleware.contextSchema&&Ce(this.middleware.contextSchema)){let u=qr(this.middleware.contextSchema);if(u){let l={},c=e?.context||{};for(let p of Object.keys(u))p in c&&(l[p]=c[p]);r=St(this.middleware.contextSchema,l)}}let n={...t,messages:t.messages},o={context:r,store:e?.store,configurable:e?.configurable,writer:e?.writer,interrupt:e?.interrupt,signal:e?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new Hm,{...o,context:Object.freeze(Object.assign(new Vm,r))})));if(!s)return{jumpTo:void 0};let a,i;if(this.name?.startsWith("BeforeAgentNode_")?(a=Ze(this.middleware.beforeAgent),i="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(a=Ze(this.middleware.beforeModel),i="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(a=Ze(this.middleware.afterAgent),i="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(a=Ze(this.middleware.afterModel),i="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!a?.includes(s.jumpTo)){let u=a&&a.length>0?`must be one of: ${a?.join(", ")}.`:i?`no ${i} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:Nu(this.middleware.stateSchema)}}};var qu=class extends Rt{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(t){super({name:`BeforeAgentNode_${t.name}`,func:async(e,r)=>this.invokeMiddleware(e,r)}),this.middleware=t}runHook(t,e){return Ot(this.middleware.beforeAgent)(t,e)}};var Bu=class extends Rt{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(t){super({name:`BeforeModelNode_${t.name}`,func:async(e,r)=>this.invokeMiddleware(e,r)}),this.middleware=t}runHook(t,e){return Ot(this.middleware.beforeModel)(t,e)}};var Ku=class extends Rt{lc_namespace=["langchain","agents","afterModelNodes"];constructor(t){super({name:`AfterModelNode_${t.name}`,func:async(e,r)=>this.invokeMiddleware(e,r)}),this.middleware=t}runHook(t,e){return Ot(this.middleware.afterModel)(t,e)}};var Gu=class extends Rt{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(t){super({name:`AfterAgentNode_${t.name}`,func:async(e,r)=>this.invokeMiddleware(e,r)}),this.middleware=t}runHook(t,e){return Ot(this.middleware.afterAgent)(t,e)}};var Wu=class Vu{#e;#r="v2";#o;#t;constructor(e,r){if(this.options=e,this.#t=$e(r??{},{metadata:{ls_integration:"langchain_create_agent"},configurable:{ls_agent_type:"root"}}),e.name&&(this.#t=$e(this.#t,{metadata:{lc_agent_name:e.name}})),this.#r=e.version??this.#r,!e.model)throw new Error("`model` option is required to create an agent.");typeof e.model!="string"&&Ds(e.model);let n=this.options.middleware?.filter(C=>C.tools).flatMap(C=>C.tools)??[],o=[...e.tools??[],...n],s=new Set(o.filter(er).filter(C=>"returnDirect"in C&&C.returnDirect).map(C=>C.name)),a=!!this.options.middleware?.some(C=>C.wrapModelCall),{state:i,input:u,output:l}=Su(this.options.responseFormat!==void 0||a,this.options.stateSchema,this.options.middleware),c=new _e(i,{input:u,output:l,context:this.options.contextSchema}),p=[],d=[],g=[],y=[],w=[];this.#o=new Lu({model:this.options.model,systemMessage:Pu(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:o,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:w});let _=new Set,f=this.options.middleware??[];for(let C=0;C<f.length;C++){let U,ee,J,H,B=f[C];if(_.has(B.name))throw new Error(`Middleware ${B.name} is defined multiple times`);if(_.add(B.name),B.beforeAgent){U=new qu(B);let Z=`${B.name}.before_agent`;p.push({index:C,name:Z,allowed:Ze(B.beforeAgent)}),c.addNode(Z,U,U.nodeOptions)}if(B.beforeModel){ee=new Bu(B);let Z=`${B.name}.before_model`;d.push({index:C,name:Z,allowed:Ze(B.beforeModel)}),c.addNode(Z,ee,ee.nodeOptions)}if(B.afterModel){J=new Ku(B);let Z=`${B.name}.after_model`;g.push({index:C,name:Z,allowed:Ze(B.afterModel)}),c.addNode(Z,J,J.nodeOptions)}if(B.afterAgent){H=new Gu(B);let Z=`${B.name}.after_agent`;y.push({index:C,name:Z,allowed:Ze(B.afterAgent)}),c.addNode(Z,H,H.nodeOptions)}B.wrapModelCall&&w.push(B)}c.addNode(ce,this.#o);let A=f.some(C=>C.wrapToolCall),T=o.filter(er);if(T.length>0||A){let C=new Uu(T,{signal:this.options.signal,wrapToolCall:Mu(f)});c.addNode(Te,C)}let E;p.length>0?E=p[0].name:d.length>0?E=d[0].name:E=ce;let G=d.length>0?d[0].name:ce,q=y.length>0?y[y.length-1].name:L;c.addEdge(ge,E);let P=T.length>0||A;for(let C=0;C<p.length;C++){let U=p[C],ee=U.name,J=C===p.length-1?G:p[C+1].name;if(U.allowed&&U.allowed.length>0){let H=U.allowed.map(Z=>Le(Z)).filter(Z=>Z!=="tools"||P),B=Array.from(new Set([J,...H.map(Z=>Z===L?q:Z)]));c.addConditionalEdges(ee,this.#u(T,J,q,P),B)}else c.addEdge(ee,J)}for(let C=0;C<d.length;C++){let U=d[C],ee=U.name,J=C===d.length-1?ce:d[C+1].name;if(U.allowed&&U.allowed.length>0){let H=U.allowed.map(Z=>Le(Z)).filter(Z=>Z!=="tools"||P),B=Array.from(new Set([J,...H]));c.addConditionalEdges(ee,this.#c(T,J,P),B)}else c.addEdge(ee,J)}let Q=g.at(-1);if(g.length>0&&Q)c.addEdge(ce,Q.name);else{let C=this.#s(T,!1,P).map(U=>U===L?q:U);C.length===1?c.addEdge(ce,C[0]):c.addConditionalEdges(ce,this.#i(q),C)}for(let C=g.length-1;C>0;C--){let U=g[C],ee=U.name,J=g[C-1].name;if(U.allowed&&U.allowed.length>0){let H=U.allowed.map(Z=>Le(Z)).filter(Z=>Z!=="tools"||P),B=Array.from(new Set([J,...H]));c.addConditionalEdges(ee,this.#n(T,U.allowed,J,P),B)}else c.addEdge(ee,J)}if(g.length>0){let C=g[0],U=C.name,ee=this.#s(T,!0,P).filter(B=>B!=="tools"||P),J=!!(C.allowed&&C.allowed.length>0),H=ee.map(B=>B===L?q:B);c.addConditionalEdges(U,this.#l(T,J,q,P),H)}for(let C=y.length-1;C>0;C--){let U=y[C],ee=U.name,J=y[C-1].name;if(U.allowed&&U.allowed.length>0){let H=U.allowed.map(Z=>Le(Z)).filter(Z=>Z!=="tools"||P),B=Array.from(new Set([J,...H]));c.addConditionalEdges(ee,this.#n(T,U.allowed,J,P),B)}else c.addEdge(ee,J)}if(y.length>0){let C=y[0],U=C.name;if(C.allowed&&C.allowed.length>0){let ee=C.allowed.map(H=>Le(H)).filter(H=>H!=="tools"||P),J=Array.from(new Set([L,...ee]));c.addConditionalEdges(U,this.#n(T,C.allowed,L,P),J)}else c.addEdge(U,L)}if(P){let C=G;s.size>0?c.addConditionalEdges(Te,this.#a(s,q,C),[C,q]):c.addEdge(Te,C)}let te=(this.options.middleware??[]).flatMap(C=>C.streamTransformers??[]),Y=[No([]),Ls([]),...te,...this.options.streamTransformers??[]];this.#e=c.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description,transformers:Y});let X=Ru(this.#t);Object.keys(X).length>0&&(this.#e=this.#e.withConfig(X))}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(e){this.#e.checkpointer=e}get store(){return this.#e.store}set store(e){this.#e.store=e}withConfig(e){return new Vu(this.options,$e(this.#t,e))}#s(e,r=!1,n=e.length>0){let o=[];return n&&o.push(Te),r&&o.push(ce),o.push(L),o}#a(e,r,n){return o=>{let s=o.messages,a=s[s.length-1];return F.isInstance(a)&&a.name&&e.has(a.name)?this.options.responseFormat?n:r:n}}#i(e=L){return r=>{let n=r.messages.at(-1);if(!$.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return e;if(this.#r==="v1")return Te;let o=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return o.length===0?e:o.map(s=>new Ie(Te,{...r,lg_tool_call:s}))}}#l(e,r,n,o=e.length>0){let s=!!this.options.responseFormat;return a=>{let i=a,u=i.messages,l=u.at(-1);if($.isInstance(l)&&(!l.tool_calls||l.tool_calls.length===0))return n;if(r&&i.jumpTo){let f=Le(i.jumpTo);return f===L?n:f==="tools"?o?new Ie(Te,{...a,jumpTo:void 0}):n:new Ie(ce,{...a,jumpTo:void 0})}let c=u.filter(F.isInstance),p=u.filter($.isInstance).at(-1),d=p?.tool_calls?.filter(f=>!c.some(A=>A.tool_call_id===f.id));if(d&&d.length>0)return this.#r==="v1"?Te:d.map(f=>new Ie(Te,{...a,lg_tool_call:f}));let g=p?.tool_calls?.some(f=>f.name.startsWith("extract-"));if(d&&d.length===0&&!g&&s)return ce;if(!$.isInstance(l)||!l.tool_calls||l.tool_calls.length===0)return n;let y=l.tool_calls.every(f=>f.name.startsWith("extract-")),w=l.tool_calls.some(f=>!f.name.startsWith("extract-"));if(y||!w)return n;if(this.#r==="v1")return Te;let _=l.tool_calls.filter(f=>!f.name.startsWith("extract-"));return _.length===0?n:_.map(f=>new Ie(Te,{...a,lg_tool_call:f}))}}#n(e,r,n,o=e.length>0){let s=new Set(r.map(a=>Le(a)));return a=>{let i=a;if(i.jumpTo){let u=Le(i.jumpTo);if(u===L&&s.has(L))return L;if(u==="tools"&&s.has("tools"))return o?new Ie(Te,{...a,jumpTo:void 0}):L;if(u==="model_request"&&s.has("model_request"))return new Ie(ce,{...a,jumpTo:void 0})}return n}}#u(e,r,n,o=e.length>0){return s=>{let a=s;if(!a.jumpTo)return r;let i=Le(a.jumpTo);return i===L?n:i==="tools"?o?new Ie(Te,{...s,jumpTo:void 0}):n:new Ie(ce,{...s,jumpTo:void 0})}}#c(e,r,n=e.length>0){return o=>{let s=o;if(!s.jumpTo)return r;let a=Le(s.jumpTo);return a===L?L:a==="tools"?n?new Ie(Te,{...o,jumpTo:void 0}):L:new Ie(ce,{...o,jumpTo:void 0})}}async#d(e,r){if(!this.options.middleware||this.options.middleware.length===0||e instanceof ae||!e)return e;let n=await $u(this.options.middleware,e),o={...(await this.#e.getState(r).catch(()=>({values:{}}))).values,...e};if(!o)return o;for(let[s,a]of Object.entries(n))s in o||(o[s]=a);return o}async invoke(e,r){let n=$e(this.#t,r),o=await this.#d(e,n);return this.#e.invoke(o,n)}async stream(e,r){let n=$e(this.#t,r),o=await this.#d(e,n);return this.#e.stream(o,n)}streamEvents(e,r,n){if(r?.version!=="v3"||n!=null){let o=$e(this.#t,r),s=r?.version==="v1"||r?.version==="v2"?r.version:"v2";return this.#e.streamEvents(e,{...o,version:s},n)}return(async()=>{let{transformers:o,version:s,...a}=r??{},i=$e(this.#t,a),u=await this.#d(e,i);return await this.#e.streamEvents(u,{...i,version:"v3",transformers:o})})()}async drawMermaidPng(e){let r=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(r)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,r){return this.#e.getState(e,r)}getStateHistory(e,r){return this.#e.getStateHistory(e,r)}getSubgraphs(e,r){return this.#e.getSubgraphs(e,r)}getSubgraphsAsync(e,r){return this.#e.getSubgraphsAsync(e,r)}updateState(e,r,n){return this.#e.updateState(e,r,n)}get builder(){return this.#e.builder}};function Jr(t){return new Wu(t)}var Jm=I.function().args(I.custom()).returns(I.union([I.boolean(),I.promise(I.boolean())])),Zm=I.function().args(I.custom(),I.custom(),I.custom()).returns(I.union([I.string(),I.promise(I.string())])),Qm=["approve","edit","reject"],Ym=I.enum(Qm),Xm=I.object({allowedDecisions:I.array(Ym),description:I.union([I.string(),Zm]).optional(),argsSchema:I.record(I.any()).optional(),when:Jm.optional()}),uS=I.object({interruptOn:I.record(I.union([I.boolean(),Xm])).optional(),descriptionPrefix:I.string().default("Tool execution requires approval")});var rf=`<role>
36
+ Context Extraction Assistant
37
+ </role>
38
+
39
+ <primary_objective>
40
+ Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
41
+ </primary_objective>
42
+
43
+ <objective_information>
44
+ 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.
45
+ 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.
46
+ </objective_information>
47
+
48
+ <instructions>
49
+ 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.
50
+ 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.
51
+ </instructions>
52
+
53
+ 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:
54
+
55
+ 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.
56
+ Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
57
+
58
+ <messages>
59
+ Messages to summarize:
60
+ {messages}
61
+ </messages>`;var nf=I.function().args(I.array(I.custom())).returns(I.union([I.number(),I.promise(I.number())])),ui=I.object({fraction:I.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:I.number().positive("Tokens must be greater than 0").optional(),messages:I.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"}),Zu=I.object({fraction:I.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:I.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:I.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"}),kS=I.object({model:I.custom(),trigger:I.union([ui,I.array(ui)]).optional(),keep:Zu.optional(),tokenCounter:nf.optional(),summaryPrompt:I.string().default(rf),trimTokensToSummarize:I.number().optional(),summaryPrefix:I.string().optional(),maxTokensBeforeSummary:I.number().optional(),messagesToKeep:I.number().optional()});var LS=I.object({model:I.string().or(I.instanceof(Yl)).optional(),systemPrompt:I.string().optional(),maxTools:I.number().optional(),alwaysInclude:I.array(I.string()).optional()});var GS=I.object({applyToInput:I.boolean().optional(),applyToOutput:I.boolean().optional(),applyToToolResults:I.boolean().optional()});var ZS=I.object({rules:I.record(I.string(),I.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var of=["continue","error","end"],sf="continue";var af=I.enum(of).default(sf);I.object({toolName:I.string().optional(),threadLimit:I.number().optional(),runLimit:I.number().optional(),exitBehavior:af});var ik=I.object({threadToolCallCount:I.record(I.string(),I.number()).default({}),runToolCallCount:I.record(I.string(),I.number()).default({})});var lf=I.enum(["pending","in_progress","completed"]).describe("Status of the todo"),uf=I.object({content:I.string().describe("Content of the todo item"),status:lf}),hk=I.object({todos:I.array(uf).default([])});var bk=I.object({threadLimit:I.number().optional(),runLimit:I.number().optional(),exitBehavior:I.enum(["error","end"]).optional()}),xk=I.object({threadModelCallCount:I.number().default(0),runModelCallCount:I.number().default(0)});var Us=I.object({maxRetries:I.number().min(0).default(2),retryOn:I.union([I.function().args(I.instanceof(Error)).returns(I.boolean()),I.array(I.custom())]).default(()=>()=>!0),backoffFactor:I.number().min(0).default(2),initialDelayMs:I.number().min(0).default(1e3),maxDelayMs:I.number().min(0).default(6e4),jitter:I.boolean().default(!0)});var Nk=I.object({onFailure:I.union([I.literal("error"),I.literal("continue"),I.function().args(I.instanceof(Error)).returns(I.string())]).default("continue")}).merge(Us);var Bk=I.object({tools:I.array(I.union([I.custom(),I.custom(),I.string()])).optional(),onFailure:I.union([I.literal("error"),I.literal("continue"),I.literal("raise"),I.literal("return_message"),I.function().args(I.instanceof(Error)).returns(I.string())]).default("continue")}).merge(Us);var oC=I.object({enableCaching:I.boolean().optional(),ttl:I.enum(["5m","1h"]).optional(),minMessagesToCache:I.number().optional(),unsupportedModelBehavior:I.enum(["ignore","warn","raise"]).optional()});var lC=I.object({enableCaching:I.boolean().optional(),ttl:I.enum(["5m","1h"]).optional(),minMessagesToCache:I.number().optional(),unsupportedModelBehavior:I.enum(["ignore","warn","raise"]).optional()});function jo(t,e){return t.lc_error_code=e,t.message=`${t.message}
62
+
63
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
64
+ `,t}function O(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 x(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 ci=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return ci=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 Lo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Do=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var k=class extends Error{},re=class t extends k{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new $t({message:n,cause:Do(r)});let s=r?.error;return e===400?new Zr(e,s,n,o):e===401?new Qr(e,s,n,o):e===403?new Yr(e,s,n,o):e===404?new Xr(e,s,n,o):e===409?new en(e,s,n,o):e===422?new tn(e,s,n,o):e===429?new rn(e,s,n,o):e>=500?new nn(e,s,n,o):new t(e,s,n,o)}},ne=class extends re{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},$t=class extends re{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ye=class extends $t{constructor({message:e}={}){super({message:e??"Request timed out."})}},Zr=class extends re{},Qr=class extends re{},Yr=class extends re{},Xr=class extends re{},en=class extends re{},tn=class extends re{},rn=class extends re{},nn=class extends re{},on=class extends k{constructor(){super("Could not parse response content as the length limit was reached")}},sn=class extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Xe=class extends Error{constructor(e){super(e)}},tr=class extends re{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let a=r;s=a.error;let i=a.error_description;i&&typeof i=="string"?o=i:s&&(o=s)}super(e,r,o,n),this.error_code=s}},Fo=class extends k{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var _f=/^[a-z][a-z0-9+.-]*:/i,Qu=t=>_f.test(t),we=t=>(we=Array.isArray,we(t)),di=we;function qs(t){return typeof t!="object"?{}:t??{}}function pi(t){if(!t)return!0;for(let e in t)return!1;return!0}function Yu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Uo(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Xu=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e};var ec=t=>{try{return JSON.parse(t)}catch{return}};var et=t=>new Promise(e=>setTimeout(e,t));var Nt="6.45.0";var oc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function wf(){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 bf=()=>{let t=wf();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Nt,"X-Stainless-OS":rc(Deno.build.os),"X-Stainless-Arch":tc(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":Nt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Nt,"X-Stainless-OS":rc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":tc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=xf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Nt,"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":Nt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function xf(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var tc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",rc=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"),nc,sc=()=>nc??(nc=bf());function Bs(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function mi(...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 Ks(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return mi({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function fi(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 hi(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 ic=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var gi="RFC3986",yi=t=>String(t),_i={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:yi},lc="RFC1738";var Gs=(t,e)=>(Gs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Gs(t,e)),tt=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var wi=1024,uc=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<s.length;i+=wi){let u=s.length>=wi?s.slice(i,i+wi):s,l=[];for(let c=0;c<u.length;++c){let p=u.charCodeAt(c);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===lc&&(p===40||p===41)){l[l.length]=u.charAt(c);continue}if(p<128){l[l.length]=tt[p];continue}if(p<2048){l[l.length]=tt[192|p>>6]+tt[128|p&63];continue}if(p<55296||p>=57344){l[l.length]=tt[224|p>>12]+tt[128|p>>6&63]+tt[128|p&63];continue}c+=1,p=65536+((p&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=tt[240|p>>18]+tt[128|p>>12&63]+tt[128|p>>6&63]+tt[128|p&63]}a+=l.join("")}return a};function cc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function bi(t,e){if(we(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var pc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},mc=function(t,e){Array.prototype.push.apply(t,we(e)?e:[e])},dc,le={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:uc,encodeValuesOnly:!1,format:gi,formatter:yi,indices:!1,serializeDate(t){return(dc??(dc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function If(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var xi={};function fc(t,e,r,n,o,s,a,i,u,l,c,p,d,g,y,w,_,f){let A=t,T=f,E=0,G=!1;for(;(T=T.get(xi))!==void 0&&!G;){let Y=T.get(t);if(E+=1,typeof Y<"u"){if(Y===E)throw new RangeError("Cyclic object value");G=!0}typeof T.get(xi)>"u"&&(E=0)}if(typeof l=="function"?A=l(e,A):A instanceof Date?A=d?.(A):r==="comma"&&we(A)&&(A=bi(A,function(Y){return Y instanceof Date?d?.(Y):Y})),A===null){if(s)return u&&!w?u(e,le.encoder,_,"key",g):e;A=""}if(If(A)||cc(A)){if(u){let Y=w?e:u(e,le.encoder,_,"key",g);return[y?.(Y)+"="+y?.(u(A,le.encoder,_,"value",g))]}return[y?.(e)+"="+y?.(String(A))]}let q=[];if(typeof A>"u")return q;let P;if(r==="comma"&&we(A))w&&u&&(A=bi(A,u)),P=[{value:A.length>0?A.join(",")||null:void 0}];else if(we(l))P=l;else{let Y=Object.keys(A);P=c?Y.sort(c):Y}let Q=i?String(e).replace(/\./g,"%2E"):String(e),te=n&&we(A)&&A.length===1?Q+"[]":Q;if(o&&we(A)&&A.length===0)return te+"[]";for(let Y=0;Y<P.length;++Y){let X=P[Y],C=typeof X=="object"&&typeof X.value<"u"?X.value:A[X];if(a&&C===null)continue;let U=p&&i?X.replace(/\./g,"%2E"):X,ee=we(A)?typeof r=="function"?r(te,U):te:te+(p?"."+U:"["+U+"]");f.set(t,E);let J=new WeakMap;J.set(xi,f),mc(q,fc(C,ee,r,n,o,s,a,i,r==="comma"&&w&&we(A)?null:u,l,c,p,d,g,y,w,_,J))}return q}function vf(t=le){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||le.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=gi;if(typeof t.format<"u"){if(!Gs(_i,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=_i[r],o=le.filter;(typeof t.filter=="function"||we(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in pc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=le.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:le.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:le.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:le.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:le.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?le.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:le.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:le.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:le.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:le.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:le.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:le.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:le.strictNullHandling}}function hc(t,e={}){let r=t,n=vf(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):we(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof r!="object"||r===null)return"";let i=pc[n.arrayFormat],u=i==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let d=0;d<o.length;++d){let g=o[d];n.skipNulls&&r[g]===null||mc(a,fc(r[g],g,i,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let c=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),c.length>0?p+c:""}function gc(t){return hc(t,{arrayFormat:"brackets"})}function wc(t){let e=0;for(let o of t)e+=o.length;let r=new Uint8Array(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var yc;function an(t){let e;return(yc??(e=new globalThis.TextEncoder,yc=e.encode.bind(e)))(t)}var _c;function Ai(t){let e;return(_c??(e=new globalThis.TextDecoder,_c=e.decode.bind(e)))(t)}var Pe,Oe,rr=class{constructor(){Pe.set(this,void 0),Oe.set(this,void 0),O(this,Pe,new Uint8Array,"f"),O(this,Oe,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?an(e):e;O(this,Pe,wc([x(this,Pe,"f"),r]),"f");let n=[],o;for(;(o=Sf(x(this,Pe,"f"),x(this,Oe,"f")))!=null;){if(o.carriage&&x(this,Oe,"f")==null){O(this,Oe,o.index,"f");continue}if(x(this,Oe,"f")!=null&&(o.index!==x(this,Oe,"f")+1||o.carriage)){n.push(Ai(x(this,Pe,"f").subarray(0,x(this,Oe,"f")-1))),O(this,Pe,x(this,Pe,"f").subarray(x(this,Oe,"f")),"f"),O(this,Oe,null,"f");continue}let s=x(this,Oe,"f")!==null?o.preceding-1:o.preceding,a=Ai(x(this,Pe,"f").subarray(0,s));n.push(a),O(this,Pe,x(this,Pe,"f").subarray(o.index),"f"),O(this,Oe,null,"f")}return n}flush(){return x(this,Pe,"f").length?this.decode(`
65
+ `):[]}};Pe=new WeakMap,Oe=new WeakMap;rr.NEWLINE_CHARS=new Set([`
66
+ `,"\r"]);rr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Sf(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function bc(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var Vs={off:0,error:200,warn:300,info:400,debug:500},Ii=(t,e,r)=>{if(t){if(Yu(Vs,t))return t;se(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Vs))}`)}};function qo(){}function Ws(t,e,r){return!e||Vs[t]>Vs[r]?qo:e[t].bind(e)}var kf={error:qo,warn:qo,info:qo,debug:qo},xc=new WeakMap;function se(t){let e=t.logger,r=t.logLevel??"off";if(!e)return kf;let n=xc.get(e);if(n&&n[0]===r)return n[1];let o={error:Ws("error",e,r),warn:Ws("warn",e,r),info:Ws("info",e,r),debug:Ws("debug",e,r)};return xc.set(e,[r,o]),o}var ct=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Bo,rt=class t{constructor(e,r,n){this.iterator=e,Bo.set(this,void 0),this.controller=r,O(this,Bo,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,a=n?se(n):console;async function*i(){if(s)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(let l of Cf(e,r))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(p){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),p}if(c&&c.error)throw new re(void 0,c.error,void 0,e.headers);yield o?{event:l.event,data:c}:c}else{let c;try{c=JSON.parse(l.data)}catch(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(l.event=="error")throw new re(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}u=!0}catch(l){if(Lo(l))return;throw l}finally{u||r.abort()}}return new t(i,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let i=new rr,u=fi(e);for await(let l of u)for(let c of i.decode(l))yield c;for(let l of i.flush())yield l}async function*a(){if(o)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let i=!1;try{for await(let u of s())i||u&&(yield JSON.parse(u));i=!0}catch(u){if(Lo(u))return;throw u}finally{i||r.abort()}}return new t(a,r,n)}[(Bo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),r.push(a)}return s.shift()}});return[new t(()=>o(e),this.controller,x(this,Bo,"f")),new t(()=>o(r),this.controller,x(this,Bo,"f"))]}toReadableStream(){let e=this,r;return mi({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let a=an(JSON.stringify(o)+`
67
+ `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Cf(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new k("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 k("Attempted to iterate over a response with no body");let r=new vi,n=new rr,o=fi(t.body);for await(let s of Ef(o))for(let a of n.decode(s)){let i=r.decode(a);i&&(yield i)}for(let s of n.flush()){let a=r.decode(s);a&&(yield a)}}async function*Ef(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?an(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=bc(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var vi=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
68
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Pf(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Pf(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Hs(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return se(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):rt.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let d=await r.json();return Ti(d,r)}return await r.text()})();return se(t).debug(`[${n}] response parsed`,ct({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-s})),a}function Ti(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 Ko,nr=class t extends Promise{constructor(e,r,n=Hs){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Ko.set(this,void 0),O(this,Ko,e,"f")}_thenUnwrap(e){return new t(x(this,Ko,"f"),this.responsePromise,async(r,n)=>Ti(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(x(this,Ko,"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)}};Ko=new WeakMap;var Js,ln=class{constructor(e,r,n,o){Js.set(this,void 0),O(this,Js,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 k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await x(this,Js,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Js=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Go=class extends nr{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await Hs(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},be=class extends ln{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}},z=class extends ln{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:{...qs(this.options.query),after:r}}:null}},W=class extends ln{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:{...qs(this.options.query),after:e}}:null}},ie=class extends ln{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...qs(this.options.query),after:e}}:null}};var Mf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Rf="urn:ietf:params:oauth:grant-type:token-exchange",Zs=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Bs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r={grant_type:Rf,subject_token:e,subject_token_type:Mf[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let u=await n.text(),l;try{l=JSON.parse(u)}catch{}throw n.status===400||n.status===401||n.status===403?new tr(n.status,l,n.headers):re.generate(n.status,l,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new k("Token exchange response missing 'access_token' field");let s=o.access_token,a=o.expires_in??3600,i=Date.now()+a*1e3;return this.cachedToken={token:s,expiresAt:i},s}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let n=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-n}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Ci=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function un(t,e,r){return Ci(),new File(t,e??"unknown_file",r)}function Wo(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Qs=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",zt=async(t,e)=>Si(t.body)?{...t,body:await Ic(t.body,e)}:t,xe=async(t,e)=>({...t,body:await Ic(t.body,e)}),Ac=new WeakMap;function $f(t){let e=typeof t=="function"?t:t.fetch,r=Ac.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return Ac.set(e,n),n}var Ic=async(t,e)=>{if(!await $f(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,o])=>ki(r,n,o))),r},vc=t=>t instanceof Blob&&"name"in t,Nf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Qs(t)||vc(t)),Si=t=>{if(Nf(t))return!0;if(Array.isArray(t))return t.some(Si);if(t&&typeof t=="object"){for(let e in t)if(Si(t[e]))return!0}return!1},ki=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,un([await r.blob()],Wo(r)));else if(Qs(r))t.append(e,un([await new Response(Ks(r)).blob()],Wo(r)));else if(vc(r))t.append(e,r,Wo(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ki(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>ki(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Tc=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",zf=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Tc(t),jf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Vo(t,e,r){if(Ci(),t=await t,zf(t))return t instanceof File?t:un([await t.arrayBuffer()],t.name);if(jf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),un(await Ei(o),e,r)}let n=await Ei(t);if(e||(e=Wo(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return un(n,e,r)}async function Ei(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Tc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Qs(t))for await(let r of t)e.push(...await Ei(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Lf(t)}`)}return e}function Lf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var b=class{constructor(e){this._client=e}};function kc(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Sc=Object.freeze(Object.create(null)),Ff=(t=kc)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],a=r.reduce((c,p,d)=>{/[?#]/.test(p)&&(o=!0);let g=n[d],y=(o?encodeURIComponent:t)(""+g);return d!==n.length&&(g==null||typeof g=="object"&&g.toString===Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??Sc)??Sc)?.toString)&&(y=g+"",s.push({start:c.length+p.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),c+p+(d===n.length?"":y)},""),i=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=u.exec(i))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((c,p)=>c.start-p.start),s.length>0){let c=0,p=s.reduce((d,g)=>{let y=" ".repeat(g.start-c),w="^".repeat(g.length);return c=g.start+g.length,d+y+w},"");throw new k(`Path parameters result in path with invalid segments:
69
+ ${s.map(d=>d.error).join(`
70
+ `)}
71
+ ${a}
72
+ ${p}`)}return a},h=Ff(kc);var or=class extends b{list(e,r={},n){return this._client.getAPIList(h`/chat/completions/${e}/messages`,z,{query:r,...n,__security:{bearerAuth:!0}})}};function Ho(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ec(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Jo(t){return t?.$brand==="auto-parseable-response-format"}function sr(t){return t?.$brand==="auto-parseable-tool"}function Pc(t,e){return!e||!Pi(e)?{...t,choices:t.choices.map(r=>(Mc(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Zo(t,e)}function Zo(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new on;if(n.finish_reason==="content_filter")throw new sn;return Mc(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Bf(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?qf(e,n.message.content):null}}});return{...t,choices:r}}function qf(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Bf(t,e){let r=t.tools?.find(n=>Ho(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:sr(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Oc(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>Ho(n)&&n.function?.name===e.function.name);return Ho(r)&&(sr(r)||r?.function.strict||!1)}function Pi(t){return Jo(t.response_format)?!0:t.tools?.some(e=>sr(e)||e.type==="function"&&e.function.strict===!0)??!1}function Mc(t){for(let e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Rc(t){for(let e of t??[]){if(e.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new k(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var cn=t=>t?.role==="assistant",Oi=t=>t?.role==="tool";var Ys,Xs,ea,Qo,Yo,ta,Xo,dt,ra,es,na,oa,dn,$c,Nc,jt=class{constructor(){Ys.add(this),this.controller=new AbortController,Xs.set(this,void 0),ea.set(this,()=>{}),Qo.set(this,()=>{}),Yo.set(this,void 0),ta.set(this,()=>{}),Xo.set(this,()=>{}),dt.set(this,{}),ra.set(this,[]),es.set(this,!1),na.set(this,!1),oa.set(this,!1),dn.set(this,!1),O(this,Xs,new Promise((e,r)=>{O(this,ea,e,"f"),O(this,Qo,r,"f")}),"f"),O(this,Yo,new Promise((e,r)=>{O(this,ta,e,"f"),O(this,Xo,r,"f")}),"f"),x(this,Xs,"f").catch(()=>{}),x(this,Yo,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},x(this,Ys,"m",Nc).bind(this))},0)}_connected(){this.ended||(x(this,ea,"f").call(this),this._emit("connect"))}get ended(){return x(this,es,"f")}get errored(){return x(this,na,"f")}get aborted(){return x(this,oa,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),x(this,ra,"f").push({signal:e,listener:r})}on(e,r){return(x(this,dt,"f")[e]||(x(this,dt,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=x(this,dt,"f")[e];if(!n)return this;let o=n.findIndex(s=>s.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(x(this,dt,"f")[e]||(x(this,dt,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{O(this,dn,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){O(this,dn,!0,"f"),await x(this,Yo,"f")}_emit(e,...r){if(x(this,es,"f"))return;e==="end"&&(x(this,Ys,"m",$c).call(this),O(this,es,!0,"f"),x(this,ta,"f").call(this));let n=x(this,dt,"f")[e];if(n&&(x(this,dt,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!x(this,dn,"f")&&!n?.length&&Promise.reject(o),x(this,Qo,"f").call(this,o),x(this,Xo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!x(this,dn,"f")&&!n?.length&&Promise.reject(o),x(this,Qo,"f").call(this,o),x(this,Xo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};Xs=new WeakMap,ea=new WeakMap,Qo=new WeakMap,Yo=new WeakMap,ta=new WeakMap,Xo=new WeakMap,dt=new WeakMap,ra=new WeakMap,es=new WeakMap,na=new WeakMap,oa=new WeakMap,dn=new WeakMap,Ys=new WeakSet,$c=function(){for(let{signal:e,listener:r}of x(this,ra,"f").splice(0))e.removeEventListener("abort",r)},Nc=function(e){if(O(this,na,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new ne),e instanceof ne)return O(this,oa,!0,"f"),this._emit("abort",e);if(e instanceof k)return this._emit("error",e);if(e instanceof Error){let r=new k(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new k(String(e)))};function zc(t){return typeof t.parse=="function"}var Se,Mi,sa,Ri,$i,Ni,jc,Lc,Kf=10,pn=class extends jt{constructor(){super(...arguments),Se.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),Oi(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(cn(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new k("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),x(this,Se,"m",Mi).call(this)}async finalMessage(){return await this.done(),x(this,Se,"m",sa).call(this)}async finalFunctionToolCall(){return await this.done(),x(this,Se,"m",Ri).call(this)}async finalFunctionToolCallResult(){return await this.done(),x(this,Se,"m",$i).call(this)}async totalUsage(){return await this.done(),x(this,Se,"m",Ni).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=x(this,Se,"m",sa).call(this);r&&this._emit("finalMessage",r);let n=x(this,Se,"m",Mi).call(this);n&&this._emit("finalContent",n);let o=x(this,Se,"m",Ri).call(this);o&&this._emit("finalFunctionToolCall",o);let s=x(this,Se,"m",$i).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",x(this,Se,"m",Ni).call(this))}async _createChatCompletion(e,r,n){this._listenForAbort(n?.signal),x(this,Se,"m",jc).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Zo(o,r))}async _runChatCompletion(e,r,n){for(let o of r.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n,o){let s="tool",{tool_choice:a="auto",stream:i,...u}=r,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=Kf,afterCompletion:p}=o||{},d=r.tools.map(_=>{if(sr(_)){if(!_.$callback)throw new k("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),g={};for(let _ of d)_.type==="function"&&(g[_.function.name||_.function.function.name]=_.function);let y="tools"in r?d.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(let _ of r.messages)this._addMessage(_,!1);let w=async _=>{if(_.type!=="function")return{message:void 0,functionCalled:!1};let f=_.id,{name:A,arguments:T}=_.function,E=g[A];if(!E){let P=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(g).map(Q=>JSON.stringify(Q)).join(", ")}. Please try again`;return{message:{role:s,tool_call_id:f,content:P},functionCalled:!1}}if(l&&l!==A){let P=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:s,tool_call_id:f,content:P},functionCalled:!1}}let G;if(zc(E)){let P;try{P=await E.parse(T)}catch(Q){let te=Q instanceof Error?Q.message:String(Q);return{message:{role:s,tool_call_id:f,content:te},functionCalled:!1}}G=await E.function(P,n)}else G=await E.function(T,n);let q=x(this,Se,"m",Lc).call(this,G);return{message:{role:s,tool_call_id:f,content:q},functionCalled:!0}};for(let _=0;_<c;++_){let f=await this._createChatCompletion(e,{...u,tool_choice:a,tools:y,messages:[...this.messages]},o),A=f.choices[0]?.message;if(!A)throw new k("missing message in ChatCompletion response");if(!A.tool_calls?.length){await p?.(f,n);return}if(l||r.parallel_tool_calls===!1)for(let T of A.tool_calls){let E=await w(T);if(E.message&&this._addMessage(E.message),l&&E.functionCalled){await p?.(f,n);return}}else{let T=await Promise.allSettled(A.tool_calls.map(w));for(let E of T)if(E.status==="rejected")throw E.reason;for(let E of T)E.status==="fulfilled"&&E.value.message&&this._addMessage(E.value.message)}await p?.(f,n)}}};Se=new WeakSet,Mi=function(){return x(this,Se,"m",sa).call(this).content??null},sa=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(cn(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},Ri=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(cn(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}}},$i=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Oi(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}},Ni=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},jc=function(e){if(e.n!=null&&e.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Lc=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ts=class t extends pn{static runTools(e,r,n){let o=new t,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),cn(e)&&e.content&&this._emit("content",e.content)}};var pe={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},zi=class extends Error{},ji=class extends Error{};function Gf(t,e=pe.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Wf(t.trim(),e)}var Wf=(t,e)=>{let r=t.length,n=0,o=d=>{throw new zi(`${d} at position ${n}`)},s=d=>{throw new ji(`${d} at position ${n}`)},a=()=>(p(),n>=r&&o("Unexpected end of input"),t[n]==='"'?i():t[n]==="{"?u():t[n]==="["?l():t.substring(n,n+4)==="null"||pe.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||pe.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||pe.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||pe.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||pe.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||pe.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):c()),i=()=>{let d=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(d,++n-Number(g)))}catch(y){s(String(y))}else if(pe.STR&e)try{return JSON.parse(t.substring(d,n-Number(g))+'"')}catch{return JSON.parse(t.substring(d,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{n++,p();let d={};try{for(;t[n]!=="}";){if(p(),n>=r&&pe.OBJ&e)return d;let g=i();p(),n++;try{let y=a();Object.defineProperty(d,g,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(pe.OBJ&e)return d;throw y}p(),t[n]===","&&n++}}catch{if(pe.OBJ&e)return d;o("Expected '}' at end of object")}return n++,d},l=()=>{n++;let d=[];try{for(;t[n]!=="]";)d.push(a()),p(),t[n]===","&&n++}catch{if(pe.ARR&e)return d;o("Expected ']' at end of array")}return n++,d},c=()=>{if(n===0){t==="-"&&pe.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(g){if(pe.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(g))}}let d=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(pe.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(d,n))}catch{t.substring(d,n)==="-"&&pe.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(d,t.lastIndexOf("e")))}catch(y){s(String(y))}}},p=()=>{for(;n<r&&`
73
+ \r `.includes(t[n]);)n++};return a()},Li=t=>Gf(t,pe.ALL^pe.NUM);var ue,pt,mn,Lt,Di,aa,Fi,Ui,qi,ia,Bi,Dc,ar=class t extends pn{constructor(e){super(),ue.add(this),pt.set(this,void 0),mn.set(this,void 0),Lt.set(this,void 0),O(this,pt,e,"f"),O(this,mn,[],"f")}get currentChatCompletionSnapshot(){return x(this,Lt,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion,this._listenForAbort(n?.signal),x(this,ue,"m",Di).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)x(this,ue,"m",Fi).call(this,s);if(o.controller.signal?.aborted)throw new ne;return this._addChatCompletion(x(this,ue,"m",ia).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),x(this,ue,"m",Di).call(this),this._connected();let n=rt.fromReadableStream(e,this.controller),o;for await(let s of n)o&&o!==s.id&&this._addChatCompletion(x(this,ue,"m",ia).call(this)),x(this,ue,"m",Fi).call(this,s),o=s.id;if(n.controller.signal?.aborted)throw new ne;return this._addChatCompletion(x(this,ue,"m",ia).call(this))}[(pt=new WeakMap,mn=new WeakMap,Lt=new WeakMap,ue=new WeakSet,Di=function(){this.ended||O(this,Lt,void 0,"f")},aa=function(r){let n=x(this,mn,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},x(this,mn,"f")[r.index]=n,n)},Fi=function(r){if(this.ended)return;let n=x(this,ue,"m",Dc).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let s=n.choices[o.index];o.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",o.delta.content,s.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),o.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:s.message.refusal}),o.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:s.logprobs?.content??[]}),o.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let a=x(this,ue,"m",aa).call(this,s);s.finish_reason&&(x(this,ue,"m",qi).call(this,s),a.current_tool_call_index!=null&&x(this,ue,"m",Ui).call(this,s,a.current_tool_call_index));for(let i of o.delta.tool_calls??[])a.current_tool_call_index!==i.index&&(x(this,ue,"m",qi).call(this,s),a.current_tool_call_index!=null&&x(this,ue,"m",Ui).call(this,s,a.current_tool_call_index)),a.current_tool_call_index=i.index;for(let i of o.delta.tool_calls??[]){let u=s.message.tool_calls?.[i.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:i.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:i.function?.arguments??""}):(u?.type,void 0))}}},Ui=function(r,n){if(x(this,ue,"m",aa).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let a=x(this,pt,"f")?.tools?.find(i=>Ho(i)&&i.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:sr(a)?a.$parseRaw(s.function.arguments):a?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},qi=function(r){let n=x(this,ue,"m",aa).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=x(this,ue,"m",Bi).call(this);this._emit("content.done",{content:r.message.content,parsed:o?o.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},ia=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=x(this,Lt,"f");if(!r)throw new k("request ended without sending any chunks");return O(this,Lt,void 0,"f"),O(this,mn,[],"f"),Vf(r,x(this,pt,"f"))},Bi=function(){let r=x(this,pt,"f")?.response_format;return Jo(r)?r:null},Dc=function(r){var n,o,s,a;let i=x(this,Lt,"f"),{choices:u,...l}=r;i?Object.assign(i,l):i=O(this,Lt,{...l,choices:[]},"f");for(let{delta:c,finish_reason:p,index:d,logprobs:g=null,...y}of r.choices){let w=i.choices[d];if(w||(w=i.choices[d]={finish_reason:p,index:d,message:{},logprobs:g,...y}),g)if(!w.logprobs)w.logprobs=Object.assign({},g);else{let{content:q,refusal:P,...Q}=g;Object.assign(w.logprobs,Q),q&&((n=w.logprobs).content??(n.content=[]),w.logprobs.content.push(...q)),P&&((o=w.logprobs).refusal??(o.refusal=[]),w.logprobs.refusal.push(...P))}if(p&&(w.finish_reason=p,x(this,pt,"f")&&Pi(x(this,pt,"f")))){if(p==="length")throw new on;if(p==="content_filter")throw new sn}if(Object.assign(w,y),!c)continue;let{content:_,refusal:f,function_call:A,role:T,tool_calls:E,...G}=c;if(Object.assign(w.message,G),f&&(w.message.refusal=(w.message.refusal||"")+f),T&&(w.message.role=T),A&&(w.message.function_call?(A.name&&(w.message.function_call.name=A.name),A.arguments&&((s=w.message.function_call).arguments??(s.arguments=""),w.message.function_call.arguments+=A.arguments)):w.message.function_call=A),_&&(w.message.content=(w.message.content||"")+_,!w.message.refusal&&x(this,ue,"m",Bi).call(this)&&(w.message.parsed=w.message.content.trim()?Li(w.message.content):null)),E){w.message.tool_calls||(w.message.tool_calls=[]);for(let{index:q,id:P,type:Q,function:te,...Y}of E){let X=(a=w.message.tool_calls)[q]??(a[q]={});Object.assign(X,Y),P&&(X.id=P),Q&&(X.type=Q),te&&(X.function??(X.function={name:te.name??"",arguments:""})),te?.name&&(X.function.name=te.name),te?.arguments&&(X.function.arguments+=te.arguments,Oc(x(this,pt,"f"),X)&&(X.function.parsed_arguments=Li(X.function.arguments)))}}}return i},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new rt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Vf(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:a,...i}=t,u={...i,id:r,choices:n.map(({message:l,finish_reason:c,index:p,logprobs:d,...g})=>{if(!c)throw new k(`missing finish_reason for choice ${p}`);let{content:y=null,function_call:w,tool_calls:_,...f}=l,A=l.role;if(!A)throw new k(`missing role for choice ${p}`);if(w){let{arguments:T,name:E}=w;if(T==null)throw new k(`missing function_call.arguments for choice ${p}`);if(!E)throw new k(`missing function_call.name for choice ${p}`);return{...g,message:{content:y,function_call:{arguments:T,name:E},role:A,refusal:l.refusal??null},finish_reason:c,index:p,logprobs:d}}return _?{...g,index:p,finish_reason:c,logprobs:d,message:{...f,role:A,content:y,refusal:l.refusal??null,tool_calls:_.map((T,E)=>{let{function:G,type:q,id:P,...Q}=T,{arguments:te,name:Y,...X}=G||{};if(P==null)throw new k(`missing choices[${p}].tool_calls[${E}].id
74
+ ${la(t)}`);if(q==null)throw new k(`missing choices[${p}].tool_calls[${E}].type
75
+ ${la(t)}`);if(Y==null)throw new k(`missing choices[${p}].tool_calls[${E}].function.name
76
+ ${la(t)}`);if(te==null)throw new k(`missing choices[${p}].tool_calls[${E}].function.arguments
77
+ ${la(t)}`);return{...Q,id:P,type:q,function:{...X,name:Y,arguments:te}}})}}:{...g,message:{...f,content:y,role:A,refusal:l.refusal??null},finish_reason:c,index:p,logprobs:d}}),created:o,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Pc(u,e)}function la(t){return JSON.stringify(t)}var rs=class t extends ar{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let o=new t(r),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,o,s)),o}};var mt=class extends b{constructor(){super(...arguments),this.messages=new or(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",z,{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 Rc(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Zo(n,e))}runTools(e,r){return e.stream?rs.runTools(this._client,e,r):ts.runTools(this._client,e,r)}stream(e,r){return ar.createChatCompletion(this._client,e,r)}};mt.Messages=or;var Dt=class extends b{constructor(){super(...arguments),this.completions=new mt(this._client)}};Dt.Completions=mt;var fn=class extends b{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",z,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var hn=class extends b{list(e={},r){return this._client.getAPIList("/organization/audit_logs",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var gn=class extends b{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",W,{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",be,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",be,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var yn=class extends b{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 _n=class extends b{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",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var wn=class extends b{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",ie,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var bn=class extends b{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",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var xn=class extends b{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 An=class extends b{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`,ie,{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 In=class extends b{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`,ie,{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 Ft=class extends b{constructor(){super(...arguments),this.users=new In(this._client),this.roles=new An(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",ie,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Ft.Users=In;Ft.Roles=An;var vn=class extends b{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`,W,{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 Tn=class extends b{list(e,r={},n){return this._client.getAPIList(h`/organization/projects/${e}/certificates`,W,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(h`/organization/projects/${e}/certificates/activate`,be,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(h`/organization/projects/${e}/certificates/deactivate`,be,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Sn=class extends b{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 kn=class extends b{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 Cn=class extends b{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 En=class extends b{listRateLimits(e,r={},n){return this._client.getAPIList(h`/organization/projects/${e}/rate_limits`,W,{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 Pn=class extends b{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`,ie,{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 On=class extends b{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`,W,{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}})}};var Mn=class extends b{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`,W,{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 Rn=class extends b{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`,ie,{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 ir=class extends b{constructor(){super(...arguments),this.roles=new Rn(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`,ie,{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}})}};ir.Roles=Rn;var $n=class extends b{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`,ie,{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 lr=class extends b{constructor(){super(...arguments),this.roles=new $n(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`,W,{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}})}};lr.Roles=$n;var me=class extends b{constructor(){super(...arguments),this.users=new lr(this._client),this.serviceAccounts=new On(this._client),this.apiKeys=new vn(this._client),this.rateLimits=new En(this._client),this.modelPermissions=new Cn(this._client),this.hostedToolPermissions=new kn(this._client),this.groups=new ir(this._client),this.roles=new Pn(this._client),this.dataRetention=new Sn(this._client),this.spendAlerts=new Mn(this._client),this.certificates=new Tn(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",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(h`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};me.Users=lr;me.ServiceAccounts=On;me.APIKeys=vn;me.RateLimits=En;me.ModelPermissions=Cn;me.HostedToolPermissions=kn;me.Groups=ir;me.Roles=Pn;me.DataRetention=Sn;me.SpendAlerts=Mn;me.Certificates=Tn;var Nn=class extends b{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`,ie,{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 ur=class extends b{constructor(){super(...arguments),this.roles=new Nn(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",W,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(h`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};ur.Roles=Nn;var fe=class extends b{constructor(){super(...arguments),this.auditLogs=new hn(this._client),this.adminAPIKeys=new fn(this._client),this.usage=new xn(this._client),this.invites=new _n(this._client),this.users=new ur(this._client),this.groups=new Ft(this._client),this.roles=new wn(this._client),this.dataRetention=new yn(this._client),this.spendAlerts=new bn(this._client),this.certificates=new gn(this._client),this.projects=new me(this._client)}};fe.AuditLogs=hn;fe.AdminAPIKeys=fn;fe.Usage=xn;fe.Invites=_n;fe.Users=ur;fe.Groups=Ft;fe.Roles=wn;fe.DataRetention=yn;fe.SpendAlerts=bn;fe.Certificates=gn;fe.Projects=me;var Ut=class extends b{constructor(){super(...arguments),this.organization=new fe(this._client)}};Ut.Organization=fe;var Fc=Symbol("brand.privateNullableHeaders");function*Ih(t){if(!t)return;if(Fc in t){let{values:n,nulls:o}=t;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():di(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=di(n[1])?n[1]:[n[1]],a=!1;for(let i of s)i!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,i])}}var S=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,a]of Ih(n)){let i=s.toLowerCase();o.has(i)||(e.delete(s),o.add(i)),a===null?(e.delete(s),r.add(i)):(e.append(s,a),r.delete(i))}}return{[Fc]:!0,values:e,nulls:r}};var zn=class extends b{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:S([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var jn=class extends b{create(e,r){return this._client.post("/audio/transcriptions",xe({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Ln=class extends b{create(e,r){return this._client.post("/audio/translations",xe({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var nt=class extends b{constructor(){super(...arguments),this.transcriptions=new jn(this._client),this.translations=new Ln(this._client),this.speech=new zn(this._client)}};nt.Transcriptions=jn;nt.Translations=Ln;nt.Speech=zn;var cr=class extends b{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",z,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(h`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var Dn=class extends b{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/assistants/${e}`,{...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/assistants/${e}`,{body:r,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",z,{query:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/assistants/${e}`,{...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Fn=class extends b{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Un=class extends b{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var qt=class extends b{constructor(){super(...arguments),this.sessions=new Fn(this._client),this.transcriptionSessions=new Un(this._client)}};qt.Sessions=Fn;qt.TranscriptionSessions=Un;var qn=class extends b{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(h`/chatkit/sessions/${e}/cancel`,{...r,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Bn=class extends b{retrieve(e,r){return this._client.get(h`/chatkit/threads/${e}`,{...r,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",W,{query:e,...r,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/chatkit/threads/${e}`,{...r,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(h`/chatkit/threads/${e}/items`,W,{query:r,...n,headers:S([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Bt=class extends b{constructor(){super(...arguments),this.sessions=new qn(this._client),this.threads=new Bn(this._client)}};Bt.Sessions=qn;Bt.Threads=Bn;var Kn=class extends b{create(e,r,n){return this._client.post(h`/threads/${e}/messages`,{body:r,...n,headers:S([{"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:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/threads/${e}/messages`,z,{query:r,...n,headers:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Gn=class extends b{retrieve(e,r,n){let{thread_id:o,run_id:s,...a}=r;return this._client.get(h`/threads/${o}/runs/${s}/steps/${e}`,{query:a,...n,headers:S([{"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`,z,{query:s,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Uc=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var De=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var he,pr,Ki,ot,ua,Fe,mr,Wn,dr,pa,Me,ca,da,ss,ns,os,qc,Bc,Kc,Gc,Wc,Vc,Hc,ft=class extends jt{constructor(){super(...arguments),he.add(this),Ki.set(this,[]),ot.set(this,{}),ua.set(this,{}),Fe.set(this,void 0),mr.set(this,void 0),Wn.set(this,void 0),dr.set(this,void 0),pa.set(this,void 0),Me.set(this,void 0),ca.set(this,void 0),da.set(this,void 0),ss.set(this,void 0)}[(Ki=new WeakMap,ot=new WeakMap,ua=new WeakMap,Fe=new WeakMap,mr=new WeakMap,Wn=new WeakMap,dr=new WeakMap,pa=new WeakMap,Me=new WeakMap,ca=new WeakMap,da=new WeakMap,ss=new WeakMap,he=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new pr;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let n=rt.fromReadableStream(e,this.controller);for await(let o of n)x(this,he,"m",ns).call(this,o);if(n.controller.signal?.aborted)throw new ne;return this._addRun(x(this,he,"m",os).call(this))}toReadableStream(){return new rt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new pr;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)x(this,he,"m",ns).call(this,i);if(a.controller.signal?.aborted)throw new ne;return this._addRun(x(this,he,"m",os).call(this))}static createThreadAssistantStream(e,r,n){let o=new pr;return o._run(()=>o._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,r,n,o){let s=new pr;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return x(this,ca,"f")}currentRun(){return x(this,da,"f")}currentMessageSnapshot(){return x(this,Fe,"f")}currentRunStepSnapshot(){return x(this,ss,"f")}async finalRunSteps(){return await this.done(),Object.values(x(this,ot,"f"))}async finalMessages(){return await this.done(),Object.values(x(this,ua,"f"))}async finalRun(){if(await this.done(),!x(this,mr,"f"))throw Error("Final run was not received.");return x(this,mr,"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 a of s)x(this,he,"m",ns).call(this,a);if(s.controller.signal?.aborted)throw new ne;return this._addRun(x(this,he,"m",os).call(this))}async _createAssistantStream(e,r,n,o){this._listenForAbort(o?.signal);let s={...n,stream:!0},a=await e.create(r,s,{...o,signal:this.controller.signal});this._connected();for await(let i of a)x(this,he,"m",ns).call(this,i);if(a.controller.signal?.aborted)throw new ne;return this._addRun(x(this,he,"m",os).call(this))}static accumulateDelta(e,r){for(let[n,o]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=o;continue}let s=e[n];if(s==null){e[n]=o;continue}if(n==="index"||n==="type"){e[n]=o;continue}if(typeof s=="string"&&typeof o=="string")s+=o;else if(typeof s=="number"&&typeof o=="number")s+=o;else if(Uo(s)&&Uo(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...o);continue}for(let a of o){if(!Uo(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);let u=s[i];u==null?s.push(a):s[i]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};pr=ft,ns=function(e){if(!this.ended)switch(O(this,ca,e,"f"),x(this,he,"m",Kc).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":x(this,he,"m",Hc).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,he,"m",Bc).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":x(this,he,"m",qc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},os=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!x(this,mr,"f"))throw Error("Final run has not been received");return x(this,mr,"f")},qc=function(e){let[r,n]=x(this,he,"m",Wc).call(this,e,x(this,Fe,"f"));O(this,Fe,r,"f"),x(this,ua,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,a=r.content[o.index];if(a&&a.type=="text")this._emit("textDelta",s,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=x(this,Wn,"f")){if(x(this,dr,"f"))switch(x(this,dr,"f").type){case"text":this._emit("textDone",x(this,dr,"f").text,x(this,Fe,"f"));break;case"image_file":this._emit("imageFileDone",x(this,dr,"f").image_file,x(this,Fe,"f"));break}O(this,Wn,o.index,"f")}O(this,dr,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(x(this,Wn,"f")!==void 0){let o=e.data.content[x(this,Wn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,x(this,Fe,"f"));break;case"text":this._emit("textDone",o.text,x(this,Fe,"f"));break}}x(this,Fe,"f")&&this._emit("messageDone",e.data),O(this,Fe,void 0,"f")}},Bc=function(e){let r=x(this,he,"m",Gc).call(this,e);switch(O(this,ss,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==x(this,pa,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(x(this,Me,"f")&&this._emit("toolCallDone",x(this,Me,"f")),O(this,pa,s.index,"f"),O(this,Me,r.step_details.tool_calls[s.index],"f"),x(this,Me,"f")&&this._emit("toolCallCreated",x(this,Me,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":O(this,ss,void 0,"f"),e.data.step_details.type=="tool_calls"&&x(this,Me,"f")&&(this._emit("toolCallDone",x(this,Me,"f")),O(this,Me,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Kc=function(e){x(this,Ki,"f").push(e),this._emit("event",e)},Gc=function(e){switch(e.event){case"thread.run.step.created":return x(this,ot,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=x(this,ot,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let o=pr.accumulateDelta(r,n.delta);x(this,ot,"f")[e.data.id]=o}return x(this,ot,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":x(this,ot,"f")[e.data.id]=e.data;break}if(x(this,ot,"f")[e.data.id])return x(this,ot,"f")[e.data.id];throw new Error("No snapshot available")},Wc=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let a=r.content[s.index];r.content[s.index]=x(this,he,"m",Vc).call(this,s,a)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Vc=function(e,r){return pr.accumulateDelta(r,e)},Hc=function(e){switch(O(this,da,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":O(this,mr,e.data,"f"),x(this,Me,"f")&&(this._emit("toolCallDone",x(this,Me,"f")),O(this,Me,void 0,"f"));break;case"thread.run.cancelling":break}};var fr=class extends b{constructor(){super(...arguments),this.steps=new Gn(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:S([{"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:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/threads/${e}/runs`,z,{query:r,...n,headers:S([{"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:S([{"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 ft.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=S([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await et(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return ft.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:S([{"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 ft.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};fr.Steps=Gn;var Kt=class extends b{constructor(){super(...arguments),this.runs=new fr(this._client),this.messages=new Kn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/threads/${e}`,{...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(h`/threads/${e}`,{body:r,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/threads/${e}`,{...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:S([{"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 ft.createThreadAssistantStream(e,this._client.beta.threads,r)}};Kt.Runs=fr;Kt.Messages=Kn;var Ue=class extends b{constructor(){super(...arguments),this.realtime=new qt(this._client),this.chatkit=new Bt(this._client),this.assistants=new Dn(this._client),this.threads=new Kt(this._client)}};Ue.Realtime=qt;Ue.ChatKit=Bt;Ue.Assistants=Dn;Ue.Threads=Kt;var hr=class extends b{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Vn=class extends b{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(h`/containers/${o}/files/${e}/content`,{...n,headers:S([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var gr=class extends b{constructor(){super(...arguments),this.content=new Vn(this._client)}create(e,r,n){return this._client.post(h`/containers/${e}/files`,zt({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`,z,{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:S([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};gr.Content=Vn;var Gt=class extends b{constructor(){super(...arguments),this.files=new gr(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",z,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/containers/${e}`,{...r,headers:S([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Gt.Files=gr;var Hn=class extends b{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`,W,{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 Wt=class extends b{constructor(){super(...arguments),this.items=new Hn(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}})}};Wt.Items=Hn;var yr=class extends b{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&se(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:o},...r,__security:{bearerAuth:!0}});return n?s:(se(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{let u=i.embedding;i.embedding=Uc(u)}),a)))}};var Jn=class extends b{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`,z,{query:s,...n,__security:{bearerAuth:!0}})}};var _r=class extends b{constructor(){super(...arguments),this.outputItems=new Jn(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`,z,{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}})}};_r.OutputItems=Jn;var Vt=class extends b{constructor(){super(...arguments),this.runs=new _r(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",z,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Vt.Runs=_r;var wr=class extends b{create(e,r){return this._client.post("/files",xe({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",z,{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:S([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),a=await this.retrieve(e);for(;!a.status||!o.has(a.status);)if(await et(r),a=await this.retrieve(e),Date.now()-s>n)throw new Ye({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};var Zn=class extends b{};var Qn=class extends b{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 br=class extends b{constructor(){super(...arguments),this.graders=new Qn(this._client)}};br.Graders=Qn;var Yn=class extends b{create(e,r,n){return this._client.getAPIList(h`/fine_tuning/checkpoints/${e}/permissions`,be,{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`,W,{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 xr=class extends b{constructor(){super(...arguments),this.permissions=new Yn(this._client)}};xr.Permissions=Yn;var Xn=class extends b{list(e,r={},n){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/checkpoints`,z,{query:r,...n,__security:{bearerAuth:!0}})}};var Ar=class extends b{constructor(){super(...arguments),this.checkpoints=new Xn(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",z,{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`,z,{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}})}};Ar.Checkpoints=Xn;var qe=class extends b{constructor(){super(...arguments),this.methods=new Zn(this._client),this.jobs=new Ar(this._client),this.checkpoints=new xr(this._client),this.alpha=new br(this._client)}};qe.Methods=Zn;qe.Jobs=Ar;qe.Checkpoints=xr;qe.Alpha=br;var eo=class extends b{};var Ht=class extends b{constructor(){super(...arguments),this.graderModels=new eo(this._client)}};Ht.GraderModels=eo;var Ir=class extends b{createVariation(e,r){return this._client.post("/images/variations",xe({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",xe({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var vr=class extends b{retrieve(e,r){return this._client.get(h`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",be,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var Tr=class extends b{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var to=class extends b{accept(e,r,n){return this._client.post(h`/realtime/calls/${e}/accept`,{body:r,...n,headers:S([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(h`/realtime/calls/${e}/hangup`,{...r,headers:S([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(h`/realtime/calls/${e}/refer`,{body:r,...n,headers:S([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(h`/realtime/calls/${e}/reject`,{body:r,...n,headers:S([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var ro=class extends b{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var ht=class extends b{constructor(){super(...arguments),this.clientSecrets=new ro(this._client),this.calls=new to(this._client)}};ht.ClientSecrets=ro;ht.Calls=to;function Jc(t,e){if(!e||!eg(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 Zc(t,r)&&Re(r),r}return Gi(t,e)}function Gi(t,e){let r=!t.status||t.status==="completed",n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:r?ng(e,s):null};if(s.type==="message"){let a=s.content.map(i=>i.type==="output_text"?{...i,parsed:r?Xh(e,i.text):null}:i);return{...s,content:a}}return s}),o=Object.assign({},t,{output:n});return Zc(t,o)&&Re(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let s of o.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),o}function Xh(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function eg(t){return!!Jo(t.text?.format)}function tg(t){return t?.$brand==="auto-parseable-tool"}function rg(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function ng(t,e){let r=rg(t.tools??[],e.name);return{...e,...e,parsed_arguments:tg(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Zc(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function Re(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}function Yc(t,e){if(!e){if(t.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Qc(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&Re(e);break}case"response.output_item.done":{K(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&Re(e);break}case"response.content_part.added":{let r=K(e,t.output_index),n=r.type,o=t.part;n==="message"&&o.type!=="reasoning_text"?(r.content.push(structuredClone(o)),o.type==="output_text"&&Re(e)):n==="reasoning"&&o.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(o)));break}case"response.content_part.done":{let r=K(e,t.output_index),n=t.part;if(r.type==="message"&&n.type!=="reasoning_text")ze(r.content,t.content_index),r.content[t.content_index]=structuredClone(n),n.type==="output_text"&&Re(e);else if(r.type==="reasoning"&&n.type==="reasoning_text"){let o=r.content;if(!o)throw new k(`missing content at index ${t.content_index}`);ze(o,t.content_index),o[t.content_index]=structuredClone(n)}break}case"response.output_text.delta":{let r=K(e,t.output_index);if(r.type==="message"){let n=ze(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=K(e,t.output_index);if(r.type==="message"){let n=ze(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.text=t.text,Re(e)}break}case"response.output_text.annotation.added":{let r=K(e,t.output_index);if(r.type==="message"){let n=ze(r.content,t.content_index);if(n.type!=="output_text")throw new k(`expected content to be 'output_text', got ${n.type}`);n.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=K(e,t.output_index);if(r.type==="message"){let n=ze(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.refusal+=t.delta}break}case"response.refusal.done":{let r=K(e,t.output_index);if(r.type==="message"){let n=ze(r.content,t.content_index);if(n.type!=="refusal")throw new k(`expected content to be 'refusal', got ${n.type}`);n.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=K(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=K(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=K(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new k(`missing content at index ${t.content_index}`);let n=ze(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.reasoning_text.done":{let r=K(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new k(`missing content at index ${t.content_index}`);let n=ze(r.content,t.content_index);if(n.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${n.type}`);n.text=t.text}break}case"response.reasoning_summary_part.added":{let r=K(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=K(e,t.output_index);r.type==="reasoning"&&(ze(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=K(e,t.output_index);if(r.type==="reasoning"){let n=ze(r.summary,t.summary_index);n.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=K(e,t.output_index);if(r.type==="reasoning"){let n=ze(r.summary,t.summary_index);n.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=K(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=K(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=K(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=K(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=K(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=K(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=K(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=K(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=K(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=K(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=K(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=K(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=K(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=K(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=K(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=K(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=K(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=K(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=K(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=K(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=K(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=Qc(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:og(t)}return e}function Qc(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&Re(e),e}function K(t,e){let r=t.output[e];if(!r)throw new k(`missing output at index ${e}`);return r}function ze(t,e){let r=t[e];if(!r)throw new k(`missing content at index ${e}`);return r}function og(t){throw new k(`Unhandled response stream event: ${JSON.stringify(t)}`)}var as,ma,Sr,fa,Xc,ed,td,ha=class t extends jt{constructor(e){super(),as.add(this),ma.set(this,void 0),Sr.set(this,void 0),fa.set(this,void 0),O(this,ma,e,"f")}static createResponse(e,r,n){let o=new t(r);return o._run(()=>o._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,r,n){this._listenForAbort(n?.signal),x(this,as,"m",Xc).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 a of o)x(this,as,"m",ed).call(this,a,s);if(o.controller.signal?.aborted)throw new ne;return x(this,as,"m",td).call(this)}[(ma=new WeakMap,Sr=new WeakMap,fa=new WeakMap,as=new WeakSet,Xc=function(){this.ended||O(this,Sr,void 0,"f")},ed=function(r,n){if(this.ended)return;let o=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},s=Yc(r,x(this,Sr,"f"));switch(O(this,Sr,s,"f"),o("event",r),r.type){case"response.output_text.delta":{let a=s.output[r.output_index];if(!a)throw new k(`missing output at index ${r.output_index}`);if(a.type==="message"){let i=a.content[r.content_index];if(!i)throw new k(`missing content at index ${r.content_index}`);if(i.type!=="output_text")throw new k(`expected content to be 'output_text', got ${i.type}`);o("response.output_text.delta",{...r,snapshot:i.text})}break}case"response.function_call_arguments.delta":{let a=s.output[r.output_index];if(!a)throw new k(`missing output at index ${r.output_index}`);a.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:a.arguments});break}default:o(r.type,r);break}},td=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let r=x(this,Sr,"f");if(!r)throw new k("request ended without sending any events");O(this,Sr,void 0,"f");let n=sg(r,x(this,ma,"f"));return O(this,fa,n,"f"),n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,a)=>r.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=x(this,fa,"f");if(!e)throw new k("stream ended without producing a ChatCompletion");return e}};function sg(t,e){return Jc(t,e)}var no=class extends b{list(e,r={},n){return this._client.getAPIList(h`/responses/${e}/input_items`,z,{query:r,...n,__security:{bearerAuth:!0}})}};var oo=class extends b{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var st=class extends b{constructor(){super(...arguments),this.inputItems=new no(this._client),this.inputTokens=new oo(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"&&Re(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"&&Re(o),o))}delete(e,r){return this._client.delete(h`/responses/${e}`,{...r,headers:S([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Gi(n,e))}stream(e,r){return ha.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}})}};st.InputItems=no;st.InputTokens=oo;var so=class extends b{retrieve(e,r){return this._client.get(h`/skills/${e}/content`,{...r,headers:S([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ao=class extends b{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(h`/skills/${o}/versions/${e}/content`,{...n,headers:S([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var kr=class extends b{constructor(){super(...arguments),this.content=new ao(this._client)}create(e,r={},n){return this._client.post(h`/skills/${e}/versions`,zt({body:r,...n,__security:{bearerAuth:!0}},this._client))}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`,z,{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}})}};kr.Content=ao;var gt=class extends b{constructor(){super(...arguments),this.content=new so(this._client),this.versions=new kr(this._client)}create(e={},r){return this._client.post("/skills",zt({body:e,...r,__security:{bearerAuth:!0}},this._client))}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",z,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};gt.Content=so;gt.Versions=kr;var io=class extends b{create(e,r,n){return this._client.post(h`/uploads/${e}/parts`,xe({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Jt=class extends b{constructor(){super(...arguments),this.parts=new io(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}})}};Jt.Parts=io;var rd=async t=>{let e=await Promise.allSettled(t),r=e.filter(o=>o.status==="rejected");if(r.length){for(let o of r)console.error(o.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let o of e)o.status==="fulfilled"&&n.push(o.value);return n};var lo=class extends b{create(e,r,n){return this._client.post(h`/vector_stores/${e}/file_batches`,{body:r,...n,headers:S([{"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:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(h`/vector_stores/${o}/file_batches/${e}/files`,z,{query:s,...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=S([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:a}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await et(i);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,a=Math.min(s,r.length),i=this._client,u=r.values(),l=[...n];async function c(d){for(let g of d){let y=await i.files.create({file:g,purpose:"assistants"},o);l.push(y.id)}}let p=Array(a).fill(u).map(c);return await rd(p),await this.createAndPoll(e,{file_ids:l})}};var uo=class extends b{create(e,r,n){return this._client.post(h`/vector_stores/${e}/files`,{body:r,...n,headers:S([{"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:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(h`/vector_stores/${e}/files`,z,{query:r,...n,headers:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=S([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),a=s.data;switch(a.status){case"in_progress":let i=5e3;if(n?.pollIntervalMs)i=n.pollIntervalMs;else{let u=s.response.headers.get("openai-poll-after-ms");if(u){let l=parseInt(u);isNaN(l)||(i=l)}}await et(i);break;case"failed":case"completed":return a}}}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`,be,{...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var yt=class extends b{constructor(){super(...arguments),this.files=new uo(this._client),this.fileBatches=new lo(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(h`/vector_stores/${e}`,{...r,headers:S([{"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:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",z,{query:e,...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(h`/vector_stores/${e}`,{...r,headers:S([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(h`/vector_stores/${e}/search`,be,{body:r,method:"post",...n,headers:S([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};yt.Files=uo;yt.FileBatches=lo;var Cr=class extends b{create(e,r){return this._client.post("/videos",xe({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",W,{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",xe({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(h`/videos/${e}/content`,{query:r,...n,headers:S([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",xe({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",xe({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`,zt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var co,nd,ga,Er=class extends b{constructor(){super(...arguments),co.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");x(this,co,"m",nd).call(this,n);let s=S([r]).values,a=x(this,co,"m",ga).call(this,s,"webhook-signature"),i=x(this,co,"m",ga).call(this,s,"webhook-timestamp"),u=x(this,co,"m",ga).call(this,s,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Xe("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-l>o)throw new Xe("Webhook timestamp is too old");if(l>c+o)throw new Xe("Webhook timestamp is too new");let p=a.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),d=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),g=u?`${u}.${i}.${e}`:`${i}.${e}`,y=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let w of p)try{let _=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",y,_,new TextEncoder().encode(g)))return}catch{continue}throw new Xe("The given webhook signature does not match the expected signature")}};co=new WeakSet,nd=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")},ga=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var sd=Symbol.for("openai.node.providerDefinitions.v1"),ad=globalThis,id=ad[sd],ld=id??new WeakMap;id||Object.defineProperty(ad,sd,{value:ld});function ud(t){let e=ld.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Wi,Vi,is,cd,fg="workload-identity-auth",R=class{constructor(e={}){Wi.add(this),is.set(this,void 0),this.completions=new hr(this),this.chat=new Dt(this),this.embeddings=new yr(this),this.files=new wr(this),this.images=new Ir(this),this.audio=new nt(this),this.moderations=new Tr(this),this.models=new vr(this),this.fineTuning=new qe(this),this.graders=new Ht(this),this.vectorStores=new yt(this),this.webhooks=new Er(this),this.beta=new Ue(this),this.batches=new cr(this),this.uploads=new Jt(this),this.admin=new Ut(this),this.responses=new st(this),this.realtime=new ht(this),this.conversations=new Wt(this),this.evals=new Vt(this),this.containers=new Gt(this),this.skills=new gt(this),this.videos=new Cr(this);let r=e.provider;if(r){let w=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(_=>e[_]!=null);if(w.length)throw new k(`The \`provider\` option cannot be used with ${w.map(_=>`\`${_}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=r?null:De("OPENAI_BASE_URL"),apiKey:o=r?null:De("OPENAI_API_KEY")??null,adminAPIKey:s=r?null:De("OPENAI_ADMIN_KEY")??null,organization:a=r?null:De("OPENAI_ORG_ID")??null,project:i=r?null:De("OPENAI_PROJECT_ID")??null,webhookSecret:u=De("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...c}=e,p=r?ud(r):void 0,d={apiKey:o,adminAPIKey:s,organization:a,project:i,webhookSecret:u,workloadIdentity:l,provider:r,...c,baseURL:p?.baseURL??(n||"https://api.openai.com/v1")};if(o&&l)throw new k("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!p&&!o&&!s&&!l)throw new k("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&oc())throw new k(`It looks like you're running in a browser-like environment.
78
+
79
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
80
+ If you understand the risks and have appropriate mitigations in place,
81
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
82
+
83
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
84
+
85
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
86
+ `);this.baseURL=d.baseURL,this.timeout=d.timeout??Vi.DEFAULT_TIMEOUT,this.logger=d.logger??console;let g="warn";this.logLevel=g,this.logLevel=Ii(d.logLevel,"ClientOptions.logLevel",this)??Ii(De("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??g,this.fetchOptions=d.fetchOptions,this.maxRetries=d.maxRetries??2,this.fetch=d.fetch??Bs(),O(this,is,ic,"f");let y=r?void 0:De("OPENAI_CUSTOM_HEADERS");if(y){let w={};for(let _ of y.split(`
87
+ `)){let f=_.indexOf(":");f>=0&&(w[_.substring(0,f).trim()]=_.substring(f+1).trim())}d.defaultHeaders=S([w,d.defaultHeaders])}this._options=d,this._provider=p,l&&(this._workloadIdentityAuth=new Zs(l,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=s,this.organization=a,this.project=i,this.webhookSecret=u}withOptions(e){let r=this._options.provider,n=e.provider??r,o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,n!==r&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return S([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return S([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return S([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return S([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return gc(e)}getUserAgent(){return`${this.constructor.name}/JS ${Nt}`}defaultIdempotencyKey(){return`stainless-node-retry-${ci()}`}makeStatusError(e,r,n,o){return re.generate(e,r,n,o)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof k?n:new k(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!x(this,Wi,"m",cd).call(this)&&n||this.baseURL,s=Qu(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),i=Object.fromEntries(s.searchParams);return(!pi(a)||!pi(i))&&(r={...i,...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new nr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:a,url:i,timeout:u}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(a,{url:i,options:o}),await this._provider?.prepareRequest?.(a,{url:i,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(se(this).debug(`[${l}] sending request`,ct({retryOfRequestLogID:n,method:o.method,url:i,options:o,headers:a.headers})),o.signal?.aborted)throw new ne;let d=o.__security??{bearerAuth:!0},g=new AbortController,y=await this.fetchWithAuth(i,a,u,g,d).catch(Do),w=Date.now();if(y instanceof globalThis.Error){let A=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new ne;let T=Lo(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(r)return se(this).info(`[${l}] connection ${T?"timed out":"failed"} - ${A}`),se(this).debug(`[${l}] connection ${T?"timed out":"failed"} (${A})`,ct({retryOfRequestLogID:n,url:i,durationMs:w-p,message:y.message})),this.retryRequest(o,r,n??l);throw se(this).info(`[${l}] connection ${T?"timed out":"failed"} - error; no more retries left`),se(this).debug(`[${l}] connection ${T?"timed out":"failed"} (error; no more retries left)`,ct({retryOfRequestLogID:n,url:i,durationMs:w-p,message:y.message})),y instanceof tr||y instanceof Fo?y:T?new Ye:new $t({message:hg(y),cause:y})}let _=[...y.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,T])=>", "+A+": "+JSON.stringify(T)).join(""),f=`[${l}${c}${_}] ${a.method} ${i} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${w-p}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&d.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await hi(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let A=await this.shouldRetry(y);if(r&&A){let Q=`retrying, ${r} attempts remaining`;return await hi(y.body),se(this).info(`${f} - ${Q}`),se(this).debug(`[${l}] response error (${Q})`,ct({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:w-p})),this.retryRequest(o,r,n??l,y.headers)}let T=A?"error; no more retries left":"error; not retryable";se(this).info(`${f} - ${T}`);let E=await y.text().catch(Q=>Do(Q).message),G=ec(E),q=G?void 0:E;throw se(this).debug(`[${l}] response error (${T})`,ct({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:q,durationMs:Date.now()-p})),this.makeStatusError(y.status,G,q,y.headers)}return se(this).info(f),se(this).debug(`[${l}] response start`,ct({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:w-p})),{response:y,options:o,controller:g,requestLogID:l,retryOfRequestLogID:n,startTime:p}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Go(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let i=r.headers,u=i.get("Authorization");if(!u||u===`Bearer ${fg}`){let l=await this._workloadIdentityAuth.getToken();i.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:a,...i}=r||{},u=this._makeAbort(o);s&&s.addEventListener("abort",u,{once:!0});let l=setTimeout(u,n),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,p={signal:o.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,a=o?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(s=u)}let i=o?.get("retry-after");if(i&&!s){let u=parseFloat(i);Number.isNaN(u)?s=Date.parse(i)-Date.now():s=u*1e3}if(s===void 0){let u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,u)}return await et(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,a=Math.min(.5*Math.pow(2,s),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:i}=n,u=this.buildURL(s,a,i);"timeout"in n&&Xu("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:c,isStreamingBody:p}=this.buildBody({options:n});p&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let d=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=S([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...sc(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:n}=e;if(!r)return r===void 0&&"body"in e?{...x(this,is,"f").call(this,{body:r,headers:S([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=S([n]),s=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,a=!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:!a}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:Ks(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}:{...x(this,is,"f").call(this,{body:r,headers:o}),isStreamingBody:!1}}};Vi=R,is=new WeakMap,Wi=new WeakSet,cd=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=Vi;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=k;R.APIError=re;R.APIConnectionError=$t;R.APIConnectionTimeoutError=Ye;R.APIUserAbortError=ne;R.NotFoundError=Xr;R.ConflictError=en;R.RateLimitError=rn;R.BadRequestError=Zr;R.AuthenticationError=Qr;R.InternalServerError=nn;R.PermissionDeniedError=Yr;R.UnprocessableEntityError=tn;R.InvalidWebhookSignatureError=Xe;R.toFile=Vo;R.Completions=hr;R.Chat=Dt;R.Embeddings=yr;R.Files=wr;R.Images=Ir;R.Audio=nt;R.Moderations=Tr;R.Models=vr;R.FineTuning=qe;R.Graders=Ht;R.VectorStores=yt;R.Webhooks=Er;R.Beta=Ue;R.Batches=cr;R.Uploads=Jt;R.Admin=Ut;R.Responses=st;R.Realtime=ht;R.Conversations=Wt;R.Evals=Vt;R.Containers=Gt;R.Skills=gt;R.Videos=Cr;function hg(t){if(gg(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 gg(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}function yg(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 Be(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Ye.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===ne.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):yg(t)?e=jl.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=jo(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=jo(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=jo(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=jo(t,"MODEL_NOT_FOUND"):e=t,e}var Ke=t=>t();function _t(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function _g(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 ya(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var wg="LC_AUTOGENERATED";function Pr(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'."),wg)}function wt(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(!As.isInstance(t))throw new Error("Invalid generic chat message");return _g(t);default:throw new Error(`Unknown message type: ${e}`)}}function dd(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function Zt(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:i}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&i&&e)return`${i}/openai/deployments/${e}`;if(n||a){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 Ji(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function pd(t){let e=Ke(()=>{if(Ji(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ji(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 md(){let t=zl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Qt(t,e=!1,r="1.0.0"){let n=pd(t),o=md(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function fd(t,e){let r;return Wr(t)?r=ei(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function bg(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function hd(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(gd(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
88
+ `)}function gd(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}: ${_a(o,e)},`):r.push(`${n}?: ${_a(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
89
+ `)}function _a(t,e){if(bg(t))return t.anyOf.map(r=>_a(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["{",gd(t,e+2),"}"].join(`
90
+ `);case"array":return t.items?`${_a(t.items,e)}[]`:"any[]";default:return""}}function wa(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 po(t){return"type"in t&&t.type!=="function"}function yd(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 _d(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Or(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 ba(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function wd(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 bd(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 xd(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Ad(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 Id(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 vd(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var Sd=Symbol("Let zodToJsonSchema decide on which parser to use"),Td={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"},kd=t=>typeof t=="string"?{...Td,basePath:["#"],definitions:{},name:t}:{...Td,basePath:["#"],definitions:{},...t};var ls=t=>"_def"in t?t._def:t;function Cd(t){if(!t)return!0;for(let e in t)return!1;return!0}var Ed=t=>{let e=kd(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[ls(o),{def:ls(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Zi(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function V(t,e,r,n,o){t[e]=r,Zi(t,e,n,o)}function Pd(){return{}}function Od(t,e){let r={type:"array"};return t.type?._def?.typeName!==D.ZodAny&&(r.items=N(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&V(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&V(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(V(r,"minItems",t.exactLength.value,t.exactLength.message,e),V(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Md(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?V(r,"minimum",n.value,n.message,e):V(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),V(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(r,"maximum",n.value,n.message,e):V(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),V(r,"maximum",n.value,n.message,e));break;case"multipleOf":V(r,"multipleOf",n.value,n.message,e);break}return r}function Rd(){return{type:"boolean"}}function $d(t,e,r){return N(t.type._def,e,r)}var Nd=(t,e,r)=>N(t.innerType._def,e,r);function Qi(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Qi(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 xg(t,e)}}var xg=(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":V(r,"minimum",n.value,n.message,e);break;case"max":V(r,"maximum",n.value,n.message,e);break}return r};function zd(t,e,r){return{...N(t.innerType._def,e,r),default:t.defaultValue()}}function jd(t,e,r){return e.effectStrategy==="input"?N(t.schema._def,e,r):{}}function Ld(t){return{type:"string",enum:[...t.values]}}var Ag=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Dd(t,e){let r=[N(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),N(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(Ag(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:i,...u}=s;a=u}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function Fd(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Yi,Mr={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:()=>(Yi===void 0&&(Yi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Yi),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 xa(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Ig(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":V(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":V(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":Ge(r,"email",o.message,e);break;case"format:idn-email":Ge(r,"idn-email",o.message,e);break;case"pattern:zod":We(r,Mr.email,o.message,e);break}break;case"url":Ge(r,"uri",o.message,e);break;case"uuid":Ge(r,"uuid",o.message,e);break;case"regex":We(r,o.regex,o.message,e);break;case"cuid":We(r,Mr.cuid,o.message,e);break;case"cuid2":We(r,Mr.cuid2,o.message,e);break;case"startsWith":We(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":We(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Ge(r,"date-time",o.message,e);break;case"date":Ge(r,"date",o.message,e);break;case"time":Ge(r,"time",o.message,e);break;case"duration":Ge(r,"duration",o.message,e);break;case"length":V(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),V(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{We(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ge(r,"ipv4",o.message,e),o.version!=="v4"&&Ge(r,"ipv6",o.message,e);break}case"emoji":We(r,Mr.emoji,o.message,e);break;case"ulid":{We(r,Mr.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ge(r,"binary",o.message,e);break}case"contentEncoding:base64":{V(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{We(r,Mr.base64,o.message,e);break}}break}case"nanoid":We(r,Mr.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Ig=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ge=(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}}})):V(t,"format",e,r,n)},We=(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:Ud(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):V(t,"pattern",Ud(e,n),r,n)},Ud=(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="",a=!1,i=!1,u=!1;for(let l=0;l<o.length;l++){if(a){s+=o[l],a=!1;continue}if(n.i){if(i){if(o[l].match(/[a-z]/)){u?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],u=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
91
+ ]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
92
+ ]))`;continue}}if(n.s&&o[l]==="."){s+=i?`${o[l]}\r
93
+ `:`[${o[l]}\r
94
+ ]`;continue}s+=o[l],o[l]==="\\"?a=!0:i&&o[l]==="]"?i=!1:!i&&o[l]==="["&&(i=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Aa(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(xa(t.keyType._def,e)).reduce((o,[s,a])=>s==="type"?o:{...o,[s]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function qd(t,e){if(e.mapStrategy==="record")return Aa(t,e);let r=N(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=N(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 Bd(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Kd(){return{not:{}}}function Gd(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var us={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Vd(t,e){if(e.target==="openApi3")return Wd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in us&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let a=us[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Wd(t,e)}var Wd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>N(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 Hd(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:us[t.innerType._def.typeName],nullable:!0}:{type:[us[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=N(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Jd(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",Zi(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?V(r,"minimum",n.value,n.message,e):V(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),V(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?V(r,"maximum",n.value,n.message,e):V(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),V(r,"maximum",n.value,n.message,e));break;case"multipleOf":V(r,"multipleOf",n.value,n.message,e);break}return r}function vg(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Zd(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let a=[...e.currentPath,"properties",o],i=N(s._def,{...e,currentPath:a,propertyPath:a});if(i===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:i},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:vg(t,e)};return r.required.length||delete r.required,r}var Qd=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return N(t.innerType._def,{...e,currentPath:e.currentPath},r);let n=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return n?{anyOf:[{not:{}},n]}:{}};var Yd=(t,e,r)=>{if(e.pipeStrategy==="input")return N(t.in._def,e,r);if(e.pipeStrategy==="output")return N(t.out._def,e,r);let n=N(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=N(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(s=>s!==void 0)}};function Xd(t,e,r){return N(t.type._def,e,r)}function ep(t,e){let n={type:"array",uniqueItems:!0,items:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&V(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&V(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function tp(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:N(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function rp(){return{not:{}}}function np(){return{}}var op=(t,e,r)=>N(t.innerType._def,e,r);function N(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==Sd)return s}if(n&&!r){let s=Tg(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=Cg(t,t.typeName,e,r);return s&&Eg(t,e,s),o.jsonSchema=s,s}finally{r&&n&&e.seen.set(t,n)}}var Tg=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((n,o)=>o===0?n:Sg(n)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:kg(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},sp="_x_",Sg=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(sp))return t;let e=sp;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},kg=(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("/")},Cg=(t,e,r,n)=>{switch(e){case D.ZodString:return xa(t,r);case D.ZodNumber:return Jd(t,r);case D.ZodObject:return Zd(t,r);case D.ZodBigInt:return Md(t,r);case D.ZodBoolean:return Rd();case D.ZodDate:return Qi(t,r);case D.ZodUndefined:return rp();case D.ZodNull:return Gd(r);case D.ZodArray:return Od(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return Vd(t,r);case D.ZodIntersection:return Dd(t,r);case D.ZodTuple:return tp(t,r);case D.ZodRecord:return Aa(t,r);case D.ZodLiteral:return Fd(t,r);case D.ZodEnum:return Ld(t);case D.ZodNativeEnum:return Bd(t);case D.ZodNullable:return Hd(t,r,n);case D.ZodOptional:return Qd(t,r,n);case D.ZodMap:return qd(t,r);case D.ZodSet:return ep(t,r);case D.ZodLazy:return N(t.getter()._def,r,n);case D.ZodPromise:return Xd(t,r,n);case D.ZodNaN:case D.ZodNever:return Kd();case D.ZodEffects:return jd(t,r,n);case D.ZodAny:return Pd();case D.ZodUnknown:return np();case D.ZodDefault:return zd(t,r,n);case D.ZodBranded:return $d(t,r,n);case D.ZodReadonly:return op(t,r,n);case D.ZodCatch:return Nd(t,r,n);case D.ZodPipeline:return Yd(t,r,n);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(o=>{})(e)}},Eg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Xi=(t,e)=>{let r=Ed(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=N(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let a=(()=>{if(Cd(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let p=Object.entries(r.definitions).filter(([d])=>!l.has(d));if(p.length===0)break;for(let[d,g]of p)u[d]=N(ls(g),{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??{},l.add(d)}return u})(),i=n===void 0?a?{...o,[r.definitionPath]:a}:o:r.nameStrategy==="duplicate-ref"?{...o,...a||r.seenRefs.size?{[r.definitionPath]:{...a,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]:o}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};function ap(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return bt(e,[],e)}function el(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(el(e))return!0;for(let e of t.anyOf??[])if(el(e))return!0;return!1}function bt(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Rr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(Rr(n))for(let[d,g]of Object.entries(n))bt(g,[...e,"$defs",d],r);let o=t.definitions;if(Rr(o))for(let[d,g]of Object.entries(o))bt(g,[...e,"definitions",d],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let a=t.required??[],i=t.properties;if(Rr(i)){for(let[d,g]of Object.entries(i))if(!el(g)&&!a.includes(d))throw new Error(`Zod field at \`${[...e,"properties",d].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(i),t.properties=Object.fromEntries(Object.entries(i).map(([d,g])=>[d,bt(g,[...e,"properties",d],r)]))}let u=t.items;Rr(u)&&(t.items=bt(u,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((d,g)=>bt(d,[...e,"anyOf",String(g)],r)));let c=t.allOf;if(Array.isArray(c))if(c.length===1){let d=bt(c[0],[...e,"allOf","0"],r);Object.assign(t,d),delete t.allOf}else t.allOf=c.map((d,g)=>bt(d,[...e,"allOf",String(g)],r));t.default===null&&delete t.default;let p=t.$ref;if(p&&Og(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);let d=Pg(r,p);if(typeof d=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!Rr(d))throw new Error(`Expected \`$ref: ${p}\` to resolve to an object but got ${JSON.stringify(d)}`);return Object.assign(t,{...d,...t}),delete t.$ref,bt(t,e,r)}return t}function Pg(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),n=t;for(let o of r){if(!Rr(n))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(n)}`);let s=n[o];if(s===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);n=s}return n}function Rr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Og(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function Mg(t,e){return Xi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Rg(t){return ap(Vl(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let n=e._zod.def;if(n.type==="union"&&"discriminator"in n&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function $g(t){return"_zod"in t}function ip(t,e,r){return Ec({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:$g(t)?Rg(t):Mg(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var lp=["jsonSchema","functionCalling","jsonMode"];function up(t,e){if(typeof e<"u"&&!lp.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${lp.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 Ng(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function cp(t,e,r){if(Hl(t))return ip(t,e,r);if(Ur(t))return Ng({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:He(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Gl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function dp(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 pp={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function mo(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var $r=class extends Eo{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??it("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??it("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!_t(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&&ut(t.json_schema.schema)?cp(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=Zt({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Qt(r.defaultHeaders),this.client=new R(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Or(t)?vd(t.metadata.customTool):ks(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:fd(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(po(n)||Or(n))return n;if(yd(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return Wr(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[a,i]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(wt(s))]),u=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=a+r+i+u,c=s;if(c._getType()==="function"&&(l-=2),c.additional_kwargs?.function_call&&(l+=3),c?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(c.additional_kwargs.function_call)),l+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=hd(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 Be(o)}})}get profile(){return pp[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:a}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let i=up(this.model,e?.method);if(i==="jsonMode"){n=Xa(o);let u=He(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...u}}})}else if(i==="jsonSchema"){let u=He(o),l={name:s??"extract",description:Ts(u),schema:ut(o)?o:u,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...u}}}),ut(o)||Tt(o)){let c=Xa(o);n=Je.from(async p=>"parsed"in p.additional_kwargs?p.additional_kwargs.parsed:c.invoke(p.content))}else n=new Xl}else{let u=s??"extract",l=He(o),c;ut(o)||Tt(o)?c={name:u,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(c=o,u=o.name):(u=o.title??u,c={name:u,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:c}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=eu(o,u)}return tu(r,n,a)}};var Ia={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=Wa({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=Ga(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=Ga(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=Wa({dataUrl:t.url}),r=Pr(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=Pr(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`)}},tl=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],a=[];for(let l of n??[])try{s.push(Cs(l,{returnId:!0}))}catch(c){a.push(Kr(l,c.message))}let i={function_call:t.function_call,tool_calls:n};r!==void 0&&(i.__raw_response=e),o!==void 0&&(i.reasoning_content=o);let u={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(i.audio=t.audio),new $({content:dp(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:u,id:e.id})}default:return new As(t.content||"",t.role??"unknown")}},rl=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},r&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});let i={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ja({content:s,response_metadata:i});if(o==="assistant"){let u=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)u.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new lt({content:s,tool_call_chunks:u,additional_kwargs:a,id:e.id,response_metadata:i})}else return o==="system"?new Is({content:s,response_metadata:i}):o==="developer"?new Is({content:s,response_metadata:i,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Fl({content:s,additional_kwargs:a,name:t.name,response_metadata:i}):o==="tool"?new Ha({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:i}):new Dl({content:s,role:o,response_metadata:i})},mp=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=Ul(()=>{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=Pr(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}}}},fp=({message:t,model:e})=>{let r=wt(t);if(r==="system"&&_t(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 $.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(Ya):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&F.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let a=mp(s);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},fo=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return fp({message:r});let n=wt(r);n==="system"&&_t(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(a=>bs(a)?xs(a,Ia):typeof a=="object"&&a!==null&&"type"in a&&a.type==="tool_use"?[]:a),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),$.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Ya):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),F.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 va=class extends $r{constructor(t,e){super(mo(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(a=>this._convertChatOpenAIToolToCompletionsTool(a,{strict:r})):void 0,tool_choice:wa(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),_t(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=fo({messages:t,model:this.model});if(o.stream){let a=this._streamResponseChunks(t,e,r),i={};for await(let g of a){g.message.response_metadata={...g.generationInfo,...g.message.response_metadata};let y=g.generationInfo?.completion??0;i[y]===void 0?i[y]=g:i[y]=i[y].concat(g)}let u=Object.entries(i).sort(([g],[y])=>parseInt(g,10)-parseInt(y,10)).map(([g,y])=>y),{functions:l,function_call:c}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,l,c),d=await this._getNumTokensFromGenerations(u);return n.input_tokens=p,n.output_tokens=d,n.total_tokens=p+d,{generations:u,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let a=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:i,prompt_tokens:u,total_tokens:l,prompt_tokens_details:c,completion_tokens_details:p}=a?.usage??{};i&&(n.output_tokens=(n.output_tokens??0)+i),u&&(n.input_tokens=(n.input_tokens??0)+u),l&&(n.total_tokens=(n.total_tokens??0)+l),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(n.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(n.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});let d=[];for(let g of a?.choices??[]){let y={text:g.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(g.message??{role:"assistant"},a)};y.generationInfo={...g.finish_reason?{finish_reason:g.finish_reason}:{},...g.logprobs?{logprobs:g.logprobs}:{}},vt(y.message)&&(y.message.usage_metadata=n),y.message=new $(Object.fromEntries(Object.entries(y.message).filter(([w])=>!w.startsWith("lc_")))),d.push(y)}return{generations:d,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=fo({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),a=this.streamUsage??e.streamUsage;yield*Es(async function*(u,l){for await(let c of u){if(l?.aborted)return;yield c}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=fo({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,a=await this.completionWithRetry(o,e),i;for await(let u of a){if(e.signal?.aborted)return;let l=u?.choices?.[0];if(u.usage&&(i=u.usage),!l)continue;let{delta:c}=l;if(!c)continue;let p=this._convertCompletionsDeltaToBaseMessageChunk(c,u,s);s=c.role??s;let d={prompt:e.promptIndex??0,completion:l.index??0};if(typeof p.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let g={...d};l.finish_reason!=null&&(g.finish_reason=l.finish_reason,g.system_fingerprint=u.system_fingerprint,g.model_name=u.model,g.service_tier=u.service_tier),this.logprobs&&(g.logprobs=l.logprobs);let y=new Co({message:p,text:p.content,generationInfo:g});yield y,await r?.handleLLMNewToken(y.text??"",d,void 0,void 0,void 0,{chunk:y})}if(i){let u={...i.prompt_tokens_details?.audio_tokens!==null&&{audio:i.prompt_tokens_details?.audio_tokens},...i.prompt_tokens_details?.cached_tokens!==null&&{cache_read:i.prompt_tokens_details?.cached_tokens}},l={...i.completion_tokens_details?.audio_tokens!==null&&{audio:i.completion_tokens_details?.audio_tokens},...i.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:i.completion_tokens_details?.reasoning_tokens}},c=new Co({message:new lt({content:"",response_metadata:{usage:{...i}},usage_metadata:{input_tokens:i.prompt_tokens,output_tokens:i.completion_tokens,total_tokens:i.total_tokens,...Object.keys(u).length>0&&{input_token_details:u},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield c,await r?.handleLLMNewToken(c.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:c})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw Be(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return rl({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return tl({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Ta="__openai_function_call_ids__",Sa="__openai_custom_tool_call_ids__";function xp(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 jg(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 cs=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},ka=t=>{if(t.error){let i=new Error(t.error.message);throw i.name=t.error.code,i}let e=[],r=[],n=[],o=t.output.map(i=>{if(i.type==="function_call"&&"parsed_arguments"in i){let u={...i};return delete u.parsed_arguments,u}return i}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(let i of t.output)if(i.type==="message")e.push(...i.content.flatMap(u=>u.type==="output_text"?("parsed"in u&&u.parsed!=null&&(a.parsed=u.parsed),{type:"text",text:u.text,annotations:u.annotations.map(xp),...i.phase!==null?{phase:i.phase}:{}}):u.type==="refusal"?(a.refusal=u.refusal,[]):u));else if(i.type==="function_call"){let u={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{r.push(Cs(u,{returnId:!0}))}catch(l){let c;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(c=l.message),n.push(Kr(u,c))}a[Ta]??={},i.id&&(a[Ta][i.call_id]=i.id)}else if(i.type==="reasoning"){a.reasoning=i;let u=i.summary?.map(l=>l.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(i.type==="custom_tool_call"){let u=wd(i);u?(r.push(u),a[Sa]??={},i.id&&i.call_id&&(a[Sa][i.call_id]=i.id)):n.push(Kr(i,"Malformed custom tool call"))}else if(i.type==="computer_call"){let u=bd(i);u?r.push(u):n.push(Kr(i,"Malformed computer call"))}else i.type==="image_generation_call"?(i.result&&e.push({type:"image",mimeType:"image/png",data:i.result,id:i.id,metadata:{status:i.status}}),a.tool_outputs??=[],a.tool_outputs.push(i)):(a.tool_outputs??=[],a.tool_outputs.push(i));return new $({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:cs(t.usage),additional_kwargs:a,response_metadata:s})},Ap=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}},nl=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},a={},i;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[xp(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let u="phase"in t.item?t.item.phase:void 0;u&&e.push({type:"text",text:"",phase:u,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Ta]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Sa]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")i=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){i=t.response.id;let u=ka(t.response);if(n=cs(t.response.usage),t.response.text?.format?.type==="json_schema"&&u.text)try{a.parsed??=JSON.parse(u.text)}catch{}for(let[l,c]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=u.response_metadata.output:s[l]=c)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,u,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:u,status:l}}}else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let u=t.item.summary?t.item.summary.map((c,p)=>({...c,index:p})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...u?{summary:u}:{}};let l=t.item.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new Co({text:e.map(u=>u.text).join(""),message:new lt({id:i,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:a,response_metadata:s}),generationInfo:r})},Ip=t=>{let e=$.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ke(()=>{try{let f=wt(t);return f==="system"||f==="developer"||f==="assistant"||f==="user"?f:"assistant"}catch{return"assistant"}}),o,s=new Set,a=new Set,i=new Map,u=new Map;function*l(){if(!o)return;let f=o.content;(typeof f=="string"&&f.length>0||Array.isArray(f)&&f.length>0)&&(yield o),o=void 0}let c=(f,A)=>{o||(o={type:"message",role:n,content:[],...A?{phase:A}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...f]:[...f]:o.content.push(...f)},p=f=>{if(typeof f=="string")return f;try{return JSON.stringify(f??{})}catch{return"{}"}},d=f=>{let A=Ke(()=>{let T=f.metadata?.detail;return T==="low"||T==="high"||T==="auto"?T:"auto"});if(f.fileId)return{type:"input_image",detail:A,file_id:f.fileId};if(f.url)return{type:"input_image",detail:A,image_url:f.url};if(f.data){let T=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${f.mimeType??"image/png"};base64,${T}`}}},g=f=>{if(f.fileId){let A=ya(f);return{type:"input_file",file_id:f.fileId,...A?{filename:A}:{}}}if(f.url){let A=ya(f);return{...A?{filename:A}:{},type:"input_file",file_url:f.url}}if(f.data){let A=Pr(f),T=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64");return{type:"input_file",file_data:`data:${f.mimeType??"application/octet-stream"};base64,${T}`,filename:A}}},y=f=>{let A=Ke(()=>{if(Array.isArray(f.summary)){let E=f.summary?.map(G=>G?.text).filter(G=>typeof G=="string")??[];if(E.length>0)return E}return f.reasoning?[f.reasoning]:[]}),T=A.length>0?A.map(E=>({type:"summary_text",text:E})):[{type:"summary_text",text:""}];return{type:"reasoning",...f.id?{id:f.id}:{},summary:T}},w=f=>({type:"function_call",name:f.name??"",call_id:f.id??"",arguments:p(f.args)}),_=f=>{let A=p(f.output),T=f.status==="success"?"completed":f.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:f.toolCallId??"",output:A,...T?{status:T}:{}}};for(let f of t.contentBlocks)if(f.type==="text"){let A=Ke(()=>{if("extras"in f&&typeof f.extras=="object"&&f.extras!==null&&"phase"in f.extras)return f.extras.phase});c([{type:"input_text",text:f.text}],A)}else if(f.type!=="invalid_tool_call"){if(f.type==="reasoning")yield*l(),yield y(f);else if(f.type==="tool_call"){yield*l();let A=f.id??"";A&&(s.add(A),i.delete(A)),yield w(f)}else if(f.type==="tool_call_chunk"){if(f.id){let A=i.get(f.id)??{name:f.name,args:[]};f.name&&(A.name=f.name),f.args&&A.args.push(f.args),i.set(f.id,A)}}else if(f.type==="server_tool_call"){yield*l();let A=f.id??"";A&&(a.add(A),u.delete(A)),yield w(f)}else if(f.type==="server_tool_call_chunk"){if(f.id){let A=u.get(f.id)??{name:f.name,args:[]};f.name&&(A.name=f.name),f.args&&A.args.push(f.args),u.set(f.id,A)}}else if(f.type==="server_tool_call_result")yield*l(),yield _(f);else if(f.type!=="audio")if(f.type==="file"){let A=g(f);A&&c([A])}else if(f.type==="image"){let A=d(f);A&&c([A])}else if(f.type==="video"){let A=g(f);A&&c([A])}else f.type==="text-plain"?f.text&&c([{type:"input_text",text:f.text}]):f.type==="non_standard"&&e&&(yield*l(),yield f.value)}yield*l();for(let[f,A]of i){if(!f||s.has(f))continue;let T=A.args.join("");!A.name&&!T||(yield{type:"function_call",call_id:f,name:A.name??"",arguments:T})}for(let[f,A]of u){if(!f||a.has(f))continue;let T=A.args.join("");!A.name&&!T||(yield{type:"function_call",call_id:f,name:A.name??"",arguments:T})}}return Array.from(r())},ds=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return Ip(n);let s=n.additional_kwargs,a=wt(n);if(a==="system"&&_t(r)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){let i=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"input_image",image_url:i.content};if(Array.isArray(i.content)){let l=i.content.find(d=>d.type==="input_image");if(l)return l;let c=i.content.find(d=>d.type==="computer_screenshot");if(c)return c;let p=i.content.find(d=>d.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id};if(i.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:i.tool_call_id,output:i.content};let u=Array.isArray(i.content)&&i.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:i.tool_call_id,id:i.id?.startsWith("fc_")?i.id:void 0,output:u?i.content:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(a==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(w=>"type"in w))return o?.output;let i=[],u=s?.reasoning,l=!!u?.encrypted_content;if(u&&(!e||l)){let w=Ap(u);i.push(w)}let{content:c}=n;if(s?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:s.refusal}]),typeof c=="string"||c.length>0){let w={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ke(()=>typeof c=="string"?c:c.flatMap(_=>{if(_.type==="text"){let f=_;return{type:"output_text",text:f.text,annotations:(f.annotations??[]).map(jg)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:Ke(()=>{if(Array.isArray(c))return c.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};i.push(w)}let p=s?.[Ta],d=s?.[Sa];$.isInstance(n)&&n.tool_calls?.length?i.push(...n.tool_calls.map(w=>Ad(w,d)?{type:"custom_tool_call",id:"call_id"in w&&typeof w.call_id=="string"?w.call_id:d?.[w.id??""]??"",call_id:w.id??"",input:w.args.input,name:w.name}:xd(w)?{type:"computer_call",id:w.call_id,call_id:w.id??"",action:w.args.action}:{type:"function_call",name:w.name,arguments:JSON.stringify(w.args),call_id:w.id,...e?{}:{id:p?.[w.id]}})):s?.tool_calls&&i.push(...s.tool_calls.map(w=>({type:"function_call",name:w.function.name,call_id:w.id,arguments:w.function.arguments,...e?{}:{id:p?.[w.id]}})));let g=o?.output?.length?o?.output:s.tool_outputs,y=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(g!=null){let w=g?.filter(_=>y.includes(_.type));w.length>0&&i.push(...w)}return i}if(a==="user"||a==="system"||a==="developer"){if(typeof n.content=="string")return{type:"message",role:a,content:n.content};let i=[],u=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&i.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),bs(l)){if(l.type==="file"){let c=ya(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...c?{filename:c}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...c?{filename:c}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:Pr(l)}}return xs(l,Ia)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ke(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),detail:Ke(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return u.length>0&&i.push({type:"message",role:a,content:u}),i}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*ol(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,a=0,i=!1,u,l,c,p,d=new Set,g=(_,f)=>{let A=s.get(_);if(A!==void 0)return{index:A,isNew:!1};let T=a++;return s.set(_,T),o.set(T,{...f}),{index:T,isNew:!0}},y=function*(){i||(i=!0,yield{event:"message-start",id:u})},w=function*(_){if(d.has(_))return;let f=o.get(_);f&&(d.add(_),yield{event:"content-block-finish",index:_,content:nu(f)})};for await(let _ of t){if(_.type==="response.created"){u=_.response.id,yield*y(),yield{event:"provider",provider:n,name:"response.created",payload:{model:_.response.model,id:_.response.id}};continue}if(_.type==="response.output_text.delta"){yield*y();let{index:f,isNew:A}=g(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});A&&(yield{event:"content-block-start",index:f,content:{type:"text",text:""}});let T=o.get(f);T.text=(T.text??"")+_.delta,yield{event:"content-block-delta",index:f,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*y();let{index:f,isNew:A}=g(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});A&&(yield{event:"content-block-start",index:f,content:{type:"reasoning",reasoning:""}});let T=o.get(f);T.reasoning=(T.reasoning??"")+_.delta,yield{event:"content-block-delta",index:f,delta:{type:"reasoning-delta",reasoning:_.delta}};continue}if(_.type==="response.output_item.added"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*y();let f=`tool:${_.output_index}`,A=_.item.type==="custom_tool_call",T=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:E,isNew:G}=g(f,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:T,index:_.output_index,...A?{isCustomTool:!0}:{}});if(G&&(yield{event:"content-block-start",index:E,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:T,index:_.output_index}}),T){let q=o.get(E);yield{event:"content-block-delta",index:E,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...q.id!=null?{id:q.id}:{},...q.name!=null?{name:q.name}:{},args:q.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*y();let{index:f,isNew:A}=g(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});A&&(yield{event:"content-block-start",index:f,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let T=o.get(f);T.args=(T.args??"")+_.delta,yield{event:"content-block-delta",index:f,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...T.id!=null?{id:T.id}:{},...T.name!=null?{name:T.name}:{},args:T.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*y();let f=`tool:${_.output_index}`,A=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:T,isNew:E}=g(f,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index});if(E)yield{event:"content-block-start",index:T,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index}};else{let G=o.get(T);G.args=A,G.id=_.item.call_id,G.name=_.item.name}yield*w(T);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*y(),u=_.response.id,c=Lg(_.response.status,_.type),p={model_provider:n,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(l=cs(_.response.usage),yield{event:"usage",usage:l});continue}_.type!=="response.image_generation_call.partial_image"&&(yield*y(),yield{event:"provider",provider:n,name:_.type,payload:_})}i||(yield{event:"message-start"});for(let[_]of o)d.has(_)||(yield*w(_));yield{event:"message-finish",reason:c,...l?{usage:l}:{},...p?{responseMetadata:p}:{}}}function Lg(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Ca=class extends $r{constructor(t,e){super(mo(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:_d(t?.tool_choice)?t?.tool_choice:(()=>{let o=wa(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let a of o)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},s=s?.concat(a)??a;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:ds({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:ka(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:ds({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*ol(async function*(a,i){for await(let u of a){if(i?.aborted)return;yield u}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:ds({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=nl(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 Be(o)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(n){throw Be(n)}})}_reduceChatOpenAITools(t,e){let r=[];for(let n of t)if(po(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(Or(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(ks(n)){let o={};for(let[s,a]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=a);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else ba(n)&&r.push(Id(n));return r}};var Ea=class vp extends $r{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=mo(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Ca(n),this.completions=n?.completions??new va(n)}_useResponsesApi(e){let r=e?.tools?.some(po),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(ba)||e?.tools?.some(Or);return this.useResponsesApi||r||n||o||dd(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 vp(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Bg=v.object({type:v.literal("screenshot")}),Kg=v.object({type:v.literal("click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Gg=v.object({type:v.literal("double_click"),x:v.number(),y:v.number(),button:v.enum(["left","right","wheel","back","forward"]).default("left")}),Wg=v.object({type:v.literal("drag"),path:v.array(v.object({x:v.number(),y:v.number()}))}),Vg=v.object({type:v.literal("keypress"),keys:v.array(v.string())}),Hg=v.object({type:v.literal("move"),x:v.number(),y:v.number()}),Jg=v.object({type:v.literal("scroll"),x:v.number(),y:v.number(),scroll_x:v.number(),scroll_y:v.number()}),Zg=v.object({type:v.literal("type"),text:v.string()}),Qg=v.object({type:v.literal("wait"),duration:v.number().optional()}),Yg=v.union([Bg,Kg,Gg,Wg,Vg,Hg,Jg,Zg,Qg]),MB=v.object({action:Yg});var Xg=v.object({type:v.literal("exec"),command:v.array(v.string()),env:v.record(v.string(),v.string()).optional(),working_directory:v.string().optional(),timeout_ms:v.number().optional(),user:v.string().optional()}),zB=v.union([Xg]);var FB=v.object({commands:v.array(v.string()).describe("Array of shell commands to execute"),timeout_ms:v.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:v.number().optional().describe("Optional maximum number of characters to return from each command")});var ey=v.object({type:v.literal("create_file"),path:v.string(),diff:v.string()}),ty=v.object({type:v.literal("update_file"),path:v.string(),diff:v.string()}),ry=v.object({type:v.literal("delete_file"),path:v.string()}),KB=v.union([ey,ty,ry]);var kp={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},ay={default:"text-embedding-ada-002"},sl=new Map,Pa=null,iy=()=>{let t=Sp.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},ly=async t=>{let e=iy();sl.size===0&&(Pa||(Pa=(async()=>{try{let n=await fetch(`${e}/models`);if(!n.ok)throw new Error("Failed to fetch AI service discovery data.");(await n.json()).models.forEach(o=>sl.set(o.name,o))}catch(n){throw Pa=null,n}})()),await Pa);let r=sl.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},uy=async(t="default")=>await ly(kp[t]);var go=(t,e)=>e,Cp=(t,e)=>({...t,...e}),Ep=(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(`
95
+
96
+ `);return o[o.length-1]?.trim()===r?t:`${t}
97
+
98
+ ${r}`},Pp=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Nr=()=>({agentExecutionContext:M({reducer:Cp,default:Pp}),outputMessage:M({reducer:Ep,default:()=>""}),summary:M({reducer:go,default:()=>""}),status:M({reducer:go})}),Oa=()=>({...Nr(),sharedStatePatch:M({reducer:go})}),cy=M.Root({agentExecutionContext:M({default:Pp,reducer:Cp}),currentIntent:M({default:()=>"none",reducer:go}),lastExecutedAgent:M({default:()=>"",reducer:go}),requiresFollowUp:M({default:()=>!0,reducer:go}),stepCount:M({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:M({default:()=>"",reducer:Ep})});var dy=t=>typeof t=="string"&&t.length>0?t:void 0,py=()=>El(),my=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,fy=t=>{let e=t?.configurable;return{conversationId:dy(e?.thread_id),abortSignal:t?.signal,requestId:py(),requestSource:my(sy.applicationName)}},hy=async({config:t})=>{let e=Sp.getDefault(),r=(await oy.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:a,requestId:i,requestSource:u}=fy(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",u)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),i.length>0&&l.set("X-Esri-Request-Id",i);let c=a&&o?.signal?AbortSignal.any([a,o.signal]):o?.signal??a;return await fetch(n,{...o,headers:l,signal:c})}},al=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=kp[e],s=await uy(e);return new Ea({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await hy({config:n})}})};var gy=v.object({id:v.string().min(1),name:v.string().min(1),description:v.string().min(1)});v.array(gy);var Op="0.1",ho=1536,Mp="openai",Rp=ay.default,$p=`Name: {name}
99
+ Title: {title}
100
+ Description: {description}`,Np=`Name: {name}
101
+ Alias: {alias}
102
+ Description: {description}`,zp=v.object({schemaVersion:v.literal(Op),modified:v.number().int().nonnegative(),embeddings:v.object({modelProvider:v.literal(Mp),model:v.literal(Rp),dimensions:v.literal(ho),templates:v.object({layer:v.string().default($p),field:v.string().default(Np)})}),layers:v.array(v.object({id:v.string().min(1),name:v.string().min(1),title:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(ho,{message:`Layer vector must be exactly ${ho} dimensions`}),fields:v.array(v.object({name:v.string().min(1),alias:v.string().catch(""),description:v.string().catch(""),vector:v.array(v.number()).length(ho,{message:`Field vector must be exactly ${ho} dimensions`})}))})).default([])});var yy=(t,e)=>{let r=ou.fromTemplate(t);return Gr.fromMessages([r,...e])};var ps=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:a,config:i}=t,u=yy(e,o??[]),l=(await al({modelTier:r,temperature:n,config:i})).withStructuredOutput(a);return await u.pipe(l).invoke(s??{},i)};var _y=m.object({name:m.string(),description:m.string(),valueType:m.string(),alias:m.string()}),mG=m.object({fields:m.array(_y)});var fG=m.object({title:m.string(),description:m.string(),name:m.string().nullable()});var Lp=t=>Array.isArray(t)&&t.every(ko),by=t=>typeof t=="object"&&t!=null&&"messages"in t&&Lp(t.messages),xy=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,xt=class extends au{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,a)=>this.run(s,a)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e,r){let n=this.tools.find(o=>o.name===t.name);try{if(n===void 0)throw new Error(`Tool "${t.name}" not found.`);let o={...t,type:"tool_call"},s={...e,state:r,toolCallId:t.id??"",config:e,context:e.context,store:e.store??null,writer:e.writer??e.configurable?.writer??null},a=await n.invoke(o,s);return ko(a)&&a.getType()==="tool"||ye(a)?a:new F({status:"success",name:n.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||So(o))throw o;return new F({status:"error",content:`Error: ${o.message}
103
+ Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(xy(t)){let{lg_tool_call:s,...a}=t;r=[await this.runTool(s,e,a)]}else{let s;if(Lp(t))s=t;else if(by(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let a=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),i;for(let u=s.length-1;u>=0;u-=1){let l=s[u];if(vt(l)){i=l;break}}if(i==null||!vt(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(u=>u.id==null||!a.has(u.id)).map(u=>this.runTool(u,e,t))??[])}if(!r.some(ye))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)ye(s)?s.graph===ae.PARENT&&Array.isArray(s.goto)&&s.goto.every(a=>$l(a))?o?o.goto.push(...s.goto):o=new ae({graph:ae.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var h2=M.Root({llmInputMessages:M({reducer:(t,e)=>Po([],e),default:()=>[]})});var ms=(t,e)=>e??t,n_=M.Root({...Oa(),intent:M({reducer:ms}),vectorSearchLayerResults:M({reducer:ms,default:()=>[]}),vectorSearchFieldResults:M({reducer:ms}),navigationInternalState:M({reducer:ms,default:()=>({toolCallMessage:void 0})})});async function o_(t,e){let r=zr.getDefault().helperServices,n=r.geocode.find(c=>c.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${il.assetsPath?.endsWith("/")?il.assetsPath:`${il.assetsPath}/`}esri/images/search/search-symbol-32.png`,a=(await vy(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!a?.extent||!a.location)throw new Error(`Could not find location for: ${t}`);let i=new Ty({url:s,width:24,height:24}),u=new Iy({geometry:a.location,symbol:i});e.graphics.removeAll(),e.graphics.add(u),await e.goTo(a.extent);let l={address:a.address??"",location:a.location?a.location.toJSON():null,extent:a.extent?a.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var s_=["mapView"];function at(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=s_.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function a_({address:t},e){let{mapView:r}=at(e);return await o_(t,r)}var i_=m.object({address:m.string().describe("The full address or place name to locate.")}),l_=j(a_,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:i_});async function u_(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 c_({bookmarkName:t},e){let{mapView:r}=at(e);return await Promise.resolve(u_(t,r))}var d_=v.object({bookmarkName:v.string().describe("The name of the bookmark to navigate to.")}),p_=j(c_,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:d_});async function m_(t,e,r){let n=r.map?.allLayers.find(a=>a.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:a,count:i}=await n.queryExtent(s);if(i===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(a)await r.goTo(a);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let u={layerId:t,layerTitle:n.title??t,where:o,count:i};return{text:`Successfully zoomed to ${i} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(a){return console.error("Error in goToFeatures:",a),{text:`Error: ${a instanceof Error?a.message:"Unknown error"}`,where:o}}}async function f_({layerId:t,where:e},r){let{mapView:n}=at(r);return await m_(t,e,n)}var h_=v.object({layerId:v.string().describe("The layerId of the layer to zoom to."),where:v.string().describe("ArcGIS SQL-92 WHERE expression used for `query.where` on the selected layer. Use only fields from that layer and return a boolean filter expression (for example comparisons, LIKE, IN, BETWEEN, IS NULL, AND/OR/NOT). Do NOT include subqueries/nested SELECT, JOIN, GROUP BY, HAVING, ORDER BY, or semicolons.")}),g_=j(f_,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:h_});async function y_(t){let e=new Sy({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 __(t,e){let{mapView:r}=at(e);return await y_(r)}var w_=v.object({}),b_=j(__,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:w_});async function x_(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 A_(t,e){let{mapView:r}=at(e);return await x_(r)}var I_=m.object({}),v_=j(A_,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:I_});async function T_(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 S_({layerId:t},e){let{mapView:r}=at(e);return await T_(t,r)}var k_=v.object({layerId:v.string().describe("The id of the layer to navigate to")}),C_=j(S_,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:k_});async function E_(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function P_({scale:t},e){let{mapView:r}=at(e);return await E_(t,r)}var O_=m.object({scale:m.number().describe("The map scale of the view to go to.")}),M_=j(P_,{name:"goToScale",description:"Go to the specified view scale.",schema:O_});async function R_(t,e,r){let n={target:new Vp({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 $_({center:t,zoom:e,scale:r},n){let{mapView:o}=at(n);return await R_(t,o,{zoom:e,scale:r})}var N_=m.object({center:m.object({longitude:m.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:m.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:m.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:m.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),z_=j($_,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:N_});async function j_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function L_({zoom:t},e){let{mapView:r}=at(e);return await j_(t,r)}var D_=m.object({zoom:m.number().min(1).max(20).describe("The zoom level of the view to go to.")}),F_=j(L_,{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:D_}),Kp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./IJ3CLFAU.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./QE4CNVDQ.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./SLTFLCVR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./KNRJ3WXR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./WBZLQZYR.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./W4SAWMXS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./C7ZFXRPS.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./W4FGRGLV.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./QKCV7CY2.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./W2SYL7IJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./3OBIA66A.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./63THOLAY.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./L6KBBJEC.js").then(t=>t.default)});async function At(t){let e=Object.entries(Kp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
104
+ Available prompts:
105
+ ${Object.keys(Kp).join(`
106
+ `)}`);return await e[1]()}var wo=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function U_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s?a=Cy({basemapTheme:await Up(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:a=Ey({basemapTheme:await Up(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(i=>({field:i,label:r.fields.find(u=>u.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:a}}async function q_(t){return await ky(t)}async function B_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"chart-size":"chart",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=await U_(u),c=await q_(l);return i.renderer=c.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var K_=["mapView"];function Ve(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=K_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function G_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await B_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var W_=m.object({layerId:m.string().describe("The id of the layer to apply the chart renderer to"),fields:m.array(m.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),includeSize:m.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),V_=j(G_,{name:"chart",description:`Label: Charts
107
+ Description: Show the values of two or more categories as a proportion of the total using a pie chart.
108
+ Keywords: pie, chart, all categories, breakdown, proportion
109
+ Example: Show the total number of homes built in each decade using a pie chart for each feature.
110
+ Fields: This style requires 2-8 number fields.
111
+
112
+ Label: Charts and Size
113
+ 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.
114
+ Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
115
+ 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.
116
+ Fields: This style requires 2-8 number fields.`,schema:W_});function H_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,a=e[0],i;return s&&(i=yl({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:a,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function J_(t){return await Py(t)}async function Z_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=H_(u),c=await J_(l);return i.renderer=c.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Q_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await Z_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Y_=m.object({layerId:m.string().describe("The id of the layer to apply the color-age renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),theme:m.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),X_=j(Q_,{name:"color-age",description:`Label: Age (color)
117
+ 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.
118
+ Keywords: since, age, how old, how long
119
+ Example: Show the age of each feature based on its reported date.
120
+ Fields: This style requires at least one field with a date type.`,schema:Y_});function ew(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,a=e[1],i=e[0],u;return o&&(u=yl({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:i,normalizationField:a,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:u}}async function tw(t){return await Oy(t)}async function rw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=ew(u),c=await tw(l);return i.renderer=c.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function nw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await rw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var ow=m.object({layerId:m.string().describe("The id of the layer to apply the color renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the color renderer"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),theme:m.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),sw=j(nw,{name:"color",description:`Label: Counts and Amounts (color)
121
+ Description: Vary color along a continuous color ramp to represent numeric or ranked data.
122
+ Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
123
+ Example: Color each feature based on the population density.
124
+ 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:ow});function aw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,a,i,u=e[0];return o&&(i=yl({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:u,normalizationField:a,theme:s,colorOptions:{colorScheme:i}}}async function iw(t){return await My(t)}async function lw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"color-size-univariate",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=aw(u),c=await iw(l);return i.renderer=c.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function uw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await lw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var cw=m.object({layerId:m.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:m.array(m.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),theme:m.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),dw=j(uw,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
125
+ Description: Vary symbol size and color based on the values of two numeric attributes.
126
+ Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
127
+ 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.
128
+ 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:cw});function pw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=$y({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(a=>({field:a,label:r.fields.find(i=>i.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function mw(t){return await Ry(t)}async function fw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=pw(i),l=await mw(u);return a.renderer=l.renderer,a.visible=!0,`Dot Density renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying dot density renderer: ${u instanceof Error?u.message:String(u)}`}}async function hw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ve(n);return await ve({type:"show-legend",data:{layerIds:[t]}},n),await fw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var gw=m.object({layerId:m.string().describe("The id of the layer to apply the dot density renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use")}),yw=j(hw,{name:"dot-density",description:`Dot Density
129
+ Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
130
+ **Use cases:**
131
+ - Population distribution visualization
132
+ - Comparing multiple categories within areas
133
+ - Showing spatial distribution patterns
134
+ **Examples:**
135
+ - Show the density of the population based on various race/ethnic groups
136
+ - Visualize distribution of different crops across regions
137
+ - Display demographic patterns within census tracts
138
+ **Fields:** Requires 2-8 number fields.
139
+ **Keywords:** density, how much, how many, total, number, amount`,schema:gw});function _w(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a=e[0];return o&&(s=zy({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:a,heatmapScheme:s}}async function ww(t){return await Ny(t)}async function bw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=_w(i),l=await ww(u);return a.renderer=l.renderer,a.visible=!0,`Heatmap renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying heatmap renderer: ${u instanceof Error?u.message:String(u)}`}}async function xw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ve(n);return await ve({type:"show-legend",data:{layerIds:[t]}},n),await bw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Aw=m.object({layerId:m.string().describe("The id of the layer to apply the heatmap renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use")}),Iw=j(xw,{name:"heatmap",description:`Label: Heat Map
140
+ Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
141
+ Keywords: density, heatmap, hot spots, pattern, cluster
142
+ Example: Create a heatmap
143
+ Fields: This typically requires zero or one field of type number.`,schema:Aw});function vw(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,a;return s&&(a=Ly({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:a}}async function Tw(t){return await jy(t)}async function Sw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:s?"predominance-size":"predominance",fields:n,layer:i,view:a,colorSchemeTags:o};try{let l=vw(u),c=await Tw(l);return i.renderer=c.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function kw({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await Sw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var Cw=m.object({layerId:m.string().describe("The id of the layer to apply the predominance renderer to"),fields:m.array(m.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),includeSize:m.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),Ew=j(kw,{name:"predominance",description:`Label: Predominant category
144
+ Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
145
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
146
+ Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
147
+ Fields: This style relies on 2-10 number fields.
148
+
149
+ Label: Predominant category and Size
150
+ 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.
151
+ Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
152
+ Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
153
+ Fields: This style relies on 2-10 number fields.`,schema:Cw});function Pw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,a={field:e[0]},i={field:e[1]};return o&&(s=Fy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:a,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function Ow(t){return await Dy(t)}async function Mw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,a=t?.allLayers.find(u=>u.id===r);if(!a)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:n,layer:a,view:s,colorSchemeTags:o};try{let u=Pw(i),l=await Ow(u);return a.renderer=l.renderer,a.visible=!0,`Relationship renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(u){return`Error applying relationship renderer: ${u instanceof Error?u.message:String(u)}`}}async function Rw({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Ve(n);return await ve({type:"show-legend",data:{layerIds:[t]}},n),await Mw({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var $w=m.object({layerId:m.string().describe("The id of the layer to apply the relationship renderer to"),fields:m.array(m.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use")}),Nw=j(Rw,{name:"relationship",description:`Label: Relationship
154
+ Description: Overlays two color ramps to represent the relationship between two numeric attributes.
155
+ Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
156
+ Example: Show the relationship between tree height and carbon storage
157
+ Fields: This style requires two number fields.`,schema:$w});function zw(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 jw(t){return await Uy(t)}async function Lw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size-age",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=zw(u),c=await jw(l);return i.renderer=c.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function Dw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await Lw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Fw=m.object({layerId:m.string().describe("The id of the layer to apply the size-age renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),theme:m.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Uw=j(Dw,{name:"size-age",description:`Label: Age (size)
158
+ 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.
159
+ Keywords: since, age, how old, how long
160
+ Example: Change the size of features so older features are larger than new features.
161
+ Fields: This style requires at least one field with a date type.`,schema:Fw});function qw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],a=e[0];return{layer:r,view:n,field:a,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Bw(t){return await qy(t)}async function Kw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"size",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=qw(u),c=await Bw(l);return i.renderer=c.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function Gw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await Kw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Ww=m.object({layerId:m.string().describe("The id of the layer to apply the size renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),theme:m.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Vw=j(Gw,{name:"size",description:`Label: Counts and Amounts (size)
162
+ Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
163
+ Keywords: graduated size, proportional size, how much, total, number, amount, size
164
+ Example: Vary the size of each point based on the total population.
165
+ 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.
166
+
167
+ Label: Continuous Timeline (size)
168
+ Description: Vary symbol sizes along a continuous ramp to represent dates.
169
+ Keywords: graduated size, proportional size, classed size, how much, total, number, when
170
+ Example: Vary the size of each feature based on the date a ticket was completed.
171
+ Fields: This style requires a single field with a date type.`,schema:Ww});function Hw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],a=e[1],i=e[2],u;return o&&(u=Ky({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:a,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:u}}async function Jw(t){return await By(t)}async function Zw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let a=e,i=t?.allLayers.find(l=>l.id===r);if(!i)return`Could not find layer for id: ${r}`;let u={styleName:"type",fields:n,layer:i,view:a,colorSchemeTags:o,theme:s};try{let l=Hw(u),c=await Jw(l);return i.renderer=c.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function Qw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Ve(o);return await ve({type:"show-legend",data:{layerIds:[t]}},o),await Zw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var Yw=m.object({layerId:m.string().describe("The id of the layer to apply the type renderer to"),fields:m.array(m.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:m.array(m.string()).optional().describe("Optional color scheme tags to use"),theme:m.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),Xw=j(Qw,{name:"type",description:`Label: Types (unique symbols)
172
+ Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
173
+ Keywords: categorical, category, type, unique, discrete, point of interest, region, group
174
+ Example: Color each feature based on the region it belongs to
175
+ Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:Yw}),eb=M.Root({...Nr(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),selectedLayerId:M()}),tb=M.Root({...Nr(),vectorSearchLayerIds:M(),vectorSearchFieldResults:M(),layerFieldInfo:M(),queryResponse:M(),dataExplorationMessages:M({reducer:Po,default:()=>[]})}),rb=["mapView"];function Yt(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=rb.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var nb=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."},ob=async(t,e)=>{let{mapView:r}=Yt(e);return nb(r)},TW=j(ob,{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:m.object({})}),sb=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."},ab=async(t,e)=>{let{mapView:r}=Yt(e);return await sb(r)},SW=j(ab,{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:m.object({})}),Gp=750;function Na(t){return"point"in t&&t.point!==void 0}function fs(t){return"layerId"in t&&t.layerId!==void 0}var La=async(t,e)=>{if(Na(t)){let{point:r}=t;return{geometry:new Vp({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(fs(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:Gp+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>Gp)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let a=s.features.map(u=>u.geometry).filter(u=>!!u);if(!a.length)return{error:"No valid geometries found for the matched geometry layer features."};let i=a.length===1?a[0]:Jp.executeMany(a);return i?(i.spatialReference||(i.spatialReference=e.spatialReference),{geometry:i}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},ib=async(t,e,r,n,o,s)=>{let a=t.map?.allLayers.find(u=>u.id===e);if(!a)return{success:!1,error:`Layer '${e}' not found.`};let i=a.createQuery();i.where=r??"1=1",n&&(i.geometry=n,i.spatialRelationship="intersects",o&&(i.distance=o),s&&(i.units=s));try{let{extent:u,count:l}=await a.queryExtent(i);return!u||l===0?{success:!1,error:`No features found for filter (where: ${i.where}${n?", spatial filter used":""})`}:(await t.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},lb=async(t,e,r,n,o,s)=>{let a=e.map?.allLayers.find(p=>p.id===t.layerId);if(!a)return`Could not find target layer with ID: ${t.layerId}`;let i;if(o){let p=await La(o,e);if("error"in p)return p.error;i=p.geometry}if(a.featureEffect=null,a.featureEffect=new Gy({filter:new Hp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),a.visible=!0,s)return`Applied feature effects to "${a.title??t.layerId}" within current map extent.`;let u=t.objectIds?.length?`${a.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await ib(e,t.layerId,u,i,o?.distance,o?.units),c=a.title??t.layerId;return l.success?`Applied feature effects to target layer "${a.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},ub=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],Xt=m.enum(ub),cb=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:a}=Yt(s);return await lb(t,a,n,o,e,r)},db=m.object({layerId:m.string().describe("The layerId of the layer containing the geometry by which to filter."),where:m.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:m.number().optional().describe("The buffer distance around the geometry."),units:Xt.optional().describe("The units for the distance buffer.")}),pb=m.object({point:m.object({x:m.number().describe("X coordinate (longitude) from navigation result"),y:m.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:m.object({wkid:m.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:m.number().optional().describe("Optional buffer distance around the point."),units:Xt.optional().describe("The units for the distance buffer.")}),mb=m.object({targetLayer:m.object({layerId:m.string().describe("The layerId of the layer on which to set a feature effect."),where:m.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:m.array(m.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:m.union([db,pb]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:m.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:m.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:m.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.")}),kW=j(cb,{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:mb}),fb=new Set(["date","esrifieldtypedate","date-only","dateonly","esrifieldtypedateonly","time-only","timeonly","esrifieldtypetimeonly","timestamp-offset","timestampoffset","esrifieldtypetimestampoffset"]),Qp=t=>{if(!t)return!1;let e=t.toLowerCase();return fb.has(e)},ul=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},hb=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,gb=t=>{if(typeof t=="string"&&t)return t;let e=ul(t);return e?e.toISOString().slice(0,10):null};var yb=(t,e,r)=>{let n=e?.toLowerCase();if(n&&!Qp(n))return t;if(n==="date-only"){let s=gb(t);return s?Wy(s,Ma("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return Vy(t,Ma("long-time"));let s=ul(t);return s?qp(s,{...Ma("long-time"),timeZone:"UTC"}):t}let o=ul(t);return o?qp(o,{...Ma("short-date-short-time"),timeZone:hb(r)}):t},Yp=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(a=>a.code===e);return s?s.name:null}}return null},_b=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,wb=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},bb=(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}},xb=(t,e,r)=>{let n=wb(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=_b(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},Xp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,em=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?bb(r,s):s?.type==="date-time"?!n||Qp(n)?xb(r,s,o):r:yb(r,n,o)},Ab=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=Yp(e,r,t)??r;return em(t,e,s,o?.type,n)},Ib=(t,e)=>Xp(t,e),tm=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(a=>a.attributes[n]),s=e.features.map(a=>{let i=a.attributes,u={};return t.fields.forEach(l=>{if(!Object.hasOwn(i,l.name))return;let c=i[l.name];if(l.name===n){u[l.name]=c;return}let p=Yp(l.name,c,t)??c,d=Xp(t,l.name);u[d]=em(t,l.name,p,l.type,r)}),u});return{objectIds:o,attributes:s}},vb=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},Tb=async(t,e,r,n)=>{let o=n.map?.allLayers.find(c=>c.id===t),s=vb(o,e,r.where),a=(await o.queryFeatures(s)).features[0],i=a?a.attributes[e]:null,u=Ab(o,e,i,n.timeZone),l=Ib(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${u}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:u,where:r.where}}};async function Sb({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Yt(n),s=await Tb(t,e,r,o);return JSON.stringify(s,null,2)}var kb=m.object({layerId:m.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:m.string().describe("The name of the field/attribute from which to get a field value."),query:m.object({where:m.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Cb=j(Sb,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:kb}),_l=(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 za(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Eb=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:a}=t,i=o.map?.allLayers.find(f=>f.id===e.layerId);if(!i)throw new Error(`Layer '${e.layerId}' not found.`);let u=await o.whenLayerView(i),l=s.get(e.layerId)?.fieldRegistry.get(r),c=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let p,d;if(a){let f=await La(a,o);if("error"in f)throw new Error(f.error);if(!f.geometry)throw fs(a)?new Error(`No features found matching: ${a.where}`):new Error("Failed to create geometry");if(fs(a)){let A=o.map?.allLayers.find(T=>T.id===a.layerId);p={geometryLayerName:A?.title??A?.id,geometryLayerId:a.layerId,geometryWhere:a.where,distance:a.distance,units:a.units,applied:!0}}else Na(a)&&(p={point:a.point,distance:a.distance,units:a.units,applied:!0});d=new Hp({geometry:f.geometry,distance:a.distance,units:a.units,spatialRelationship:"intersects"})}let g=_l(u,[r],!1),y=null,w=null,_=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let f={layer:i,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:za(i.definitionExpression,e.where),...d&&{filter:d},outStatisticTypes:{include:[n]}};y=await Hy(f);let A=["string","small-integer","integer"],T=l.domain?.type==="coded-value"?l.domain:null;(A.includes(l.type)||T)&&(w=(await Jy({layer:i,useFeaturesInView:g,view:g?o:void 0,field:r,sqlWhere:za(i.definitionExpression,e.where),...d&&{filter:d}})).uniqueValueInfos.sort((E,G)=>G.count-E.count).slice(0,_)),w&&l.domain?.type==="coded-value"&&(w=w.map(E=>({...E,value:T?T.getName(E.value)??E.value:E.value})))}catch(f){console.error("Statistics error:",f)}return{tool:"getStatistics",layerName:i.title??e.layerId,summary:`${n} = ${typeof y?.[n]=="number"?y[n]:"N/A"}`,details:{fieldName:r,fieldAlias:c,statisticType:n,statistic:y?.[n]??null,summaryStatistics:y,uniqueValues:w,where:e.where,spatialFilterInfo:p}}};async function Pb({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=wo(o,"layersAndFieldsRegistry"),{mapView:a}=Yt(o),i=await Eb({targetLayer:t,fieldName:e,statisticType:r,mapView:a,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(i,null,2)}var Ob=m.object({layerId:m.string().describe("The layerId of the layer containing the geometry by which to filter."),where:m.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:m.number().optional().describe("The buffer distance around the geometry."),units:Xt.optional().describe("The units for the distance buffer.")}),Mb=m.object({point:m.object({x:m.number().describe("X coordinate (longitude) from navigation result"),y:m.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:m.object({wkid:m.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:m.number().optional().describe("Optional buffer distance around the point."),units:Xt.optional().describe("The units for the distance buffer.")}),Rb=m.object({targetLayer:m.object({layerId:m.string().describe("The layerId of the layer containing the field from which to get a value."),where:m.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:m.union([Ob,Mb]).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:m.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:m.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),$b=j(Pb,{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.
176
+
177
+ USE THIS TOOL FOR:
178
+ - "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
179
+ - "Most common/frequent value of [field]?" \u2014 frequency analysis
180
+ - Questions requiring a mathematical aggregation across many features
181
+
182
+ DO NOT USE FOR:
183
+ - "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
184
+ - "Show / list / find features" \u2014 use queryFeatures instead
185
+ - Simple counts of features matching a condition \u2014 use queryFeatures instead
186
+
187
+ 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:Rb}),Nb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),zb=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(d=>d.id===t.layerId),a=await r.whenLayerView(s),i=s.title??t.layerId,u;if(n){let d=await La(n,r);if("error"in d)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:d.error}};if(!d.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};u=d.geometry}else o&&(u=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,c=s.objectIdField,p=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])];try{let d;if(l){let w=new Zy({where:t.where||"1=1",outFields:p,orderByFields:t.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new Qy({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});d=await s.queryTopFeatures(w)}else{let w=s.createQuery();w.where=za(s.definitionExpression,t.where||"1=1"),w.outFields=p.length?p:["*"],w.orderByFields=e.orderByFields,w.returnGeometry=!1,w.num=e.topCount,u&&(w.geometry=u,w.spatialRelationship="intersects"),n?.distance&&(w.distance=n.distance),n?.units&&(w.units=n.units),w.outSpatialReference=r.spatialReference;let _=[...new Set([...t.outFields,...Nb(e.orderByFields)])],f=_l(a,_,o??!1);try{d=f?await a.queryFeatures(w):await s.queryFeatures(w)}catch(A){console.warn("Client-side query failed, falling back to server:",A),d=await s.queryFeatures(w)}}let g=d.features.map(w=>w.attributes[c]),{attributes:y}=tm(s,d,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:y,objectIds:g,objectIdField:c,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(d){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:d instanceof Error?d.message:String(d)}}}},jb=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Yt(o),a=await zb(t,e,s,r,n);return JSON.stringify(a,null,2)},Lb=m.object({layerId:m.string().describe("The layerId of the layer containing the geometry by which to filter."),where:m.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:m.number().optional().describe("The buffer distance around the geometry."),units:Xt.optional().describe("The units for the distance buffer.")}),Db=m.object({point:m.object({x:m.number().describe("X coordinate (longitude) from navigation result"),y:m.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:m.object({wkid:m.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:m.number().optional().describe("Optional buffer distance around the point."),units:Xt.optional().describe("The units for the distance buffer.")}),Fb=m.object({targetLayer:m.object({layerId:m.string().describe("The layerId of the layer containing the field from which to get a value."),where:m.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:m.array(m.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:m.array(m.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:m.union([Lb,Db]).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:m.object({topCount:m.number().describe("Number of top features to return per group."),orderByFields:m.array(m.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:m.array(m.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:m.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).")}),Ub=j(jb,{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:Fb}),ll=25,qb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Bb=async(t,e,r,n)=>{let o=e.map?.allLayers.find(_=>_.id===t.layerId),s=await e.whenLayerView(o),a=o.title??t.layerId,i;if(r){let _=await La(r,e);if("error"in _){let f={error:_.error};if(fs(r)){let A=e.map?.allLayers.find(T=>T.id===r.layerId);f.geometryLayerName=A?.title??A?.id,f.geometryLayerId=r.layerId,f.geometryWhere=r.where}else Na(r)&&(f.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"Geometry lookup failed",details:f}}if(!_.geometry){let f={};if(fs(r)){let A=e.map?.allLayers.find(T=>T.id===r.layerId);f.error=`No features found matching: ${r.where}`,f.geometryLayerName=A?.title??A?.id,f.geometryLayerId=r.layerId,f.geometryWhere=r.where}else Na(r)&&(f.error="Failed to create point geometry",f.point=r.point);return{tool:"queryFeatures",layerName:a,summary:"No features found for geometry filter",details:f}}i=_.geometry}else n&&(i=e.extent.clone());let u=[...new Set([...t.outFields,...qb(t.orderByFields)])],l=_l(s,u,n??!1),c=o.objectIdField,p=o.createQuery();p.where=za(o.definitionExpression,t.where||"1=1"),p.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,c])],p.orderByFields=t.orderByFields,i&&(p.geometry=i,p.spatialRelationship="intersects"),r?.distance&&(p.distance=r.distance),r?.units&&(p.units=r.units),p.outSpatialReference=e.spatialReference;let d,g;try{d=l?await s.queryFeatureCount(p):await o.queryFeatureCount(p),d>0&&d<=ll&&(g=l?await s.queryFeatures(p):await o.queryFeatures(p))}catch(_){console.warn("Client-side query failed, falling back to server:",_),d=await o.queryFeatureCount(p),d>0&&d<=ll&&(g=await o.queryFeatures(p))}let{objectIds:y,attributes:w}=g?tm(o,g,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:a,summary:`${d} features found`,details:{totalCount:d,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...y&&{objectIds:y,objectIdField:c},...w&&{attributes:w},...d>ll&&{note:`${d} features found.`}}}};async function Kb({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Yt(n),s=await Bb(t,o,e,r);return JSON.stringify(s,null,2)}var Gb=m.object({layerId:m.string().describe("The layerId of the layer containing the geometry by which to filter."),where:m.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:m.number().optional().describe("The buffer distance around the geometry."),units:Xt.optional().describe("The units for the distance buffer.")}),Wb=m.object({point:m.object({x:m.number().describe("X coordinate (longitude) from navigation result"),y:m.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:m.object({wkid:m.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:m.number().optional().describe("Optional buffer distance around the point."),units:Xt.optional().describe("The units for the distance buffer.")}),Vb=m.object({targetLayer:m.object({layerId:m.string().describe("The layerId of the layer containing the field from which to get a value."),where:m.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:m.array(m.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:m.array(m.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:m.union([Gb,Wb]).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:m.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).")}),Hb=j(Kb,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
188
+
189
+ USE THIS TOOL FOR:
190
+ - "Show / display / list features where..." \u2014 finding and listing features
191
+ - "How many X are Y?" \u2014 counting features that match a condition
192
+ - "Which features..." / "Find features..." \u2014 identifying specific features
193
+ - Spatial queries \u2014 finding features near/within/intersecting other features
194
+ - Any question where the user wants to SEE or COUNT matching features
195
+
196
+ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Vb}),rm=[Cb,$b,Ub,Hb];var CW=new xt(rm,{handleToolErrors:!1});var Jb=M.Root({...Nr(),helpInternalState:M({reducer:ms,default:()=>({toolCallMessage:void 0})})}),Zb=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(a=>a.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
197
+ `);return`**${r.layerItem.title}** has ${n.length} field(s):
198
+
199
+ ${o}`},Qb=async({layerTitle:t},e)=>{let r=wo(e,"layersAndFieldsRegistry");return Zb(r,t)},Yb=j(Qb,{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:m.object({layerTitle:m.string().describe("The title or partial title of the layer to list fields for.")})}),Xb=M.Root({...Nr(),intent:M({reducer:(t,e)=>e}),arcgisKnowledgeMessages:M({reducer:Po,default:()=>[]}),arcgisKnowledgeToolResult:M({reducer:(t,e)=>e,default:()=>null})});function nm(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 bo(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function Da(t){!t||bo(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function gs(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)&&nm(r),{view:r}}async function xo(t){let e=t?.configurable?.context;if(ex(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 Bp(n)}}else{nm(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 Bp(n)}}}}function ex(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 cl=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ja.fromDataModel(e)}},ja=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(hs.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(dl.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:tx(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}.
200
+ Relationship Types: ${n}.`}},hs=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=rx(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:nx(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}},dl=class extends hs{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=hs.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},tx=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},rx=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function nx(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 Fa(t){return t?.signal}async function ox(t,e){let r=await At("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
201
+
202
+ Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
203
+
204
+ Attempt Number: ${e.attemptCount}
205
+ Execution Error: ${e.executionError}
206
+ Failed Query:
207
+ ${e.failedGraphQuery}`:`${t} ${r}`}async function sx(t,e,r,n){let{graphQuery:o,explanation:s}=await wl(t,e,r,n);return{graphQuery:o,explanation:s}}async function wl(t,e,r,n,o){let s={message:await ox(t,o),context:new cl(e)},a=Fa(n);await oe({text:"Attempting to generate a cypher query from your prompt..."},n);let i=await Fp(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:Dp.findCredential(zr.getDefault().url)?.token??""},signal:a});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});let u=!1,l=Date.now(),c=i.data.sequenceNumber,p="",d="",g=1;for(;!u;){await new Promise(w=>setTimeout(w,1e3)),await oe({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,g)}`},n),g=g%3+1;let y=await Fp(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Dp.findCredential(zr.getDefault().url)?.token??""},signal:a});if(y.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${y.httpStatus}`,{cause:y.data});if(y.data.context?.kind){if(y.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${y.data.message}`,{cause:y.data});p=y.data.context.graphQuery,d=y.data.message||"",u=!0}else if(!y.data.hasMore)u=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=y.data.sequenceNumber}return{graphQuery:p,explanation:d}}function ax(t,e){yo(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function yo(t,e){if(!(!t||typeof t!="object")){if(lx(t))for(let r of t.path)yo(r,e);else if(ix(t))e(t);else if(Array.isArray(t))for(let r of t)yo(r,e);else if(ux(t))for(let r of Object.values(t.properties??{}))yo(r,e)}}function ix(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function lx(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function ux(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function cx(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,a]of o)for(let i of s){let u=t.getMemberIdsByType(i.name);a.push(...u)}return{entityIds:r,relationshipIds:n}}function dx(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(i=>i.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],a=!0;for(let[i,u]of s)for(let l of i){let c=o.namedTypeDefinitions.get(l.name);if(!c){a=!1,n.push(l.name);continue}if(!c.useAllData){a=!1,n.push(l.name);for(let[p]of c.members||[])u.push(p)}}return{allNamedTypesFullyDynamic:a,bindParameters:r,nonDynamicTypes:n}}var _o=3;function om(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 Ao(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 px=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:a})=>{let i=null,u=r,l=new AbortController,c=o?.signal,p=()=>{l.abort(c?.reason)};c&&(c.aborted?l.abort(c.reason):c.addEventListener("abort",p,{once:!0}));try{let d=await Xy(t,e,o);i=d.resultHeader;let g=d.resultRowsStream.getReader(),y=0,w=Date.now(),_=!1;for(;;){let{done:f,value:A}=await g.read();if(f)break;if(!_&&a&&Date.now()-w>a)return l.abort(),{type:"timeout"};for(let T of A){if(y++,s&&y>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:i,processedResult:u};u=n(u,T)}}}catch(d){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Ao(d),error:d}}finally{c?.removeEventListener("abort",p)}return{type:"success",rowLimitReached:!1,resultHeader:i,processedResult:u}};async function sm({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u,config:l}){let c;for(let p=1;p<=_o;p++){let d;try{d=await wl(t,r.dataModel,n,l,c)}catch(_){return{type:"generation-error",errorMessage:Ao(_),error:_}}await oe({text:`Attempting to execute query: ${d.graphQuery.substring(0,500)}${d.graphQuery.length>500?"...":""}`},l);let g=await mx(d.graphQuery,e),y=await px({kg:r,queryParams:new Zp({openCypherQuery:d.graphQuery,bindParameters:g}),targetStructure:o,targetStructureReducer:s,requestOptions:a,queryRowLimit:i,queryTimeoutMs:u}),w=y.type==="aborted"?"Query execution was aborted.":y.type==="timeout"?"Query execution timed out.":y.type==="error"?`Query failed with error: ${y.errorMessage}`:"";if(y.type==="success")return{type:"success",graphQuery:d.graphQuery,explanation:d.explanation,rowLimitReached:y.rowLimitReached,resultHeader:y.resultHeader,processedResult:y.processedResult};if(y.type==="aborted")return{type:"aborted",errorMessage:w,graphQuery:d.graphQuery,explanation:d.explanation};if(p>=_o)return y.type==="timeout"?{type:"timeout",errorMessage:w,graphQuery:d.graphQuery,explanation:d.explanation}:{type:"execution-error",errorMessage:w,error:y.error,graphQuery:d.graphQuery,explanation:d.explanation};c={failedGraphQuery:d.graphQuery,executionError:w,attemptCount:p},await oe({text:`Attempt ${p} failed with error: ${w}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${_o} attempts.`)}var mx=async(t,e)=>{if(!e)return{};let{bindParameters:r,parseErrors:n}=await r_(t);if(n)return e;let o={};for(let s of r)s in e&&(o[s]=e[s]);return o},fx=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let a=[],i=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(i=["entity","relationship"]);let u=o??1/0;try{for(let l of i){let c=u-a.length;if(c<=0)break;let p=(await e_(t,new t_({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:c}),s)).resultRowsStream.getReader(),d=!1;for(;!d;){let{done:g,value:y}=await p.read();if(g){d=!0;break}for(let w of y)for(let _ of w)a.push(_)}}}catch(l){let c=Ao(l);return s?.signal?.aborted?{type:"aborted",errorMessage:c,error:l}:{type:"error",errorMessage:c,error:l}}return{type:"success",results:a}},am="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function im({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(am),!bo(e)&&e.map){let c=await At("arcgis_knowledge_current_lc_context"),p=cx(e.map,r);return o.push(c),{enhancedPrompt:o.join(`
208
+
209
+ `),bindParameters:p,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:a,bindParameters:i,nonDynamicTypes:u}=dx(s,r);if(a)return{enhancedPrompt:o.join(`
210
+
211
+ `),bindParameters:i,allNamedTypesFullyDynamic:!0};let l=(await At("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(u));return o.push(l),{enhancedPrompt:o.join(`
212
+
213
+ `),bindParameters:i,allNamedTypesFullyDynamic:a}}async function hx(t,e,r,n,o,s){let{view:a}=o,i=await sm({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(d,g)=>{for(let y of g)ax(y,d);return d},requestOptions:{signal:Fa(s),timeout:s?.timeout},config:s});if(i.type!=="success"){let d=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${d}`)}let{graphQuery:u,explanation:l,processedResult:c}=i,p=Array.from(c.values());return await oe({text:`Query Results parsed into ${p.length} unique relationships and entities. Atempting to add to link chart...`},s),!bo(a)&&a?.map?(await a.map.addRecords(p),await Da(a),{generatedQuery:u,explanation:l,addedIdTypePairs:p}):(await a?.map?.allLayers.find(d=>d.type==="knowledge-graph")?.addRecords(p),{generatedQuery:u,explanation:l,addedIdTypePairs:p})}var Ra="addRecords",gx=m.object({prompt:m.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.")}),yx=async({prompt:t},e)=>{let{knowledgeGraph:r}=await xo(e),n=gs(e),{view:o}=n,s=zr.getDefault().helperServices,{enhancedPrompt:a,bindParameters:i,allNamedTypesFullyDynamic:u}=await im({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(u)return{toolName:Ra,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:c,addedIdTypePairs:p}=await hx(a,i,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Ra,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
214
+
215
+ Number of records added: ${p.length}`,details:{generatedQuery:l,explanation:c,addedIdTypePairs:p}}}catch(l){let c=Ao(l);return{toolName:Ra,status:"error",errorMessage:`Failed to add records to the link chart. ${c}`,error:l}}},_x=j(yx,{name:Ra,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.
216
+
217
+ example prompts:
218
+ - "add all suppliers and the parts they produce to the link chart"
219
+ - "show me the competitors of company x and add them to the link chart"
220
+ - "add the relationships between company x and company y to the link chart"
221
+ - "expand all the companies"
222
+ - "expand company x through all the buildings it owns"
223
+ - "connect company x and company y"
224
+ - "connect all buildings on the link chart"
225
+ `,schema:gx});async function wx(t,e){return await e.map?.applyLayout(t),await Da(e),{appliedLayout:t}}var pl="applyLayout",bx=m.object({layout:m.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")}),xx=async({layout:t},e)=>{let{view:r}=gs(e);if(bo(r))return{toolName:pl,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await wx(t,r);return{toolName:pl,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},Ax=j(xx,{name:pl,description:"Apply a diagram layout to the link chart",schema:bx});async function Ix(t,e){return e.map?.changeNonspatialDataDisplay(t),await Da(e),{appliedNonspatialDataDisplayMode:t}}var ml="changeNonspatialVisibility",vx=m.object({setting:m.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Tx=async({setting:t},e)=>{let{view:r}=gs(e);if(bo(r))return{toolName:ml,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await Ix(t,r);return{toolName:ml,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},Sx=j(Tx,{name:ml,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:vx});async function kx(t,e,r,n,o){let s,a="";for(let i=1;i<=_o;i++){let{graphQuery:u,explanation:l}=await wl(t,e.dataModel,r,o,s);try{await oe({text:`Attempting to create link chart from derived query: ${u}`},o);let c=await Yy.fromCypherQuery(e,new Zp({openCypherQuery:u}));await oe({text:"Link chart created successfully, loading..."},o),await c.load();let p=n.map;return n.map=c,await n.when(),await Wp.whenOnce(()=>!n.updating),c.entityCount===0&&c.relationshipCount===0?(n.map===c&&(n.map=p),c.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
226
+ ${u}
227
+
228
+ Explanation: ${l}`}):(await Da(n),{type:"success",graphQuery:u,explanation:l})}catch(c){let p=Ao(c);if(i>=_o){a=p;break}s={failedGraphQuery:u,executionError:p,attemptCount:i},await oe({text:`Attempt ${i} to create link chart failed with error: ${p}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${_o} attempts. Last error: ${a}`}}var $a="createLinkChart",Cx=m.object({prompt:m.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.")}),Ex=async({prompt:t},e)=>{let{knowledgeGraph:r}=await xo(e),{view:n}=gs(e);if(bo(n))return{toolName:$a,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=zr.getDefault().helperServices,s=await kx(`${t}
229
+
230
+ ${am}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:$a,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:a,explanation:i}=s;return{toolName:$a,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
231
+ ${a}
232
+
233
+ Explanation: ${i}`,details:{generatedQuery:a,explanation:i}}}},Px=j(Ex,{name:$a,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:Cx}),fl="queryGraphData",Ox=m.object({prompt:m.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.")}),Mx=async({prompt:t},e)=>{let{knowledgeGraph:r}=await xo(e),n=zr.getDefault().helperServices,o=t,s=null,a=null;try{({view:a}=gs(e))}catch{}a&&({enhancedPrompt:o,bindParameters:s}=await im({prompt:t,view:a,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let i=await sm({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(w,_)=>(w.push(_),w),requestOptions:{signal:Fa(e),timeout:e?.timeout},config:e});if(i.type!=="success"){let w=i.type==="generation-error"?i.errorMessage:`${i.errorMessage} Cypher query: ${i.graphQuery}`;return{toolName:fl,status:"error",errorMessage:`Failed to query the knowledge graph. ${w}`,error:"error"in i?i.error:null}}let{graphQuery:u,explanation:l,processedResult:c,resultHeader:p}=i,d=p.headerKeys;for(let w of c)for(let _ of w)yo(_,f=>om(f));let g=50,y=c.slice(0,g).map(w=>JSON.stringify(w));return{toolName:fl,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
234
+
235
+ \`\`\`cypher
236
+ ${u}
237
+ \`\`\`
238
+
239
+ Query Results:
240
+ ${y.length} result(s) found.
241
+
242
+ Column Headers: ${d.join(", ")}
243
+
244
+ ${y.length>g?`Showing top ${g} results:
245
+
246
+ `:`Results:
247
+
248
+ `}${y.join(`
249
+ `)}
250
+ `,details:{generatedQuery:u,explanation:l,resultHeader:p,queryResults:c}}},Rx=j(Mx,{name:fl,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:Ox}),hl="generateCypher",$x=m.object({prompt:m.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Nx=async({prompt:t},e)=>{let{knowledgeGraph:r}=await xo(e),n=zr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await sx(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:hl,status:"success",summary:`Generated Graph Query:
251
+ ${o}
252
+
253
+ Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Ao(o);return{toolName:hl,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},zx=j(Nx,{name:hl,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:$x}),jx=t=>{let e=t.dataModel,r=new Map;for(let i of e.searchIndexes)if(i.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,l]of i.searchProperties.entries()){let c=r.get(u)??new Set;l.propertyNames.forEach(p=>c.add(p)),r.set(u,c)}let n=e.entityTypes.filter(i=>r.has(i.name)),o=e.relationshipTypes.filter(i=>r.has(i.name)),s=`Entity Types:
254
+ ${n.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
255
+ `)}`,a=`Relationship Types:
256
+ ${o.map(({name:i})=>`${i}: [${Array.from(r.get(i)??[]).join(", ")}]`).join(`
257
+ `)}`;return`${s}
258
+
259
+ ${a}`};async function Lx(t,e,r){let n=await At("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:jx(e)},s=m.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),a=m.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),i=m.array(m.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),u=m.object({query:m.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:i.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:a});return await ps({promptText:n,inputVariables:o,schema:u,config:r})}var gl="searchGraphData",Dx=m.object({prompt:m.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.")}),Fx=async({prompt:t},e)=>{let{knowledgeGraph:r}=await xo(e);await oe({text:"Generating search query for the user inquiry"},e);let n=await Lx(t,r,e);await oe({text:"Executing graph search with generated search query"},e);let o=await fx({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:Fa(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:gl,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let i of o.results)yo(i,u=>om(u));let s=10,a=o.results.slice(0,s);return{toolName:gl,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
260
+ Query: ${n.query}
261
+ Type Category Filter: ${n.typeCategoryFilter}
262
+ Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
263
+ Result Limit: ${n.resultLimit??"No limit"}
264
+
265
+ Search Results: ${o.results.length} result(s) found.
266
+
267
+ ${o.results.length>s?`Showing top ${s} results:
268
+
269
+ `:""}${a.map(i=>JSON.stringify(i)).join(`
270
+ `)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},Ux=j(Fx,{name:gl,description:`
271
+ 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.
272
+ Example prompts:
273
+ - "Find 'Bradley'"
274
+ - "find the person john smith"
275
+ - "find all people named smith"
276
+ - "Find all references to 'delayed parts shipment'"
277
+ - "Find all reports authored by someone with the title of 'Researcher'"
278
+ - "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".
279
+ - "Search for all john smiths and show their global ids`,schema:Dx});var GW=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
280
+ 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.
281
+
282
+ Supported actions:
283
+ - **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
284
+ - **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
285
+ - **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
286
+ - **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
287
+ - **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
288
+ - **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
289
+ - **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").
290
+ - **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
291
+
292
+ _Example: “Zoom to Texas”_
293
+ _Example: “Go to the water mains layer”_
294
+ _Example: “Zoom to to the extent of my link chart”_
295
+ _Example: “Center the map on San Francisco at scale 50000”_
296
+ _Example: “Zoom to the features in the schools layer where city = 'Austin'”_
297
+ _Example: “Go to the Downtown bookmark”_
298
+ _Example: “Where is Mount Rainier?”_`;var xV=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.
299
+ _Example: “Color points by sales amount”_
300
+ _Example: “Show population density with a color gradient”_
301
+ _Example: “Create a relationship map between height and depth”_
302
+ _Example: “Vary circle sizes according to population”_`;var GV=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).
303
+ 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.
304
+ _Example: “Only show stations where Brand is Shell”_
305
+ _Example: “Make Shell stations stand out on the map”_
306
+ _Example: “Gray out all stations that aren’t Shell”_
307
+ 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.
308
+ _Example: “How many features are there?”_
309
+ _Example: “What’s the average population?”_
310
+ _Example: “Which values are in the status field?”_
311
+
312
+ 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 lH=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
313
+
314
+ _Example: “Tell me about this map”_
315
+ _Example: “List all layers in this map”_
316
+ _Example: “List fields in protected areas layer”_
317
+ _Example: “What agents are available to me?”_
318
+ _Example: “What can you do?”_
319
+ _Example: “What can I ask”_
320
+
321
+ 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.
322
+
323
+ 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.
324
+ _Example: "Create a chart"_
325
+ _Example: "Create a table"_`;var SH=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).
326
+ 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.
327
+ 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,
328
+ 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
329
+ 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.
330
+ This agent is designed to handle requests that manipulate the specific link chart.
331
+ 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,
332
+ and can alternatively use those queries to create a new link chart visualization from the results if requested.
333
+
334
+ Supported actions:
335
+ - **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.
336
+ - **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.
337
+ - **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.
338
+ - **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
339
+ - **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.
340
+ - **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.
341
+ - **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.
342
+
343
+ _example: "Change the layout to hierarchical-bottom-to-top"_
344
+ _example: "Apply radial-root-centric layout"_
345
+ _example: "Show nonspatial data"_
346
+ _example: "Hide nonspatial data"_
347
+ _example: "Turn off nonspatial visibility"_
348
+ _example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
349
+ _example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
350
+ _example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
351
+ _example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
352
+ _example: "Find all people who work for Microsoft and put them on a new link chart"_
353
+ _example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
354
+ _example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
355
+ _example: "Find all the products supplied by Supplier X and add them to my visualization"_
356
+ _example: "Expand the link chart from 'Entity D' to show its direct connections"_
357
+ _example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
358
+ _example: "Connect Emma and Rob on the link chart if there is a relationship between them"
359
+ _example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
360
+ _example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
361
+ _example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
362
+ _example: "Find John Smith and all people he has made phone calls to in the last year"_
363
+ _example: "What is the average age of all people who work for Esri?"_`;var It=ps;var Ae=oe;var _s=()=>Oa(),qa=async(t,e)=>await ve(t,e),Ba=async({modelTier:t="default",temperature:e=0,config:r}={})=>await al({modelTier:t,temperature:e,config:r});var gm=t=>{let{portal:e,user:r}=t??{};return!!t&&!!e&&!!r};function jr(t){if(!gm(t))throw new Error("Invalid context: PortalAssistantContext with portal and user is required.")}var Gx=t=>t.map(e=>`"${e}"`).join(", "),Wx=m.object({successMessage:m.string().default("")}),cm="portal-group-creation",dm="approveAddMembers",Vx=async(t,e)=>{if(t.intentParams.intent!=="addMembers")return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let r=t.agentExecutionContext.sharedState.createdGroupId?.value;if(!r)return{status:"success",outputMessage:"Create a group first, then add members using @mention usernames."};let n=t.intentParams.memberInfo.memberIdentifiers.map(p=>p.trim()).filter(Boolean);if(!n.length)return{status:"success",outputMessage:"Use @mention usernames for the members you want to add."};let o=`The following member(s) will be added to the newly created group:
364
+
365
+ ${n.map(p=>`- **@${p}**`).join(`
366
+ `)}
367
+
368
+ Do you want to continue?`,{hitlResponse:s}=e?.configurable??{};if(s?.agentId!==cm||s.id!==dm){let p={agentId:cm,id:dm,kind:"booleanChoice",message:o,metadata:{action:"addMembers",groupId:r,members:[...n]}};throw new ws(p)}if(s.payload!==!0)return{status:"success",outputMessage:"Okay, I cancelled adding members to the group."};await Ae({text:`Adding members ${Gx(n)}...`,agentName:"group-creation"},e);let a=e?.configurable?.context;jr(a);let{result:i,error:u}=await uu(a.portal,r,n);if(u||!i)return{status:"success",outputMessage:"I could not add members to that group. Please confirm group access and user accounts, then try again."};let{addedUsernames:l,notAddedUsers:c}=i;try{let p=(await It({promptText:Hx,schema:Wx,modelTier:"fast",inputVariables:{addedMembers:l.join(", "),notAddedMembers:JSON.stringify(c.map(d=>({username:d.username,reason:d.error.message})))}})).successMessage;if(p)return{status:"success",outputMessage:p}}catch(p){console.error("Error generating add-members success message:",p)}return{}},Hx=`
369
+ Write a concise, friendly success message for adding members to a group.
370
+
371
+ Rules:
372
+ - Keep it to 1-2 short sentences.
373
+ - Use plain text only.
374
+ - If there is no notAddedMembers, confirm that all requested members were added successfully.
375
+ - If there are notAddedMembers, acknowledge that some members could not be added and list the added and not added members separately then mention why based on the context
376
+ - Make sure to bold the usernames
377
+
378
+ Added members:
379
+ {addedMembers}
380
+
381
+ Not added members:
382
+ {notAddedMembers}
383
+ `,pm="portal-group-creation",mm="approveCreateGroup",Jx=m.object({successMessage:m.string().default("")}),Zx=m.object({failureMessage:m.string().default("")}),Qx=async(t,e)=>{if(t.intentParams.intent!=="create")return{status:"success",outputMessage:"Tell me the group title you want to use."};let r=t.intentParams.title.trim();if(!r)return{status:"success",outputMessage:"What title would you like for the new group?"};let n=`A group with the title **${r}** will be created. Do you want to continue?`,{hitlResponse:o}=e?.configurable;if(o?.agentId!==pm||o.id!==mm){let l={agentId:pm,id:mm,kind:"booleanChoice",message:n,metadata:{action:"createGroup",title:r,access:"private"}};throw new ws(l)}if(o.payload!==!0)return{status:"success",outputMessage:`Okay, I cancelled creating **${r}**.`};await Ae({text:`Creating group "${r}"...`,agentName:"group-creation"},e);let s=e?.configurable?.context;jr(s);let{result:a,error:i}=await lu(s.portal,{title:r,access:"private"});if(i||!a){let l=i?.message?.trim()||"No additional details were provided.";try{let c=(await It({promptText:Xx,schema:Zx,modelTier:"fast",inputVariables:{groupTitle:r,failureReason:l}})).failureMessage.trim();if(c)return{status:"success",outputMessage:c}}catch(c){console.error("Error generating create-group failure message:",c)}return{status:"success",outputMessage:"I could not create that group. Please confirm your permissions and try again with the group title."}}let u=a.id;try{let l=(await It({promptText:Yx,schema:Jx,modelTier:"fast",inputVariables:{groupTitle:r}})).successMessage.trim();if(l)return{status:"success",outputMessage:l,sharedStatePatch:{createdGroupId:{value:u}},createdGroupId:u}}catch(l){console.error("Error generating create-group success message:",l)}return{}},Yx=`
384
+ Write a concise, friendly success message after creating a portal group.
385
+
386
+ Rules:
387
+ - Mention that the group was created successfully.
388
+ - Mention that the user can add members by using @mention usernames.
389
+ - Keep it to 1-2 short sentences.
390
+ - Make sure to bold the group title in the message.
391
+
392
+ Group title:
393
+ {groupTitle}
394
+ `,Xx=`
395
+ Write a concise, friendly failure message after an attempt to create a portal group.
396
+
397
+ Rules:
398
+ - Keep it to 1-2 short sentences.
399
+ - Use plain text only.
400
+ - Mention that group creation failed.
401
+ - Include the failure reason in user-friendly language.
402
+ - End with a clear next step the user can try.
403
+
404
+ Group title:
405
+ {groupTitle}
406
+
407
+ Failure reason:
408
+ {failureReason}
409
+ `,Lr=t=>{for(let e=t.length-1;e>=0;e-=1){let r=t[e];if(r.type!=="human")continue;let n=r.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.map(o=>typeof o=="string"?o:"text"in o&&typeof o.text=="string"?o.text:"").join(" ").trim()}return""},eA=m.object({intent:m.enum(["clarify","create","addMembers"]).default("clarify"),title:m.string().default(""),memberIdentifiers:m.array(m.string()).default([]),clarifyMessage:m.string().default("")}),tA=async(t,e)=>{await Ae({text:"Thinking about groups...",agentName:"group-creation"},e);let r=Lr(t.agentExecutionContext.messages).trim(),n=await It({promptText:rA,schema:eA,modelTier:"default",inputVariables:{userMessage:r}}),o=n.title.trim(),s=n.memberIdentifiers.filter(Boolean),a=n.clarifyMessage.trim(),i=n.intent==="create"&&!!o,u=n.intent==="addMembers"&&s.length>0;return{intentParams:i?{intent:"create",title:o}:u?{intent:"addMembers",memberInfo:{memberIdentifiers:s}}:{intent:"clarify"},status:"success",outputMessage:!i&&!u?a:""}},rA=`
410
+ You classify whether a user is asking to create a new ArcGIS Portal group or add members to an existing group.
411
+
412
+ Rules:
413
+ - Set intent="create" when the user asks to create a group and a title can be identified.
414
+ - Set intent="addMembers" when the user asks to add one or more members to a group.
415
+ - Set intent="clarify" when required data is missing or the request is ambiguous.
416
+ - For create requests, extract title only.
417
+ - For add-members requests, extract memberIdentifiers as ArcGIS usernames only (no @ prefix), but if you're returning a hint text asking for missing members, include the @ prefix.
418
+ - If the user includes mentions like @jsmith, return "jsmith" in memberIdentifiers.
419
+ - Do not extract group ids or group titles; add-members is a follow-up action that targets the most recently created group.
420
+ - When intent="clarify", provide a concise clarifyMessage describing exactly what is missing.
421
+ - If the user gives the title in quotes, extract exactly that title.
422
+ - If the user says create group <title> without quotes, extract only the title text after the create-group wording.
423
+ - If the user message looks like only a potential title (short phrase, not a question), treat it as the title and set intent="create".
424
+ - Return only extracted values. Do not add helper text into title or memberIdentifiers.
425
+ - Make sure to match the user's tone and texting style
426
+
427
+ Examples:
428
+ - help me create a new group "<title>" => intent="create", title="<title>", memberIdentifiers=[]
429
+ - add @<username1> and @<username2> => intent="addMembers", memberIdentifiers=["<username1>","<username2>"]
430
+ - add <member> => intent="addMembers", memberIdentifiers=["<member>"]
431
+ - help me create a new group => intent="clarify" with a question for missing title
432
+
433
+ User message:
434
+ {userMessage}
435
+ `,nA=m.discriminatedUnion("destinationType",[m.object({destinationType:m.literal("portal-content")}),m.object({destinationType:m.literal("portal-groups")}),m.object({destinationType:m.literal("portal-item"),itemId:m.string().trim().min(1)}),m.object({destinationType:m.literal("portal-group"),groupId:m.string().trim().min(1)})]),ym="portal-navigation",vl=async(t,e)=>{let r=e?.configurable?.context;!gm(r)||!r.navigationTargetMap?.[t.destinationType]||await qa({type:ym,data:{...t}},e)},oA=async(t,e)=>{let r=t.createdGroupId??t.agentExecutionContext.sharedState.createdGroupId?.value;return r?(await Ae({text:"Preparing navigation...",agentName:"group-creation"},e),await vl({destinationType:"portal-group",groupId:r},e),{}):{}},fm=(t,e)=>e??t,_m=M.Root({..._s(),intentParams:M({reducer:fm,default:()=>({intent:"clarify"})}),createdGroupId:M({reducer:fm,default:()=>""})}),sA=()=>new _e(_m).addNode("detectGroupCreationIntent",tA).addNode("createPortalGroup",Qx).addNode("addMembersToPortalGroup",Vx).addNode("suggestCreatedGroupNavigation",oA).addEdge(ge,"detectGroupCreationIntent").addConditionalEdges("detectGroupCreationIntent",t=>{switch(t.intentParams.intent){case"create":return"createPortalGroup";case"addMembers":return"addMembersToPortalGroup";default:return L}}).addEdge("createPortalGroup","suggestCreatedGroupNavigation").addEdge("addMembersToPortalGroup","suggestCreatedGroupNavigation").addEdge("suggestCreatedGroupNavigation",L),aA=String.raw`- **portal-group-creation** - Portal group creation assistant:
436
+ - creates a new ArcGIS Portal group for the signed-in user
437
+ - adds users to the newly created group using @mention usernames
438
+ `,iA={id:"portal-group-creation",name:"Portal Group Creation",description:aA,createGraph:sA,workspace:_m},wm="portalDocAssistantMemory",lA=()=>({conversationId:""}),uA=t=>{let e=t?.[wm]?.value;if(!e||typeof e!="object")return lA();let r=e;return{conversationId:typeof r.conversationId=="string"?r.conversationId:""}},cA=t=>({[wm]:{value:t}});async function dA({portal:t,question:e,persona:r,previousConversationId:n,signal:o,skillId:s}){s??="doc_ai_assistant";let a=await pA({portal:t,skillId:s,message:e,options:{context:{kind:"DocAIAssistantRequest",filters:{persona:{persona:r}}},previousConversationId:n,signal:o}});return{reply:mA(a,s),conversationId:a[0]?.conversationId??""}}async function pA({portal:t,skillId:e,message:r,options:n}){let o=`${t.helperServices.aiAssistantServices.url}/skills/${e}/chat`,s={"Content-Type":"application/json",token:Kx.findCredential(t.url)?.token??""},a=await um(o,{method:"post",body:JSON.stringify({message:r,context:n.context,conversationId:n.previousConversationId}),headers:s,signal:n.signal});if(a.httpStatus!==200)throw new Error(`Doc assistant chat failed (${a.httpStatus})`,{cause:a.data});let i=a.data,u=[i],{conversationId:l,inquiryId:c}=i,p=async(d,g)=>{if(!g)return;await Rl(1e3);let y=await um(o,{method:"post",body:JSON.stringify({conversationId:l,inquiryId:c,ackSequenceNumber:d}),headers:s,signal:n.signal});if(y.httpStatus!==200)throw new Error(`Doc assistant poll failed (${y.httpStatus})`,{cause:y.data});let w=y.data;u.push(w),await p(w.sequenceNumber,w.hasMore)};return i.hasMore&&await p(i.sequenceNumber,i.hasMore),u}function mA(t,e){switch(e){case"doc_chat":return t.find(r=>r.message!=null)?.message??"";case"doc_ai_assistant":for(let r=t.length-1;r>=0;r-=1){let n=t[r];if(n.context?.kind==="DocAIAssistantContext"){let o=n.context.results?.[0]?.reply;if(o)return o}}return"";default:return To(e)}}var fA=async(t,e)=>{await Ae({text:"Asking documentation assistant...",agentName:"doc-assistant"},e);let r=Lr(t.agentExecutionContext.messages).trim();if(!r)return{status:"success",outputMessage:"Please share your question and I can help with ArcGIS and Portal documentation."};let n=e?.configurable?.context;jr(n);let o=uA(t.agentExecutionContext.sharedState),{reply:s,conversationId:a}=await dA({portal:n.portal,question:r,previousConversationId:o.conversationId||void 0,skillId:"doc_ai_assistant",persona:"developers"});return{status:"success",outputMessage:s.trim()||"I could not retrieve a response from the documentation assistant.",sharedStatePatch:cA({conversationId:a||o.conversationId})}},bm=j(async({groupTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;jr(n);try{return(await iu(n.portal,{query:`title:${r}`,num:1}))?.results[0]?.id||null}catch(o){return console.error("Error searching for portal group by title:",o),null}},{name:"resolvePortalGroupIdByTitle",description:"Resolves an ArcGIS Portal group title to the best-match group id. Use this when a user references a group by title instead of an explicit group id.",schema:m.object({groupTitle:m.string().describe("The portal group title to resolve to a group id.")})}),xm=j(async({itemTitle:t},e)=>{let r=t.trim();if(!r)return null;let n=e?.configurable?.context;jr(n);let{result:o,error:s}=await cu(n.portal,r,{num:1});return s&&console.error("Error searching for portal item by title:",s),o?.results[0]?.id||null},{name:"resolvePortalItemIdByTitle",description:'Resolves an ArcGIS Portal item title to the best-match item id. Use this when a user references an item by title (including hash mentions like #title or #"title with spaces") instead of an explicit item id.',schema:m.object({itemTitle:m.string().describe("The portal item title to resolve to an item id.")})}),hm=m.object({shouldSuggestNavigation:m.boolean().default(!1),destinationType:m.enum(["none","portal-content","portal-item","portal-groups","portal-group"]).default("none"),itemId:m.string().default(""),groupId:m.string().default("")}),hA=async(t,e)=>{await Ae({text:"Extracting navigation intent...",agentName:"doc-assistant"},e);let r=t.outputMessage.trim();if(!r)return{};let n=Lr(t.agentExecutionContext.messages).trim(),o=await Gr.fromTemplate(yA).format({question:n,response:r}),s=await Jr({model:await Ba({modelTier:"default"}),tools:[xm,bm],systemPrompt:o,responseFormat:hm,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),a=hm.parse(s.structuredResponse??{});if(!a.shouldSuggestNavigation||a.destinationType==="none")return{};let i=gA(a);return i?(await vl(i,e),{}):{}};function gA({destinationType:t,itemId:e,groupId:r}){switch(t){case"portal-content":return{destinationType:"portal-content"};case"portal-groups":return{destinationType:"portal-groups"};case"portal-item":return e?{destinationType:"portal-item",itemId:e}:null;case"portal-group":return r?{destinationType:"portal-group",groupId:r}:null;case"none":return null;default:return To(t)}}var yA=`
439
+ You decide whether the assistant response should include a navigation action to ArcGIS Portal.
440
+
441
+ Given the user question and assistant response:
442
+ - Decide if a navigation action would help the user complete the task.
443
+ - If yes, choose one destination type:
444
+ - portal-content: portal content page
445
+ - portal-groups: groups listing page
446
+ - portal-item: specific item page (requires itemId)
447
+ - portal-group: specific group page (requires groupId)
448
+
449
+ Rules:
450
+ - If no navigation is useful, set shouldSuggestNavigation=false and destinationType=none.
451
+ - If destinationType is portal-item and user references an item by title (for example #title, #"title with spaces", or plain quoted title), call resolvePortalItemIdByTitle and set itemId from the tool result.
452
+ - If destinationType is portal-group and user references a group by title (for example $title, $"title with spaces", or plain quoted group title), call resolvePortalGroupIdByTitle and set groupId from the tool result.
453
+ - Do not invent itemId.
454
+ - Do not invent groupId.
455
+ - Prefer destinationType=portal-content for generic "go to content" guidance.
456
+
457
+ User question:
458
+ {question}
459
+
460
+ Assistant response:
461
+ {response}
462
+ `,Am=M.Root({..._s()}),_A=()=>new _e(Am).addNode("answerDocQuestion",fA).addNode("extractNavigationIntent",hA).addEdge(ge,"answerDocQuestion").addEdge("answerDocQuestion","extractNavigationIntent").addEdge("extractNavigationIntent",L),wA=String.raw`- **portal-doc-assistant** - General ArcGIS documentation and Portal help assistant:
463
+ - answers general ArcGIS, Portal, Enterprise, and JavaScript SDK questions
464
+ - acts as a fallback when specialized agents are not applicable
465
+ `,bA={id:"portal-doc-assistant",name:"Portal Doc Assistant",description:wA,createGraph:_A,workspace:Am},Im=`
466
+ Shared markdown formatting rules:
467
+ - Use clear markdown headings (##) to separate sections.
468
+ - Use concise bullet points for lists of facts, counts, or signals.
469
+ - Emphasize key metrics with bold labels (for example: **Recent items:** 4).
470
+ - Keep wording direct and analytical; avoid filler language but make sure the language is friendly.
471
+ - Do not include raw internal IDs unless explicitly requested.
472
+ `,xA=()=>({latestGroupId:null,memory:{}}),Ka=t=>{let e=t?.agentExecutionContext.sharedState.portalGroupSummaryMemory?.value;return e?{latestGroupId:e.latestGroupId,memory:e.memory}:xA()},AA=async(t,e)=>{await Ae({text:"Answering group follow-up...",agentName:"group-analytics"},e);let r=Ka(t),n=t.groupSummaryGroupId??r.latestGroupId,o=n?r.memory[n]:void 0,s=t.groupSummaryQuestion||Lr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await It({promptText:vA,schema:IA,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I do not have group analytics context yet. Ask me to analyze a group first with analyze group <group id>."}},IA=m.object({answer:m.string(),isRelevant:m.boolean()}),vA=`
473
+ You answer follow-up questions about ArcGIS group analytics.
474
+
475
+ ${Im}
476
+
477
+ Ground your answer in the provided group analytics summary and context.
478
+ If the answer is not available from the provided context, state that clearly and suggest what to check next.
479
+
480
+ Response rules:
481
+ - Reply in concise markdown with this section structure:
482
+ 1) ## Answer
483
+ 2) ## Evidence
484
+ 3) ## Gaps (only when data is missing)
485
+ - Keep the answer focused on the follow-up question.
486
+ - Do not include internal identifiers.
487
+ - Mark isRelevant=false when the question is not about this group or cannot be grounded in this group context.
488
+
489
+ Group analytics summary:
490
+ {summary}
491
+
492
+ Group full context:
493
+ {fullContext}
494
+
495
+ Question:
496
+ {question}
497
+ `,TA=async(t,e)=>{await Ae({text:"Analyzing group-analytics intent...",agentName:"group-analytics"},e);let r=Lr(t.agentExecutionContext.messages),n=!!Ka(t).latestGroupId,o=await Gr.fromTemplate(kA).format({userMessage:r,hasAnalyticsContext:String(n)}),s=await Jr({model:await Ba({modelTier:"fast"}),tools:[bm],systemPrompt:o,responseFormat:SA,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,groupId:i,question:u}=s.structuredResponse,l=a==="summarize"&&!i,c=a==="followUp"&&!(u??"").trim(),p=a==="clarify"||l||c;return{groupSummaryIntent:p?"clarify":a,groupSummaryGroupId:i||null,groupSummaryQuestion:u||"",status:"success",outputMessage:p?"Please clarify with a group id or title":""}},SA=m.object({intent:m.enum(["summarize","followUp","navigation","clarify"]),groupId:m.string().default(""),question:m.string().default("")}),kA=`
498
+ Classify the user's request for ArcGIS Portal group analytics.
499
+
500
+ Rules:
501
+ - intent="summarize" only when the user explicitly asks to summarize, analyze, overview, or recap a group.
502
+ - intent="followUp" for follow-up questions about a previously analyzed group.
503
+ - intent="navigation" when the user asks to open, go to, navigate to, or view the group page.
504
+ - intent="clarify" when intent or required group target is missing.
505
+ - groupId must be the final resolved group id.
506
+ - If request has explicit group id, set groupId directly.
507
+ - If request references group title (for example $title, $"title with spaces", or plain quoted group title), call resolvePortalGroupIdByTitle and set groupId to the tool result.
508
+ - Never return group titles in output fields.
509
+ - If intent is "followUp", set question to the user's full question/request text.
510
+ - If intent is "navigation", set question="".
511
+ - If intent is "summarize", set question="".
512
+ - If intent is "navigation" and no group is specified, leave groupId empty so the system can navigate to the groups listing page.
513
+ - If hasAnalyticsContext is true and the user asks about the same group context without an explicit summarize/analyze command, prefer "followUp".
514
+
515
+ Examples:
516
+ - "Analyze group 0123456789abcdef0123456789abcdef" => summarize, groupId="0123456789abcdef0123456789abcdef"
517
+ - "Analyze group $living atlas" => summarize, call resolvePortalGroupIdByTitle("living atlas") and set groupId to tool result
518
+ - "Analyze group $"living atlas basemaps"" => summarize, call resolvePortalGroupIdByTitle("living atlas basemaps") and set groupId to tool result
519
+ - "Is this group active?" with hasAnalyticsContext=true => followUp
520
+
521
+ hasAnalyticsContext:
522
+ {hasAnalyticsContext}
523
+
524
+ User message:
525
+ {userMessage}
526
+ `,CA=async(t,e)=>{let r=Ka(t),n=t.groupSummaryGroupId??r.latestGroupId;return await Ae({text:"Preparing navigation...",agentName:"group-analytics"},e),await vl(n?{destinationType:"portal-group",groupId:n}:{destinationType:"portal-groups"},e),{status:"success"}};function vm({timestamp:t,now:e,windowMs:r}){return t?e-t<=r:!1}var EA=720*60*60*1e3;function PA(t){let e=pu(t);return{id:t.id??"",title:t.title??"",description:t.description??"",snippet:t.snippet??"",access:t.access??null,owner:t.owner??"",tags:t.tags??[],created:t.created?.getTime(),modified:t.modified?.getTime(),isInvitationOnly:t.isInvitationOnly,sourceSignals:{capabilities:mu(t),membershipAccess:fu(t),isOpenData:hu(t),isDistributedCollaborationGroup:gu(t),orgId:e.orgId,hiddenMembers:e.hiddenMembers,isViewOnly:e.isViewOnly,isReadOnly:e.isReadOnly,leavingDisallowed:e.leavingDisallowed}}}async function OA(t){let e={owner:t.owner??"",admins:[],users:[]};try{return await t.fetchMembers()}catch(r){return console.warn("Unable to fetch group members for analytics context",r),e}}function MA(t){return t.map(e=>({id:e.id??"",title:e.title??"Untitled",type:e.type??"Unknown",owner:e.owner??"",created:e.created?.getTime(),modified:e.modified?.getTime()}))}function RA(t,e){return t.filter(r=>r.modified?vm({timestamp:r.modified,now:e,windowMs:EA}):!1)}function $A(t){let e=new Map;for(let r of t)e.set(r.type,(e.get(r.type)??0)+1);return[...e.entries()].sort((r,n)=>n[1]-r[1]||r[0].localeCompare(n[0])).slice(0,6).map(([r,n])=>({type:r,count:n}))}async function NA(t){let e=await t.queryItems({num:20,sortField:"modified",sortOrder:"desc"}),r=MA(e.results),n=Date.now();return{total:e.total,topItems:r,recentlyModifiedItems:RA(r,n),topItemTypes:$A(r)}}async function zA(t,e){if(!e)return{error:{code:"missingGroupId",message:"Group id is required."}};try{let r=(await t.queryGroups({query:`id:${e}`,num:1})).results[0];if(!r)return{error:{code:"groupNotFound",message:`No group found for id: ${e}`}};let n=PA(r),o=await OA(r),s=await NA(r);return{result:{group:n,members:o,items:s}}}catch(r){return console.error("Error fetching portal group analytics context:",r),{error:{code:"unhandledError"}}}}var jA=2160*60*60*1e3,LA=async(t,e)=>{let r=t.groupSummaryGroupId;if(!r)return{status:"success",outputMessage:'Please clarify with analyze group <group id>, analyze group $<title>, or analyze group $"<title with spaces>".'};await Ae({text:`Analyzing group ${r}...`,agentName:"group-analytics"},e);let n=e?.configurable?.context;jr(n);let{result:o,error:s}=await zA(n.portal,r);if(s||!o)return await Ae({text:"Failed to fetch group context",agentName:"group-analytics"},e),{status:"success",outputMessage:"Unable to retrieve group context for analytics."};let{group:a,items:i}=o,u=Date.now(),l=a.modified,c=l?vm({timestamp:l,now:u,windowMs:jA}):!1,p=i.recentlyModifiedItems.length,d=p>0,g=c||d,y=await It({promptText:FA,schema:DA,modelTier:"default",inputVariables:{context:JSON.stringify(o),deterministicSignals:JSON.stringify({isGroupActive:g,isGroupRecentlyModified:c,hasRecentlyAddedOrUpdatedContent:d,recentItemCount:p})}}),{followUpQuestions:w,summary:_}=y,f=Ka(t),A={latestGroupId:r,memory:{...f.memory,[r]:{summary:_,followUpQuestions:w,fullContext:o}}};return w.length&&await qa({type:"suggested-prompts",data:{prompts:w}},e),{status:"success",outputMessage:_,sharedStatePatch:{portalGroupSummaryMemory:{value:A}}}},DA=m.object({summary:m.string(),followUpQuestions:m.array(m.string()).default([])}),FA=`
527
+ You summarize ArcGIS Portal groups based on structured context and deterministic activity signals.
528
+
529
+ ${Im}
530
+
531
+ Output format requirements:
532
+ - Return concise markdown with clear sections in this order:
533
+ 1) Overview
534
+ 2) Activity
535
+ 3) Members
536
+ 4) Content Theme
537
+ 5) Contribution Model
538
+ 6) Unknowns / Data Gaps
539
+ - Keep total response about 180-280 words unless the user asked for extra detail.
540
+ - Avoid internal-only implementation details and do not expose raw IDs unless user explicitly asks.
541
+
542
+ Reasoning rules:
543
+ - Use deterministicSignals as the source of truth for active/recent status.
544
+ - If group description/snippet are empty, infer purpose from tags, item title patterns, and item type distribution.
545
+ - For members, report owner/admin/user counts when available; if unavailable due to permission scope, explicitly say so.
546
+ - For contribution model, use membershipAccess, capabilities, and sourceJSON flags to characterize collaboration vs distribution behavior.
547
+ - Be explicit when signals are heuristic or unavailable.
548
+
549
+ Follow-up prompt rules:
550
+ - Generate exactly 3 follow-up prompts.
551
+ - Write them as direct first-person user chat prompts that can be clicked and sent as-is.
552
+ - Do not write meta-questions such as "Would you like..." or "Do you want me to...".
553
+ - Keep each prompt short, specific, and actionable.
554
+ - Every prompt must be answerable using only the provided group context and deterministic signals.
555
+ - Do not require external data, navigation, or additional fetches.
556
+ - Tailor each prompt to this specific group's available signals (content mix, activity, members, and contribution model).
557
+ - Avoid repeating phrasing from prior prompts or using generic template wording.
558
+ - If a signal is unavailable (for example members), do not ask follow-ups that depend on that missing signal.
559
+
560
+ Group context:
561
+ {context}
562
+
563
+ Deterministic signals:
564
+ {deterministicSignals}
565
+ `,xl=(t,e)=>e??t,Tm=M.Root({..._s(),groupSummaryIntent:M({reducer:xl,default:()=>"clarify"}),groupSummaryGroupId:M({reducer:xl,default:()=>null}),groupSummaryQuestion:M({reducer:xl,default:()=>""})}),UA=()=>new _e(Tm).addNode("detectGroupSummaryIntent",TA).addNode("summarizePortalGroup",LA).addNode("answerGroupSummaryFollowUp",AA).addNode("suggestGroupSummaryNavigation",CA).addEdge(ge,"detectGroupSummaryIntent").addConditionalEdges("detectGroupSummaryIntent",t=>t.groupSummaryIntent==="summarize"?"summarizePortalGroup":t.groupSummaryIntent==="followUp"?"answerGroupSummaryFollowUp":t.groupSummaryIntent==="navigation"?"suggestGroupSummaryNavigation":L).addEdge("summarizePortalGroup",L).addEdge("answerGroupSummaryFollowUp",L).addEdge("suggestGroupSummaryNavigation",L),qA=String.raw`- **portal-group-analytics** - Portal group analytics assistant:
566
+ - summarizes ArcGIS portal groups from group context and sourceJSON details
567
+ - answers follow-up questions grounded in the summarized group
568
+ - suggests navigation to groups when relevant
569
+ `,BA={id:"portal-group-analytics",name:"Portal Group Analytics",description:qA,createGraph:UA,workspace:Tm},KA=()=>({latestItemId:null,memory:{}}),Tl=t=>{let e=t?.agentExecutionContext.sharedState.portalItemAnalyticsSummaryMemory?.value;return e?{latestItemId:e.latestItemId,memory:e.memory}:KA()},GA=m.object({intent:m.enum(["summarize","followUp","clarify"]),itemId:m.string().default(""),question:m.string().default("")}),WA=m.object({summary:m.string(),followUpQuestions:m.array(m.string()).default([])}),VA=m.object({answer:m.string(),isRelevant:m.boolean()}),HA=async(t,e)=>{await Ae({text:"Answering follow-up...",agentName:"analytics"},e);let r=Tl(t),n=t.analyticsItemId??r.latestItemId,o=n?r.memory[n]:void 0,s=t.analyticsQuestion||Lr(t.agentExecutionContext.messages);return o?{status:"success",outputMessage:(await It({promptText:JA,schema:VA,modelTier:"default",inputVariables:{summary:o.summary,question:s,fullContext:JSON.stringify(o.fullContext)}})).answer}:{status:"success",outputMessage:"I don't have enough information yet. Please ask me to summarize the item first using summarize item <item id>."}},JA=`
570
+ You answer follow-up questions about an ArcGIS item.
571
+
572
+ Ground your answer in the provided item context.
573
+ If the answer is not available from the provided context, state that clearly and suggest what to check next.
574
+
575
+ Response rules:
576
+ - Reply in concise markdown.
577
+ - Keep the answer focused on the follow-up question.
578
+ - Do not include internal identifiers.
579
+ - Mark isRelevant=false when the question is not about this item or cannot be grounded in this item context.
580
+
581
+ Item summary:
582
+ {summary}
583
+
584
+ Item full context
585
+ {fullContext}
586
+
587
+ Question:
588
+ {question}
589
+ `,ZA=async(t,e)=>{await Ae({text:"Analyzing intent...",agentName:"analytics"},e);let r=Lr(t.agentExecutionContext.messages),n=!!Tl(t).latestItemId,o=await Gr.fromTemplate(QA).format({userMessage:r,hasSummaryContext:String(n)}),s=await Jr({model:await Ba({modelTier:"fast"}),tools:[xm],systemPrompt:o,responseFormat:GA,checkpointer:!0}).invoke({messages:t.agentExecutionContext.messages},e),{intent:a,itemId:i,question:u}=s.structuredResponse,l=a==="clarify"||a==="summarize"&&!i||a==="followUp"&&!u;return{agentExecutionContext:{...t.agentExecutionContext},analyticsIntent:l?"clarify":a,analyticsItemId:i||null,analyticsQuestion:u||"",status:"success",outputMessage:l?'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".':""}},QA=`
590
+ Classify the user analytics request.
591
+
592
+ Rules:
593
+ - intent="summarize" only when the user explicitly asks to summarize/overview/recap an item.
594
+ - intent="followUp" for analytical questions about item details, including schema/fields/attributes/layers.
595
+ - intent="clarify" when neither summarize nor follow-up intent is clear.
596
+ - itemId must be the final resolved item id.
597
+ - If request has explicit item id, set itemId directly.
598
+ - If request references item title (for example #title, #"title with spaces", or plain quoted title), call resolvePortalItemIdByTitle and set itemId to the returned value.
599
+ - Never return item titles in output fields.
600
+ - If intent is "followUp", set question to the user's full question/request text.
601
+ - If intent is "summarize", set question="".
602
+ - When user asks to show/list/explain fields, schema, attributes, columns, or layer details, classify as "followUp" unless they explicitly request a summary.
603
+ - If hasSummaryContext is true, prefer "followUp" for detail-oriented requests that do not explicitly ask to summarize.
604
+
605
+ Examples:
606
+ - "Summarize item 0123456789abcdef0123456789abcdef" => summarize, itemId="0123456789abcdef0123456789abcdef"
607
+ - "Summarize item #california" => summarize, call resolvePortalItemIdByTitle("california") and set itemId to tool result
608
+ - "Summarize item #"california farmland"" => summarize, call resolvePortalItemIdByTitle("california farmland") and set itemId to tool result
609
+ - "Show the layer's available fields" => followUp
610
+ - "List attributes and explain what status means" => followUp
611
+ - "What fields are available?" with hasSummaryContext=true => followUp
612
+ - "Give me an overview of item 0123456789abcdef0123456789abcdef" => summarize
613
+
614
+ hasSummaryContext:
615
+ {hasSummaryContext}
616
+
617
+ User message:
618
+ {userMessage}
619
+ `,YA=async(t,e)=>{let r=t.analyticsItemId;if(!r)return{status:"success",outputMessage:'Please clarify with summarize item <item id>, summarize item #<title>, or summarize item #"<title with spaces>".'};await Ae({text:`Summarizing item ${r}...`,agentName:"analytics"},e);let n=e?.configurable?.context;jr(n);let{portal:o,user:s}=n,{result:a,error:i}=await du(s,o,r);if(i||!a)return await Ae({text:"Failed to get item context for summarization",agentName:"analytics"},e),{status:"success",outputMessage:"Unable to retrieve item context for summarization."};let{context:u}=a,l=await It({promptText:XA,schema:WA,modelTier:"default",inputVariables:{context:JSON.stringify(u)}}),{followUpQuestions:c,summary:p}=l,d=Tl(t),g={latestItemId:r,memory:{...d.memory,[r]:{summary:p,followUpQuestions:c,fullContext:u}}};return c.length&&await qa({type:"suggested-prompts",data:{prompts:c}},e),{status:"success",outputMessage:p,sharedStatePatch:{portalItemAnalyticsSummaryMemory:{value:g}}}},XA=`
620
+ You are a item summary tool for ArcGIS. Your job is to summarize an item's info based on the provided context.
621
+ Summary rules:
622
+ - The summary should be concise markdown, make sure to format the output nicely so it's easy to read.
623
+ - Target length: 80-150 words.
624
+ - Provide one short descriptive paragraph.
625
+ - Also propose 3 concise follow-up questions grounded in the item summary.
626
+ - Keep follow-up questions specific and actionable.
627
+ Follow-up questions rules:
628
+ - These questions should be in the format of a prompt that the user can click on.
629
+ - Make sure the questions are relevant to the item summary and that you can answer based solely on the provided context.
630
+ Do not include internal identifiers.
631
+ If the user asks for a detailed summary, you may expand the response up to 300 words.
632
+ Item context:
633
+ {context}
634
+ `,Al=(t,e)=>e??t,Sm=M.Root({..._s(),analyticsIntent:M({reducer:Al,default:()=>"clarify"}),analyticsItemId:M({reducer:Al,default:()=>null}),analyticsQuestion:M({reducer:Al,default:()=>""})}),eI=()=>new _e(Sm).addNode("detectAnalyticsIntent",ZA).addNode("summarizePortalItem",YA).addNode("answerAnalyticsFollowUp",HA).addEdge(ge,"detectAnalyticsIntent").addConditionalEdges("detectAnalyticsIntent",t=>t.analyticsIntent==="summarize"?"summarizePortalItem":t.analyticsIntent==="followUp"?"answerAnalyticsFollowUp":L).addEdge("summarizePortalItem",L).addEdge("answerAnalyticsFollowUp",L),tI=String.raw`- **portal-item-analytics** - Portal item analytics assistant:
635
+ - summarizes ArcGIS portal items from item context
636
+ - suggests follow-up prompts grounded in the item
637
+ `,rI={id:"portal-item-analytics",name:"Portal Item Analytics",description:tI,createGraph:eI,workspace:Sm},nI=Sl`:host{height:100%;border-width:1px;border-style:solid;border-color:var(--calcite-color-border-3);display:block;width:100%;--tw-shadow: 0 1px 6px -1px rgba(0, 0, 0, .16), 0 1px 2px -1px rgba(0, 0, 0, .08);--tw-shadow-colored: 0 1px 6px -1px var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.chat-entry{display:flex;flex-direction:column;gap:.75rem;width:100%}.chat-actions{display:flex;justify-content:flex-end;gap:.5rem}.header-actions{display:flex;gap:.5rem;padding-inline-start:.75rem}.navigation-block{display:flex;flex-direction:column;align-items:stretch;gap:.35rem;margin-top:.5rem}.navigation-button{width:100%;margin-block:.25rem}.navigation-block-description{font-size:.75rem;color:var(--calcite-color-text-3)}`;function oI(t,e){if(!e)return;let{destinationType:r}=t;switch(r){case"portal-content":case"portal-groups":return e[r];case"portal-item":return e[r]?.(t.itemId);case"portal-group":return e[r]?.(t.groupId);default:return To(r)}}function sI(t){let e=nA.safeParse(t);return e.success?e.data:void 0}var Il=class extends Pl{constructor(){super(...arguments),this.t9n=Ml({blocking:!0}),this.assistantEl=Io(),this.formEl=Io(),this.voiceInputEl=Io(),this.inputEl=Io(),this.navigationSlotElements=new Map,this.handleSlottableRequest=e=>{let r=e.detail,n=r.data?.block;if(!n)return;let o=this.getNavigationAction(n);o&&this.upsertNavigationSlotElement(r.slotName,o)},this.inputText="",this.showVoiceInput=!0,this.isListening=!1,this.isVoiceInputDisabled=!1,this.interrupt=null,this.autoDestroyDisabled=!1,this.defaultClosed=!1,this.arcgisPortalNavigationRequest=Cl()}static{this.properties={inputText:16,showVoiceInput:16,isListening:16,isVoiceInputDisabled:16,interrupt:16,autoDestroyDisabled:5,portal:0,user:0,config:0,navigationTargetMap:0,defaultClosed:5}}static{this.styles=nI}getNavigationAction(e){if(e?.type!==ym)return;let r=sI(e.data);if(!r)return;let n=oI(r,this.navigationTargetMap);if(n)return{href:n,targetDetail:r,label:this.getNavigationText(r.destinationType)}}upsertNavigationSlotElement(e,r){let n=this.assistantEl.value;if(!n)return;let o=this.navigationSlotElements.get(e);o||(o=document.createElement("div"),o.slot=e,this.navigationSlotElements.set(e,o),n.append(o)),kl(Dr`<div><calcite-button class="navigation-button" appearance=outline width=full .href=${r.href} icon-end=launch @click=${s=>{s.preventDefault(),this.arcgisPortalNavigationRequest.emit({href:r.href,targetDetail:r.targetDetail})}}>${r.label}</calcite-button>${r.description?Dr`<div class="navigation-block-description">${r.description}</div>`:null}</div>`,o)}getNavigationText(e){let r=this.t9n.navigation;switch(e){case"portal-content":return r.openContent;case"portal-groups":return r.openGroups;case"portal-item":return r.openItem;case"portal-group":return r.openGroup;default:return To(e)}}render(){let{t9n:e,inputText:r,portal:n,user:o,navigationTargetMap:s,showVoiceInput:a,isListening:i,isVoiceInputDisabled:u}=this;return Dr`<arcgis-assistant log-enabled keep-suggested-prompts .heading=${e.heading} .entryMessage=${e.entryMessage} @arcgisSlottableRequest=${this.handleSlottableRequest} @arcgisInterrupt=${({detail:l})=>{this.interrupt=l}} @arcgisInterruptCancel=${()=>{this.interrupt=null}} @arcgisInterruptSubmit=${()=>{this.interrupt=null}} @arcgisPromptSelect=${({detail:l})=>{this.inputText=l.prompt,requestAnimationFrame(()=>{this.inputEl.value?.focusTextArea()})}} ${vo(this.assistantEl)}><div slot=header-actions-start class="header-actions"><calcite-icon icon=effects></calcite-icon></div><form slot=chat-entry class="chat-entry" @submit=${l=>{l.preventDefault();let c=r.trim();c&&(this.assistantEl.value?.submitMessage(c),this.inputText="")}} ${vo(this.formEl)}><arcgis-portal-mentionable-text-area .portal=${n} .user=${o} rows=3 .popoverListLabel=${e.mentionEntities} .placeholder=${e.placeholder} .value=${r} @arcgisUserMentionableTextAreaKeyDown=${({detail:l})=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),this.formEl.value?.requestSubmit())}} @arcgisUserMentionableTextAreaChange=${({detail:l})=>{this.inputText=l??""}} ${vo(this.inputEl)}></arcgis-portal-mentionable-text-area><div class="chat-actions"><arcgis-portal-voice-input @arcgisVoiceInputStart=${()=>{this.isListening=!0,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputStop=${()=>{this.isListening=!1,this.isVoiceInputDisabled=!1}} @arcgisVoiceInputError=${l=>{l.detail.errorCode==="not-supported"&&(this.showVoiceInput=!1)}} @arcgisVoiceInputInterimTranscription=${l=>{this.inputText=l.detail.text}} ${vo(this.voiceInputEl)}></arcgis-portal-voice-input>${a&&Dr`<calcite-button icon-start=microphone .label=${e.voiceInput} round .disabled=${u} .appearance=${i?"solid":"outline-fill"} @click=${async()=>{this.isVoiceInputDisabled=!0;let l=this.voiceInputEl.value;i?await l?.stopListening():await l?.startListening()}}></calcite-button>`||""}<calcite-button type=submit icon-start=send round .disabled=${!r.trim()} .label=${e.send}>${e.send}</calcite-button></div></form><arcgis-assistant-agent .agent=${rI} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${iA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${bA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent><arcgis-assistant-agent .agent=${BA} .context=${{portal:n,user:o,navigationTargetMap:s}}></arcgis-assistant-agent>${this.interrupt&&Dr`<arcgis-portal-ai-assistant-interrupt slot=interrupt .type=${this.interrupt.type} .message=${this.interrupt.message} .options=${this.interrupt.options} @arcgisSubmit=${({detail:l})=>{this.assistantEl.value?.submitInterrupt(l)}} @arcgisCancel=${()=>{this.assistantEl.value?.cancelInterrupt()}}></arcgis-portal-ai-assistant-interrupt>`||""}</arcgis-assistant>`}};Ol("arcgis-portal-ai-assistant",Il);return Il},"identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","applications/KnowledgeStudio/generalSharedKgUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","request",a)