@esri/solutions-components 5.1.2 → 5.1.3
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.
- package/dist/cdn/{7EJXZVSX.js → 2CCKYJSY.js} +1 -1
- package/dist/cdn/{3KYCZII7.js → 2DCSGUOX.js} +1 -1
- package/dist/cdn/{LSMP2ZCO.js → 2EUQOQY3.js} +1 -1
- package/dist/cdn/{FSFVH74N.js → 2GHTA5PV.js} +1 -1
- package/dist/cdn/{3DNEBMT3.js → 2GJEHDZJ.js} +1 -1
- package/dist/cdn/{LRGW6G5E.js → 2XTZLJ5F.js} +1 -1
- package/dist/cdn/{CKPQTIAF.js → 37CMWBMW.js} +1 -1
- package/dist/cdn/{SD3DV4KO.js → 37XAYW3Z.js} +1 -1
- package/dist/cdn/{LQFA6HOT.js → 3DFMPPUD.js} +1 -1
- package/dist/cdn/{LXJI7FYN.js → 3MN7XFQ2.js} +1 -1
- package/dist/cdn/{EHIUCEAX.js → 3N2AUH5S.js} +1 -1
- package/dist/cdn/{OPWMEQVM.js → 3TO6KC3G.js} +2 -2
- package/dist/cdn/{OVAQRVFG.js → 3XOKCST3.js} +1 -1
- package/dist/cdn/{GZZMHIFA.js → 43MZA66W.js} +1 -1
- package/dist/cdn/{T7O4WZGU.js → 45JNINYV.js} +1 -1
- package/dist/cdn/{RQVXDCWL.js → 4PDKVX4T.js} +1 -1
- package/dist/cdn/{DEVAXAP7.js → 56PIVLPU.js} +1 -1
- package/dist/cdn/{ZB5UCRCG.js → 5BJO5ABV.js} +1 -1
- package/dist/cdn/{QVD3AXIP.js → 5EYRW6FE.js} +1 -1
- package/dist/cdn/{L6XSVTY3.js → 5L7HZJBG.js} +1 -1
- package/dist/cdn/{4RH7N22O.js → 5LM5R34X.js} +1 -1
- package/dist/cdn/{JF2ASXUT.js → 6AVCTQ6J.js} +1 -1
- package/dist/cdn/{PSM4UX7K.js → 6AWTIASQ.js} +1 -1
- package/dist/cdn/{NIUKLQOT.js → 6FPVZV4K.js} +1 -1
- package/dist/cdn/{WVCL5OUK.js → 6SHN7V3N.js} +1 -1
- package/dist/cdn/{IVMHEGLY.js → 6UVMG6O6.js} +1 -1
- package/dist/cdn/{RPL5Q7IL.js → 7IKNLW73.js} +1 -1
- package/dist/cdn/{5IO4VX4R.js → AHC3CH4P.js} +1 -1
- package/dist/cdn/{74Z5A6E2.js → AKXVDLK3.js} +1 -1
- package/dist/cdn/AO7XKW2U.js +4 -0
- package/dist/cdn/{BZWJ3KFS.js → ATEM3GJU.js} +104 -104
- package/dist/cdn/{3NI2BJYO.js → AULN2QXN.js} +1 -1
- package/dist/cdn/{GRVDJVOF.js → AX2U2PGS.js} +1 -1
- package/dist/cdn/{YBJ6AHAG.js → B57TWGXS.js} +1 -1
- package/dist/cdn/{EX4K4RKP.js → B7YYMYZB.js} +1 -1
- package/dist/cdn/{SQEPSAKG.js → BACWGZE4.js} +1 -1
- package/dist/cdn/{BWNEUQZZ.js → BDAY2SRY.js} +1 -1
- package/dist/cdn/{O6IGMQN7.js → BOQUQFNT.js} +1 -1
- package/dist/cdn/{LKVPVQIC.js → BTOTDVAS.js} +1 -1
- package/dist/cdn/{6L6JOGWD.js → BWFET22E.js} +1 -1
- package/dist/cdn/{DXI5HEQM.js → C7YLT2V6.js} +1 -1
- package/dist/cdn/{V24CDHGH.js → CAXEJ55N.js} +1 -1
- package/dist/cdn/{LCDURBN6.js → CYKO5XJY.js} +1 -1
- package/dist/cdn/{HOSSEVH5.js → DDUV67TU.js} +1 -1
- package/dist/cdn/{UDWEFNJE.js → DRZ2MEHM.js} +1 -1
- package/dist/cdn/DTTQLI5W.js +2 -0
- package/dist/cdn/{5FW45CM6.js → EJK7PYN5.js} +1 -1
- package/dist/cdn/{C2GWD5VP.js → ENJC4SNG.js} +1 -1
- package/dist/cdn/{WNYAZ4ME.js → ESH7SFXX.js} +1 -1
- package/dist/cdn/{B7CVHLVL.js → F46RK2J3.js} +1 -1
- package/dist/cdn/{MZ5XI2CY.js → F6H43GFC.js} +1 -1
- package/dist/cdn/{ECUD4NU6.js → FAHLQLKD.js} +1 -1
- package/dist/cdn/{QMQAQSIA.js → FKQHOE2A.js} +1 -1
- package/dist/cdn/{7AHZBLTM.js → FL4YRGDB.js} +1 -1
- package/dist/cdn/{KPEPW4QL.js → FPBZRT3J.js} +1 -1
- package/dist/cdn/{UILBHLN7.js → FWRNU7AK.js} +1 -1
- package/dist/cdn/{BFFHQBDI.js → G63VTGNV.js} +1 -1
- package/dist/cdn/{QODVIACF.js → GCDVJH5S.js} +1 -1
- package/dist/cdn/{EBDDUQNC.js → GCLCH6NX.js} +1 -1
- package/dist/cdn/{MVXK7UGO.js → GLD7SDA5.js} +1 -1
- package/dist/cdn/{KB7CXY4N.js → GVREVCUB.js} +1 -1
- package/dist/cdn/{ZHVO477V.js → HCY3VGST.js} +1 -1
- package/dist/cdn/{65I4AUS4.js → HKURBCD6.js} +1 -1
- package/dist/cdn/{XA6ZDTKA.js → HSZJX2Q4.js} +1 -1
- package/dist/cdn/{GSLDFLWZ.js → HXCNKN3S.js} +1 -1
- package/dist/cdn/{JB5XLSNA.js → IK3L2OC3.js} +1 -1
- package/dist/cdn/{O6HS2AMH.js → IKA3ESQ5.js} +1 -1
- package/dist/cdn/{Y7Z6LFBH.js → IXSDSBUI.js} +1 -1
- package/dist/cdn/{XXRBPKMI.js → J5Q7IGCO.js} +1 -1
- package/dist/cdn/{KMY4AVEA.js → J6PFJWXU.js} +1 -1
- package/dist/cdn/{QTCXH2O3.js → JBBUAR3W.js} +1 -1
- package/dist/cdn/{3CSSTWYC.js → JCPQ7OOS.js} +1 -1
- package/dist/cdn/{BSIPKI63.js → JNQB7T54.js} +1 -1
- package/dist/cdn/{J7DTCWOP.js → JX7BWUKD.js} +1 -1
- package/dist/cdn/{CC7JGR5Q.js → KGL266WS.js} +1 -1
- package/dist/cdn/{MXPZF4RB.js → KGXEY5HR.js} +1 -1
- package/dist/cdn/{EJRV6YWD.js → KN5XFC7O.js} +1 -1
- package/dist/cdn/{FDNEF4QD.js → KU2QSXAD.js} +1 -1
- package/dist/cdn/{65OXHGCN.js → KX4F4INQ.js} +1 -1
- package/dist/cdn/{7XPOQHB4.js → KZBPVSUW.js} +1 -1
- package/dist/cdn/{VSRNGZ43.js → LABCYKSC.js} +1 -1
- package/dist/cdn/{WRMREY3V.js → LI3GKZ35.js} +1 -1
- package/dist/cdn/{7NQYBMRX.js → MIKSQTTI.js} +1 -1
- package/dist/cdn/{CVKCFLNY.js → MOHSZVTU.js} +1 -1
- package/dist/cdn/{LFIP5DV3.js → MWTTZLRQ.js} +1 -1
- package/dist/cdn/{GHVPHEOH.js → MXNYBLUV.js} +1 -1
- package/dist/cdn/{AS7PVOU3.js → MZ63UWGX.js} +1 -1
- package/dist/cdn/N4MCHYQT.js +2 -0
- package/dist/cdn/{MVSQRD5M.js → NAZXHTIH.js} +1 -1
- package/dist/cdn/{GSI62QHB.js → NBWMZOGE.js} +1 -1
- package/dist/cdn/{NJSQ3NUT.js → NGAS7OCN.js} +1 -1
- package/dist/cdn/{6RQBPR56.js → O7LSXSBD.js} +1 -1
- package/dist/cdn/{DF2U7HIU.js → OLN76PG4.js} +1 -1
- package/dist/cdn/PIRHBQVO.js +351 -0
- package/dist/cdn/{LSDYUCCZ.js → PLELSLAV.js} +1 -1
- package/dist/cdn/{6KBY56R4.js → PPLHKHZ3.js} +1 -1
- package/dist/cdn/{HQFL3NGM.js → PWGCOGC7.js} +1 -1
- package/dist/cdn/{DLV7AZZ6.js → QEITYICZ.js} +1 -1
- package/dist/cdn/{KLZWOBGK.js → QVDDWNQD.js} +1 -1
- package/dist/cdn/{ZXGNDW3R.js → QWUJHEPY.js} +1 -1
- package/dist/cdn/R437P4KQ.js +2 -0
- package/dist/cdn/{ZSATEDPE.js → RKVNFHFD.js} +1 -1
- package/dist/cdn/{CVNW2AU2.js → RM6HYEWM.js} +1 -1
- package/dist/cdn/{GWIC6C6P.js → RNMVOUE3.js} +1 -1
- package/dist/cdn/{C3SIGIJC.js → RQQWTDQG.js} +1 -1
- package/dist/cdn/{XIUYVZYL.js → S3CBTGXW.js} +1 -1
- package/dist/cdn/{XYAVR2MM.js → SGWJLKO4.js} +1 -1
- package/dist/cdn/{BKIKLE4Z.js → SI2EHJJ5.js} +1 -1
- package/dist/cdn/{Z6CZ7GFZ.js → SY3D5J7W.js} +1 -1
- package/dist/cdn/{3FIRDPVD.js → TBXAQ6YS.js} +1 -1
- package/dist/cdn/{Q5N7I65T.js → TFWTXEN7.js} +1 -1
- package/dist/cdn/{YHF3Q7QB.js → TKIL55TV.js} +1 -1
- package/dist/cdn/{NVNB4L52.js → TSLAML4I.js} +1 -1
- package/dist/cdn/{5Q64VY2E.js → UCHXRVI7.js} +1 -1
- package/dist/cdn/{PQVA7SKB.js → UE2HAEBW.js} +1 -1
- package/dist/cdn/{E3O6DPAL.js → UEC5OGAS.js} +1 -1
- package/dist/cdn/{DE7GSGUB.js → UKAP3ALW.js} +1 -1
- package/dist/cdn/{CRTJERAB.js → UNKENPV5.js} +1 -1
- package/dist/cdn/{5F6WBFDO.js → V4OFLP6D.js} +1 -1
- package/dist/cdn/{LK6WQCXQ.js → VBZL2GZD.js} +1 -1
- package/dist/cdn/{RNNEZRGA.js → VLP6VQEG.js} +1 -1
- package/dist/cdn/{INFZEU32.js → VZY472CH.js} +1 -1
- package/dist/cdn/{P2FSR5OV.js → WEADUP3Y.js} +1 -1
- package/dist/cdn/{Y2KRCLNN.js → WKTMPKVR.js} +1 -1
- package/dist/cdn/{E5YZOOW3.js → WXFKH5GM.js} +1 -1
- package/dist/cdn/{RAL6IXW5.js → X52CK3FZ.js} +1 -1
- package/dist/cdn/{4MAH5ULJ.js → X7GGOH2R.js} +1 -1
- package/dist/cdn/{RJLEYL7O.js → XEON6B7Z.js} +1 -1
- package/dist/cdn/{SAVDBHDE.js → XL66TA6C.js} +1 -1
- package/dist/cdn/{KPKJ2OVD.js → XN5455P6.js} +1 -1
- package/dist/cdn/{DQJ36YEL.js → XOCNSPTC.js} +1 -1
- package/dist/cdn/{TK5EXRZL.js → XOPNEAS5.js} +1 -1
- package/dist/cdn/{YVNBCXBJ.js → XR3PT7FP.js} +1 -1
- package/dist/cdn/{LOSU3FPH.js → XSJOQTEM.js} +1 -1
- package/dist/cdn/{6OKLCUSH.js → Y2DDFGCN.js} +1 -1
- package/dist/cdn/{6F6YFDOY.js → YWO5HXXP.js} +1 -1
- package/dist/cdn/{NWOPIQFN.js → ZIIHIUUV.js} +1 -1
- package/dist/cdn/{Q6CXYCV6.js → ZOGD4MGP.js} +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/runtime.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/solutions-components_commit.txt +4 -7
- package/package.json +1 -1
- package/dist/cdn/A4KEZALJ.js +0 -2
- package/dist/cdn/CGQALCTZ.js +0 -4
- package/dist/cdn/CXTHIJOC.js +0 -351
- package/dist/cdn/GPIIJWNM.js +0 -2
- package/dist/cdn/IGY23J7D.js +0 -2
package/dist/cdn/CXTHIJOC.js
DELETED
|
@@ -1,351 +0,0 @@
|
|
|
1
|
-
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import{d as wr,e as eo,f as Ri,g as $i,h as Ni}from"./NQH7ZZWD.js";import{a as Mi}from"./MHMM4RFR.js";import{a as oc,b as sc,c as ic,f as ts,g as rs,j as ac}from"./BSIPKI63.js";import b from"./DQJ36YEL.js";import a from"./TK5EXRZL.js";import{b as $l,c as Nl}from"./2B4SGB3I.js";import{b as Ai}from"./RLSY4VUQ.js";import"./CGQALCTZ.js";import{a as Rl}from"./VSRNGZ43.js";import"./QMAV4UTN.js";import"./Y2AUIXNK.js";import{$ as Bl,Aa as ec,Ba as Qo,Ca as Yo,Da as tc,Db as Xo,Ea as rc,Eb as es,Fa as _r,Fb as he,Ga as I,Ha as L,Ia as Oi,J as jl,Ja as Pi,K as xe,L as zl,M as qo,N as vi,O as Ii,P as Bo,Q as Qn,R as B,S as Ti,T as j,Ta as k,U as it,V as at,W as Ko,X as Ul,Y as ql,Z as Si,_ as Wo,a as fe,aa as Kl,b as K,ba as Yn,ca as Ho,da as Wl,ea as Hl,fa as Vl,g as Fl,ga as Vo,ha as Gl,ia as Pt,j as qe,ja as Ci,k as Ot,ka as Go,la as N,ma as A,mb as nc,na as Mt,oa as lt,pa as Jl,qa as Jo,ra as Zl,s as zo,sa as Ql,ta as Zo,ua as Ei,va as yr,wa as ki,xa as Yl,y as Uo,ya as Xl,zb as Xn}from"./BZWJ3KFS.js";import"./TEHBW75B.js";import"./RSPNBIIE.js";import"./ZCU2WWVN.js";import"./WGO4EVOV.js";import"./YKB6256M.js";import"./36LRAUE4.js";import"./JMY4B4WQ.js";import"./VQ5ZAQUF.js";import"./Z4F2NZOT.js";import"./KOIDWEP3.js";import"./3KXMYZCU.js";import"./6ERMTA3J.js";import"./GF4QELNV.js";import{l as Ll,v as xi}from"./3TAQSXLA.js";import"./PY6RTQDR.js";import"./DKD2EGQP.js";import"./5O53T3SW.js";import"./AJZDBHB6.js";import"./FES7B3SJ.js";import{b as Ml}from"./ZB5UCRCG.js";import{F as kl,G as Ol,H as Pl,L as bi,h as vl,i as st,k as Il,l as _i,q as wi,t as Tl,w as Sl,x as Cl,y as El}from"./T3EPRHTT.js";import{c as xl}from"./EXBEKVP5.js";export default $arcgis.t(([dl,v2,T2,Ud,Sg,Cg,Fg,P2,R2,UG,sA,ip,mr,Ha,mp,,ap,qg,{addressToLocations:Bg},Kg,Wg,fp,{createRenderer:Hg},{getSchemesByTag:Vg,getSchemes:Gg},{getBackgroundColorTheme:lp},{createAgeRenderer:Jg,createContinuousRenderer:Zg},{getSchemesByTag:rl},{createContinuousRenderer:Qg},{createRenderer:Yg},{getSchemesByTag:Xg},{createRenderer:ey},{getSchemesByTag:ty},{createRenderer:ry},{getSchemesByTag:ny},{createRenderer:oy},{getSchemesByTag:sy},{createAgeRenderer:iy,createContinuousRenderer:ay},{createRenderer:ly},{getSchemesByTag:cy},uy,hp,gp,{formatDateOnly:dy,convertDateFormatToIntlOptions:Gs,formatTimeOnly:py,formatDate:cp},my,fy,hy,gy,yy,yp,,{fetchKnowledgeGraph:up,executeQueryStreaming:_y,executeSearchStreaming:wy},by,,,,,,,,,,,,,,,,,,,,,,,,,qV,KV,,,,,,,,,,,,,bA,AA,{r:Dl},{r:Zn}])=>{var to=class extends El{constructor(e){if(super(e),this.it=_i,e.type!==Sl.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===_i||e==null)return this._t=void 0,this.it=e;if(e===Il)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;let r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};to.directiveName="unsafeHTML",to.resultType=1;var lc=Cl(to);var d=I;async function Li(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 Kl(r),o=n?.getParentRunId();n!==void 0&&o!==void 0&&await n.handleCustomEvent?.(t,e,o)}var J=async(t,e)=>{await Li("trace_message",t,e)},ge=async(t,e)=>{await Li("graph_ux_suggestion",t,e)};var Xp={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"}},cv=Object.keys(Xp);var ji=Symbol.for("langgraph-zod");ji in globalThis||(globalThis[ji]=new WeakSet);function dc(t){let e=globalThis[ji];e.has(t)||(Object.defineProperty(t,"langgraph",{get(){let r=this;return{metadata(n){return es(r,{jsonSchemaExtra:n})},reducer(n,o){return es(r,{default:Go(r),reducer:{schema:o,fn:n}})}}}}),e.add(t))}try{dc(A.ZodType.prototype),dc(I.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 pc=class extends Hl{constructor(t){super(),this.parent=t,this._map=this.parent._map}add(t,...e){let r=e[0];if(r&&!r?.default){let n=Go(t);n!=null&&(r.default=n)}return super.add(t,...e)}},nm=new pc(Xo);var wm=A.function().args(A.custom()).returns(A.union([A.boolean(),A.promise(A.boolean())])),bm=A.function().args(A.custom(),A.custom(),A.custom()).returns(A.union([A.string(),A.promise(A.string())])),Am=["approve","edit","reject"],xm=A.enum(Am),vm=A.object({allowedDecisions:A.array(xm),description:A.union([A.string(),bm]).optional(),argsSchema:A.record(A.any()).optional(),when:wm.optional()}),_S=A.object({interruptOn:A.record(A.union([A.boolean(),vm])).optional(),descriptionPrefix:A.string().default("Tool execution requires approval")});var Sm=`<role>
|
|
10
|
-
Context Extraction Assistant
|
|
11
|
-
</role>
|
|
12
|
-
|
|
13
|
-
<primary_objective>
|
|
14
|
-
Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
|
|
15
|
-
</primary_objective>
|
|
16
|
-
|
|
17
|
-
<objective_information>
|
|
18
|
-
You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
|
|
19
|
-
This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
|
|
20
|
-
</objective_information>
|
|
21
|
-
|
|
22
|
-
<instructions>
|
|
23
|
-
The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
|
|
24
|
-
You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
|
|
25
|
-
</instructions>
|
|
26
|
-
|
|
27
|
-
The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
|
|
28
|
-
|
|
29
|
-
With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
|
|
30
|
-
Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
|
|
31
|
-
|
|
32
|
-
<messages>
|
|
33
|
-
Messages to summarize:
|
|
34
|
-
{messages}
|
|
35
|
-
</messages>`;var Cm=A.function().args(A.array(A.custom())).returns(A.union([A.number(),A.promise(A.number())])),Wi=A.object({fraction:A.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().positive("Tokens must be greater than 0").optional(),messages:A.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),Ac=A.object({fraction:A.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:A.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:A.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(t=>[t.fraction,t.tokens,t.messages].filter(e=>e!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),LS=A.object({model:A.custom(),trigger:A.union([Wi,A.array(Wi)]).optional(),keep:Ac.optional(),tokenCounter:Cm.optional(),summaryPrompt:A.string().default(Sm),trimTokensToSummarize:A.number().optional(),summaryPrefix:A.string().optional(),maxTokensBeforeSummary:A.number().optional(),messagesToKeep:A.number().optional()});var VS=A.object({model:A.string().or(A.instanceof(Zl)).optional(),systemPrompt:A.string().optional(),maxTools:A.number().optional(),alwaysInclude:A.array(A.string()).optional()});var eC=A.object({applyToInput:A.boolean().optional(),applyToOutput:A.boolean().optional(),applyToToolResults:A.boolean().optional()});var sC=A.object({rules:A.record(A.string(),A.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Em=["continue","error","end"],km="continue";var Om=A.enum(Em).default(km);A.object({toolName:A.string().optional(),threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:Om});var gC=A.object({threadToolCallCount:A.record(A.string(),A.number()).default({}),runToolCallCount:A.record(A.string(),A.number()).default({})});var Pm=A.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Mm=A.object({content:A.string().describe("Content of the todo item"),status:Pm}),IC=A.object({todos:A.array(Mm).default([])});var kC=A.object({threadLimit:A.number().optional(),runLimit:A.number().optional(),exitBehavior:A.enum(["error","end"]).optional()}),OC=A.object({threadModelCallCount:A.number().default(0),runModelCallCount:A.number().default(0)});var ns=A.object({maxRetries:A.number().min(0).default(2),retryOn:A.union([A.function().args(A.instanceof(Error)).returns(A.boolean()),A.array(A.custom())]).default(()=>()=>!0),backoffFactor:A.number().min(0).default(2),initialDelayMs:A.number().min(0).default(1e3),maxDelayMs:A.number().min(0).default(6e4),jitter:A.boolean().default(!0)});var KC=A.object({onFailure:A.union([A.literal("error"),A.literal("continue"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(ns);var YC=A.object({tools:A.array(A.union([A.custom(),A.custom(),A.string()])).optional(),onFailure:A.union([A.literal("error"),A.literal("continue"),A.literal("raise"),A.literal("return_message"),A.function().args(A.instanceof(Error)).returns(A.string())]).default("continue")}).merge(ns);var mE=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});var yE=A.object({enableCaching:A.boolean().optional(),ttl:A.enum(["5m","1h"]).optional(),minMessagesToCache:A.number().optional(),unsupportedModelBehavior:A.enum(["ignore","warn","raise"]).optional()});function ro(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
36
|
-
|
|
37
|
-
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
38
|
-
`,t}function E(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function _(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 Hi=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Hi=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 no(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var oo=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var C=class extends Error{},W=class t extends C{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;let s=r;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new ut({message:n,cause:oo(r)});let s=r?.error;return e===400?new Ar(e,s,n,o):e===401?new xr(e,s,n,o):e===403?new vr(e,s,n,o):e===404?new Ir(e,s,n,o):e===409?new Tr(e,s,n,o):e===422?new Sr(e,s,n,o):e===429?new Cr(e,s,n,o):e>=500?new Er(e,s,n,o):new t(e,s,n,o)}},H=class extends W{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ut=class extends W{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Me=class extends ut{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ar=class extends W{},xr=class extends W{},vr=class extends W{},Ir=class extends W{},Tr=class extends W{},Sr=class extends W{},Cr=class extends W{},Er=class extends W{},kr=class extends C{constructor(){super("Could not parse response content as the length limit was reached")}},Or=class extends C{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Re=class extends Error{constructor(e){super(e)}},$t=class extends W{constructor(e,r,n){let o="OAuth2 authentication error",s;if(r&&typeof r=="object"){let i=r;s=i.error;let a=i.error_description;a&&typeof a=="string"?o=a:s&&(o=s)}super(e,r,o,n),this.error_code=s}},so=class extends C{constructor(e,r,n){super(e),this.provider=r,this.cause=n}};var qm=/^[a-z][a-z0-9+.-]*:/i,xc=t=>qm.test(t),ue=t=>(ue=Array.isArray,ue(t)),Vi=ue;function os(t){return typeof t!="object"?{}:t??{}}function Gi(t){if(!t)return!0;for(let e in t)return!1;return!0}function vc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function io(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Ic=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new C(`${t} must be an integer`);if(e<0)throw new C(`${t} must be a positive integer`);return e};var Tc=t=>{try{return JSON.parse(t)}catch{return}};var $e=t=>new Promise(e=>setTimeout(e,t));var dt="6.44.0";var kc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Bm(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Km=()=>{let t=Bm();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"X-Stainless-OS":Cc(Deno.build.os),"X-Stainless-Arch":Sc(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":dt,"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":dt,"X-Stainless-OS":Cc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Sc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Wm();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":dt,"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":dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Wm(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var Sc=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Cc=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"),Ec,Oc=()=>Ec??(Ec=Km());function ss(){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 Ji(...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 is(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ji({start(){},async pull(r){let{done:n,value:o}=await e.next();n?r.close():r.enqueue(o)},async cancel(){await e.return?.()}})}function Zi(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 Qi(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 Mc=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Yi="RFC3986",Xi=t=>String(t),ea={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Xi},Rc="RFC1738";var as=(t,e)=>(as=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),as(t,e)),Ne=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var ta=1024,$c=(t,e,r,n,o)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=ta){let c=s.length>=ta?s.slice(a,a+ta):s,l=[];for(let u=0;u<c.length;++u){let m=c.charCodeAt(u);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===Rc&&(m===40||m===41)){l[l.length]=c.charAt(u);continue}if(m<128){l[l.length]=Ne[m];continue}if(m<2048){l[l.length]=Ne[192|m>>6]+Ne[128|m&63];continue}if(m<55296||m>=57344){l[l.length]=Ne[224|m>>12]+Ne[128|m>>6&63]+Ne[128|m&63];continue}u+=1,m=65536+((m&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=Ne[240|m>>18]+Ne[128|m>>12&63]+Ne[128|m>>6&63]+Ne[128|m&63]}i+=l.join("")}return i};function Nc(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ra(t,e){if(ue(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Dc={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Fc=function(t,e){Array.prototype.push.apply(t,ue(e)?e:[e])},Lc,ee={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:$c,encodeValuesOnly:!1,format:Yi,formatter:Xi,indices:!1,serializeDate(t){return(Lc??(Lc=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Vm(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var na={};function jc(t,e,r,n,o,s,i,a,c,l,u,m,f,h,w,b,v,g){let x=t,S=g,$=0,z=!1;for(;(S=S.get(na))!==void 0&&!z;){let Q=S.get(t);if($+=1,typeof Q<"u"){if(Q===$)throw new RangeError("Cyclic object value");z=!0}typeof S.get(na)>"u"&&($=0)}if(typeof l=="function"?x=l(e,x):x instanceof Date?x=f?.(x):r==="comma"&&ue(x)&&(x=ra(x,function(Q){return Q instanceof Date?f?.(Q):Q})),x===null){if(s)return c&&!b?c(e,ee.encoder,v,"key",h):e;x=""}if(Vm(x)||Nc(x)){if(c){let Q=b?e:c(e,ee.encoder,v,"key",h);return[w?.(Q)+"="+w?.(c(x,ee.encoder,v,"value",h))]}return[w?.(e)+"="+w?.(String(x))]}let P=[];if(typeof x>"u")return P;let U;if(r==="comma"&&ue(x))b&&c&&(x=ra(x,c)),U=[{value:x.length>0?x.join(",")||null:void 0}];else if(ue(l))U=l;else{let Q=Object.keys(x);U=u?Q.sort(u):Q}let q=a?String(e).replace(/\./g,"%2E"):String(e),ne=n&&ue(x)&&x.length===1?q+"[]":q;if(o&&ue(x)&&x.length===0)return ne+"[]";for(let Q=0;Q<U.length;++Q){let X=U[Q],bl=typeof X=="object"&&typeof X.value<"u"?X.value:x[X];if(i&&bl===null)continue;let yi=m&&a?X.replace(/\./g,"%2E"):X,Qp=ue(x)?typeof r=="function"?r(ne,yi):ne:ne+(m?"."+yi:"["+yi+"]");g.set(t,$);let Al=new WeakMap;Al.set(na,g),Fc(P,jc(bl,Qp,r,n,o,s,i,a,r==="comma"&&b&&ue(x)?null:c,l,u,m,f,h,w,b,v,Al))}return P}function Gm(t=ee){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||ee.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Yi;if(typeof t.format<"u"){if(!as(ea,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=ea[r],o=ee.filter;(typeof t.filter=="function"||ue(t.filter))&&(o=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Dc?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=ee.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:ee.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ee.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ee.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ee.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?ee.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ee.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ee.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ee.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ee.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ee.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ee.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ee.strictNullHandling}}function zc(t,e={}){let r=t,n=Gm(e),o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):ue(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof r!="object"||r===null)return"";let a=Dc[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);let l=new WeakMap;for(let f=0;f<o.length;++f){let h=o[f];n.skipNulls&&r[h]===null||Fc(i,jc(r[h],h,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let u=i.join(n.delimiter),m=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),u.length>0?m+u:""}function Uc(t){return zc(t,{arrayFormat:"brackets"})}function Kc(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 qc;function Pr(t){let e;return(qc??(e=new globalThis.TextEncoder,qc=e.encode.bind(e)))(t)}var Bc;function oa(t){let e;return(Bc??(e=new globalThis.TextDecoder,Bc=e.decode.bind(e)))(t)}var ye,_e,Nt=class{constructor(){ye.set(this,void 0),_e.set(this,void 0),E(this,ye,new Uint8Array,"f"),E(this,_e,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Pr(e):e;E(this,ye,Kc([_(this,ye,"f"),r]),"f");let n=[],o;for(;(o=Zm(_(this,ye,"f"),_(this,_e,"f")))!=null;){if(o.carriage&&_(this,_e,"f")==null){E(this,_e,o.index,"f");continue}if(_(this,_e,"f")!=null&&(o.index!==_(this,_e,"f")+1||o.carriage)){n.push(oa(_(this,ye,"f").subarray(0,_(this,_e,"f")-1))),E(this,ye,_(this,ye,"f").subarray(_(this,_e,"f")),"f"),E(this,_e,null,"f");continue}let s=_(this,_e,"f")!==null?o.preceding-1:o.preceding,i=oa(_(this,ye,"f").subarray(0,s));n.push(i),E(this,ye,_(this,ye,"f").subarray(o.index),"f"),E(this,_e,null,"f")}return n}flush(){return _(this,ye,"f").length?this.decode(`
|
|
39
|
-
`):[]}};ye=new WeakMap,_e=new WeakMap;Nt.NEWLINE_CHARS=new Set([`
|
|
40
|
-
`,"\r"]);Nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Zm(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Wc(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 cs={off:0,error:200,warn:300,info:400,debug:500},sa=(t,e,r)=>{if(t){if(vc(cs,t))return t;Z(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(cs))}`)}};function ao(){}function ls(t,e,r){return!e||cs[t]>cs[r]?ao:e[t].bind(e)}var Qm={error:ao,warn:ao,info:ao,debug:ao},Hc=new WeakMap;function Z(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Qm;let n=Hc.get(e);if(n&&n[0]===r)return n[1];let o={error:ls("error",e,r),warn:ls("warn",e,r),info:ls("info",e,r),debug:ls("debug",e,r)};return Hc.set(e,[r,o]),o}var Be=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var lo,Le=class t{constructor(e,r,n){this.iterator=e,lo.set(this,void 0),this.controller=r,E(this,lo,n,"f")}static fromSSEResponse(e,r,n,o){let s=!1,i=n?Z(n):console;async function*a(){if(s)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let l of Ym(e,r))if(!c){if(l.data.startsWith("[DONE]")){c=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let u;try{u=JSON.parse(l.data)}catch(m){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),m}if(u&&u.error)throw new W(void 0,u.error,void 0,e.headers);yield o?{event:l.event,data:u}:u}else{let u;try{u=JSON.parse(l.data)}catch(m){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),m}if(l.event=="error")throw new W(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}c=!0}catch(l){if(no(l))return;throw l}finally{c||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*s(){let a=new Nt,c=Zi(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*i(){if(o)throw new C("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(no(c))return;throw c}finally{a||r.abort()}}return new t(i,r,n)}[(lo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let i=n.next();e.push(i),r.push(i)}return s.shift()}});return[new t(()=>o(e),this.controller,_(this,lo,"f")),new t(()=>o(r),this.controller,_(this,lo,"f"))]}toReadableStream(){let e=this,r;return Ji({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await r.next();if(s)return n.close();let i=Pr(JSON.stringify(o)+`
|
|
41
|
-
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};async function*Ym(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new C("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new C("Attempted to iterate over a response with no body");let r=new ia,n=new Nt,o=Zi(t.body);for await(let s of Xm(o))for(let i of n.decode(s)){let a=r.decode(i);a&&(yield a)}for(let s of n.flush()){let i=r.decode(s);i&&(yield i)}}async function*Xm(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Pr(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=Wc(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var ia=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
42
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=ef(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function ef(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function us(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,i=await(async()=>{if(e.options.stream)return Z(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):Le.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.json();return aa(f,r)}return await r.text()})();return Z(t).debug(`[${n}] response parsed`,Be({retryOfRequestLogID:o,url:r.url,status:r.status,body:i,durationMs:Date.now()-s})),i}function aa(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var co,Lt=class t extends Promise{constructor(e,r,n=us){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,co.set(this,void 0),E(this,co,e,"f")}_thenUnwrap(e){return new t(_(this,co,"f"),this.responsePromise,async(r,n)=>aa(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,co,"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)}};co=new WeakMap;var ds,Mr=class{constructor(e,r,n,o){ds.set(this,void 0),E(this,ds,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new C("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,ds,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ds=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},uo=class extends Lt{constructor(e,r,n){super(e,r,async(o,s)=>new n(o,s.response,await us(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},de=class extends Mr{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}},R=class extends Mr{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:{...os(this.options.query),after:r}}:null}},D=class extends Mr{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:{...os(this.options.query),after:e}}:null}},Y=class extends Mr{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:{...os(this.options.query),after:e}}:null}};var rf={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},nf="urn:ietf:params:oauth:grant-type:token-exchange",ps=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??ss()}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:nf,subject_token:e,subject_token_type:rf[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){let a=await n.text(),c;try{c=JSON.parse(a)}catch{}throw n.status===400||n.status===401||n.status===403?new $t(n.status,c,n.headers):W.generate(n.status,c,`Token exchange failed with status ${n.status}`,n.headers)}let o=await n.json(),s=o.expires_in||3600,i=Date.now()+s*1e3;return this.cachedToken={token:o.access_token,expiresAt:i},o.access_token}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 ua=()=>{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 Rr(t,e,r){return ua(),new File(t,e??"unknown_file",r)}function po(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 ms=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pt=async(t,e)=>la(t.body)?{...t,body:await Gc(t.body,e)}:t,pe=async(t,e)=>({...t,body:await Gc(t.body,e)}),Vc=new WeakMap;function of(t){let e=typeof t=="function"?t:t.fetch,r=Vc.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 Vc.set(e,n),n}var Gc=async(t,e)=>{if(!await of(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])=>ca(r,n,o))),r},Jc=t=>t instanceof Blob&&"name"in t,sf=t=>typeof t=="object"&&t!==null&&(t instanceof Response||ms(t)||Jc(t)),la=t=>{if(sf(t))return!0;if(Array.isArray(t))return t.some(la);if(t&&typeof t=="object"){for(let e in t)if(la(t[e]))return!0}return!1},ca=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,Rr([await r.blob()],po(r)));else if(ms(r))t.append(e,Rr([await new Response(is(r)).blob()],po(r)));else if(Jc(r))t.append(e,r,po(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ca(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>ca(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 Zc=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",af=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Zc(t),lf=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function mo(t,e,r){if(ua(),t=await t,af(t))return t instanceof File?t:Rr([await t.arrayBuffer()],t.name);if(lf(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Rr(await da(o),e,r)}let n=await da(t);if(e||(e=po(t)),!r?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(r={...r,type:o})}return Rr(n,e,r)}async function da(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Zc(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(ms(t))for await(let r of t)e.push(...await da(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${cf(t)}`)}return e}function cf(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var y=class{constructor(e){this._client=e}};function Yc(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Qc=Object.freeze(Object.create(null)),df=(t=Yc)=>function(r,...n){if(r.length===1)return r[0];let o=!1,s=[],i=r.reduce((u,m,f)=>{/[?#]/.test(m)&&(o=!0);let h=n[f],w=(o?encodeURIComponent:t)(""+h);return f!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Qc)??Qc)?.toString)&&(w=h+"",s.push({start:u.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),u+m+(f===n.length?"":w)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((u,m)=>u.start-m.start),s.length>0){let u=0,m=s.reduce((f,h)=>{let w=" ".repeat(h.start-u),b="^".repeat(h.length);return u=h.start+h.length,f+w+b},"");throw new C(`Path parameters result in path with invalid segments:
|
|
43
|
-
${s.map(f=>f.error).join(`
|
|
44
|
-
`)}
|
|
45
|
-
${i}
|
|
46
|
-
${m}`)}return i},p=df(Yc);var Dt=class extends y{list(e,r={},n){return this._client.getAPIList(p`/chat/completions/${e}/messages`,R,{query:r,...n,__security:{bearerAuth:!0}})}};function fo(t){return t!==void 0&&"function"in t&&t.function!==void 0}function eu(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function ho(t){return t?.$brand==="auto-parseable-response-format"}function Ft(t){return t?.$brand==="auto-parseable-tool"}function tu(t,e){return!e||!pa(e)?{...t,choices:t.choices.map(r=>(nu(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:go(t,e)}function go(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new kr;if(n.finish_reason==="content_filter")throw new Or;return nu(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>ff(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?mf(e,n.message.content):null}}});return{...t,choices:r}}function mf(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 ff(t,e){let r=t.tools?.find(n=>fo(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ft(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function ru(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>fo(n)&&n.function?.name===e.function.name);return fo(r)&&(Ft(r)||r?.function.strict||!1)}function pa(t){return ho(t.response_format)?!0:t.tools?.some(e=>Ft(e)||e.type==="function"&&e.function.strict===!0)??!1}function nu(t){for(let e of t||[])if(e.type!=="function")throw new C(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ou(t){for(let e of t??[]){if(e.type!=="function")throw new C(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new C(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var $r=t=>t?.role==="assistant",ma=t=>t?.role==="tool";var fa,fs,hs,yo,_o,gs,wo,Ke,bo,ys,_s,Nr,su,mt=class{constructor(){fa.add(this),this.controller=new AbortController,fs.set(this,void 0),hs.set(this,()=>{}),yo.set(this,()=>{}),_o.set(this,void 0),gs.set(this,()=>{}),wo.set(this,()=>{}),Ke.set(this,{}),bo.set(this,!1),ys.set(this,!1),_s.set(this,!1),Nr.set(this,!1),E(this,fs,new Promise((e,r)=>{E(this,hs,e,"f"),E(this,yo,r,"f")}),"f"),E(this,_o,new Promise((e,r)=>{E(this,gs,e,"f"),E(this,wo,r,"f")}),"f"),_(this,fs,"f").catch(()=>{}),_(this,_o,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},_(this,fa,"m",su).bind(this))},0)}_connected(){this.ended||(_(this,hs,"f").call(this),this._emit("connect"))}get ended(){return _(this,bo,"f")}get errored(){return _(this,ys,"f")}get aborted(){return _(this,_s,"f")}abort(){this.controller.abort()}on(e,r){return(_(this,Ke,"f")[e]||(_(this,Ke,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=_(this,Ke,"f")[e];if(!n)return this;let o=n.findIndex(s=>s.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(_(this,Ke,"f")[e]||(_(this,Ke,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{E(this,Nr,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){E(this,Nr,!0,"f"),await _(this,_o,"f")}_emit(e,...r){if(_(this,bo,"f"))return;e==="end"&&(E(this,bo,!0,"f"),_(this,gs,"f").call(this));let n=_(this,Ke,"f")[e];if(n&&(_(this,Ke,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!_(this,Nr,"f")&&!n?.length&&Promise.reject(o),_(this,yo,"f").call(this,o),_(this,wo,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!_(this,Nr,"f")&&!n?.length&&Promise.reject(o),_(this,yo,"f").call(this,o),_(this,wo,"f").call(this,o),this._emit("end")}}_emitFinal(){}};fs=new WeakMap,hs=new WeakMap,yo=new WeakMap,_o=new WeakMap,gs=new WeakMap,wo=new WeakMap,Ke=new WeakMap,bo=new WeakMap,ys=new WeakMap,_s=new WeakMap,Nr=new WeakMap,fa=new WeakSet,su=function(e){if(E(this,ys,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new H),e instanceof H)return E(this,_s,!0,"f"),this._emit("abort",e);if(e instanceof C)return this._emit("error",e);if(e instanceof Error){let r=new C(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new C(String(e)))};function iu(t){return typeof t.parse=="function"}var me,ha,ws,ga,ya,_a,au,lu,hf=10,Lr=class extends mt{constructor(){super(...arguments),me.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),ma(e)&&e.content)this._emit("functionToolCallResult",e.content);else if($r(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new C("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_(this,me,"m",ha).call(this)}async finalMessage(){return await this.done(),_(this,me,"m",ws).call(this)}async finalFunctionToolCall(){return await this.done(),_(this,me,"m",ga).call(this)}async finalFunctionToolCallResult(){return await this.done(),_(this,me,"m",ya).call(this)}async totalUsage(){return await this.done(),_(this,me,"m",_a).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=_(this,me,"m",ws).call(this);r&&this._emit("finalMessage",r);let n=_(this,me,"m",ha).call(this);n&&this._emit("finalContent",n);let o=_(this,me,"m",ga).call(this);o&&this._emit("finalFunctionToolCall",o);let s=_(this,me,"m",ya).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",_(this,me,"m",_a).call(this))}async _createChatCompletion(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,me,"m",au).call(this,r);let s=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(go(s,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){let o="tool",{tool_choice:s="auto",stream:i,...a}=r,c=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:l=hf}=n||{},u=r.tools.map(h=>{if(Ft(h)){if(!h.$callback)throw new C("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),m={};for(let h of u)h.type==="function"&&(m[h.function.name||h.function.function.name]=h.function);let f="tools"in r?u.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of r.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){let b=(await this._createChatCompletion(e,{...a,tool_choice:s,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!b)throw new C("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(let v of b.tool_calls){if(v.type!=="function")continue;let g=v.id,{name:x,arguments:S}=v.function,$=m[x];if($){if(c&&c!==x){let q=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:g,content:q});continue}}else{let q=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(m).map(ne=>JSON.stringify(ne)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:g,content:q});continue}let z;try{z=iu($)?await $.parse(S):S}catch(q){let ne=q instanceof Error?q.message:String(q);this._addMessage({role:o,tool_call_id:g,content:ne});continue}let P=await $.function(z,this),U=_(this,me,"m",lu).call(this,P);if(this._addMessage({role:o,tool_call_id:g,content:U}),c)return}}}};me=new WeakSet,ha=function(){return _(this,me,"m",ws).call(this).content??null},ws=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if($r(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new C("stream ended without producing a ChatCompletionMessage with role=assistant")},ga=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if($r(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}}},ya=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ma(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}},_a=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},au=function(e){if(e.n!=null&&e.n>1)throw new C("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},lu=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Ao=class t extends Lr{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,s)),o}_addMessage(e,r=!0){super._addMessage(e,r),$r(e)&&e.content&&this._emit("content",e.content)}};var se={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},wa=class extends Error{},ba=class extends Error{};function gf(t,e=se.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return yf(t.trim(),e)}var yf=(t,e)=>{let r=t.length,n=0,o=f=>{throw new wa(`${f} at position ${n}`)},s=f=>{throw new ba(`${f} at position ${n}`)},i=()=>(m(),n>=r&&o("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||se.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||se.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||se.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||se.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||se.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||se.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let f=n,h=!1;for(n++;n<r&&(t[n]!=='"'||h&&t[n-1]==="\\");)h=t[n]==="\\"?!h:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(h)))}catch(w){s(String(w))}else if(se.STR&e)try{return JSON.parse(t.substring(f,n-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,m();let f={};try{for(;t[n]!=="}";){if(m(),n>=r&&se.OBJ&e)return f;let h=a();m(),n++;try{let w=i();Object.defineProperty(f,h,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(se.OBJ&e)return f;throw w}m(),t[n]===","&&n++}}catch{if(se.OBJ&e)return f;o("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(i()),m(),t[n]===","&&n++}catch{if(se.ARR&e)return f;o("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){t==="-"&&se.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(se.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(h))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(se.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&se.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){s(String(w))}}},m=()=>{for(;n<r&&`
|
|
47
|
-
\r `.includes(t[n]);)n++};return i()},Aa=t=>gf(t,se.ALL^se.NUM);var te,We,Dr,ft,xa,bs,va,Ia,Ta,As,Sa,cu,jt=class t extends Lr{constructor(e){super(),te.add(this),We.set(this,void 0),Dr.set(this,void 0),ft.set(this,void 0),E(this,We,e,"f"),E(this,Dr,[],"f")}get currentChatCompletionSnapshot(){return _(this,ft,"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;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,te,"m",xa).call(this);let s=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let i of s)_(this,te,"m",va).call(this,i);if(s.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,te,"m",As).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),_(this,te,"m",xa).call(this),this._connected();let o=Le.fromReadableStream(e,this.controller),s;for await(let i of o)s&&s!==i.id&&this._addChatCompletion(_(this,te,"m",As).call(this)),_(this,te,"m",va).call(this,i),s=i.id;if(o.controller.signal?.aborted)throw new H;return this._addChatCompletion(_(this,te,"m",As).call(this))}[(We=new WeakMap,Dr=new WeakMap,ft=new WeakMap,te=new WeakSet,xa=function(){this.ended||E(this,ft,void 0,"f")},bs=function(r){let n=_(this,Dr,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},_(this,Dr,"f")[r.index]=n,n)},va=function(r){if(this.ended)return;let n=_(this,te,"m",cu).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 i=_(this,te,"m",bs).call(this,s);s.finish_reason&&(_(this,te,"m",Ta).call(this,s),i.current_tool_call_index!=null&&_(this,te,"m",Ia).call(this,s,i.current_tool_call_index));for(let a of o.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(_(this,te,"m",Ta).call(this,s),i.current_tool_call_index!=null&&_(this,te,"m",Ia).call(this,s,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of o.delta.tool_calls??[]){let c=s.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},Ia=function(r,n){if(_(this,te,"m",bs).call(this,r).done_tool_calls.has(n))return;let s=r.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let i=_(this,We,"f")?.tools?.find(a=>fo(a)&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Ft(i)?i.$parseRaw(s.function.arguments):i?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},Ta=function(r){let n=_(this,te,"m",bs).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let o=_(this,te,"m",Sa).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}))},As=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,ft,"f");if(!r)throw new C("request ended without sending any chunks");return E(this,ft,void 0,"f"),E(this,Dr,[],"f"),_f(r,_(this,We,"f"))},Sa=function(){let r=_(this,We,"f")?.response_format;return ho(r)?r:null},cu=function(r){var n,o,s,i;let a=_(this,ft,"f"),{choices:c,...l}=r;a?Object.assign(a,l):a=E(this,ft,{...l,choices:[]},"f");for(let{delta:u,finish_reason:m,index:f,logprobs:h=null,...w}of r.choices){let b=a.choices[f];if(b||(b=a.choices[f]={finish_reason:m,index:f,message:{},logprobs:h,...w}),h)if(!b.logprobs)b.logprobs=Object.assign({},h);else{let{content:P,refusal:U,...q}=h;Object.assign(b.logprobs,q),P&&((n=b.logprobs).content??(n.content=[]),b.logprobs.content.push(...P)),U&&((o=b.logprobs).refusal??(o.refusal=[]),b.logprobs.refusal.push(...U))}if(m&&(b.finish_reason=m,_(this,We,"f")&&pa(_(this,We,"f")))){if(m==="length")throw new kr;if(m==="content_filter")throw new Or}if(Object.assign(b,w),!u)continue;let{content:v,refusal:g,function_call:x,role:S,tool_calls:$,...z}=u;if(Object.assign(b.message,z),g&&(b.message.refusal=(b.message.refusal||"")+g),S&&(b.message.role=S),x&&(b.message.function_call?(x.name&&(b.message.function_call.name=x.name),x.arguments&&((s=b.message.function_call).arguments??(s.arguments=""),b.message.function_call.arguments+=x.arguments)):b.message.function_call=x),v&&(b.message.content=(b.message.content||"")+v,!b.message.refusal&&_(this,te,"m",Sa).call(this)&&(b.message.parsed=Aa(b.message.content))),$){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:P,id:U,type:q,function:ne,...Q}of $){let X=(i=b.message.tool_calls)[P]??(i[P]={});Object.assign(X,Q),U&&(X.id=U),q&&(X.type=q),ne&&(X.function??(X.function={name:ne.name??"",arguments:""})),ne?.name&&(X.function.name=ne.name),ne?.arguments&&(X.function.arguments+=ne.arguments,ru(_(this,We,"f"),X)&&(X.function.parsed_arguments=Aa(X.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function _f(t,e){let{id:r,choices:n,created:o,model:s,system_fingerprint:i,...a}=t,c={...a,id:r,choices:n.map(({message:l,finish_reason:u,index:m,logprobs:f,...h})=>{if(!u)throw new C(`missing finish_reason for choice ${m}`);let{content:w=null,function_call:b,tool_calls:v,...g}=l,x=l.role;if(!x)throw new C(`missing role for choice ${m}`);if(b){let{arguments:S,name:$}=b;if(S==null)throw new C(`missing function_call.arguments for choice ${m}`);if(!$)throw new C(`missing function_call.name for choice ${m}`);return{...h,message:{content:w,function_call:{arguments:S,name:$},role:x,refusal:l.refusal??null},finish_reason:u,index:m,logprobs:f}}return v?{...h,index:m,finish_reason:u,logprobs:f,message:{...g,role:x,content:w,refusal:l.refusal??null,tool_calls:v.map((S,$)=>{let{function:z,type:P,id:U,...q}=S,{arguments:ne,name:Q,...X}=z||{};if(U==null)throw new C(`missing choices[${m}].tool_calls[${$}].id
|
|
48
|
-
${xs(t)}`);if(P==null)throw new C(`missing choices[${m}].tool_calls[${$}].type
|
|
49
|
-
${xs(t)}`);if(Q==null)throw new C(`missing choices[${m}].tool_calls[${$}].function.name
|
|
50
|
-
${xs(t)}`);if(ne==null)throw new C(`missing choices[${m}].tool_calls[${$}].function.arguments
|
|
51
|
-
${xs(t)}`);return{...q,id:U,type:P,function:{...X,name:Q,arguments:ne}}})}}:{...h,message:{...g,content:w,role:x,refusal:l.refusal??null},finish_reason:u,index:m,logprobs:f}}),created:o,model:s,object:"chat.completion",...i?{system_fingerprint:i}:{}};return tu(c,e)}function xs(t){return JSON.stringify(t)}var xo=class t extends jt{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,s)),o}};var He=class extends y{constructor(){super(...arguments),this.messages=new Dt(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(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/chat/completions/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return ou(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>go(n,e))}runTools(e,r){return e.stream?xo.runTools(this._client,e,r):Ao.runTools(this._client,e,r)}stream(e,r){return jt.createChatCompletion(this._client,e,r)}};He.Messages=Dt;var ht=class extends y{constructor(){super(...arguments),this.completions=new He(this._client)}};ht.Completions=He;var Fr=class extends y{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",R,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var jr=class extends y{list(e={},r){return this._client.getAPIList("/organization/audit_logs",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var zr=class extends y{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/organization/certificates/${e}`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/certificates/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",de,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",de,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Ur=class extends y{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var qr=class extends y{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends y{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/roles/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",Y,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Kr=class extends y{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/spend_alerts/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Wr=class extends y{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var Hr=class extends y{create(e,r,n){return this._client.post(p`/organization/groups/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/roles`,Y,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Vr=class extends y{create(e,r,n){return this._client.post(p`/organization/groups/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{group_id:o}=r;return this._client.get(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/groups/${e}/users`,Y,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{group_id:o}=r;return this._client.delete(p`/organization/groups/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var gt=class extends y{constructor(){super(...arguments),this.users=new Vr(this._client),this.roles=new Hr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/groups/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",Y,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};gt.Users=Vr;gt.Roles=Hr;var Gr=class extends y{retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/api_keys`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Jr=class extends y{list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/certificates`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/activate`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,n){return this._client.getAPIList(p`/organization/projects/${e}/certificates/deactivate`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Zr=class extends y{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/data_retention`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Qr=class extends y{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}};var Yr=class extends y{retrieve(e,r){return this._client.get(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}/model_permissions`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Xr=class extends y{listRateLimits(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/rate_limits`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/rate_limits/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}};var en=class extends y{create(e,r,n){return this._client.post(p`/projects/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/projects/${o}/roles/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/projects/${e}/roles`,Y,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/projects/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var tn=class extends y{create(e,r,n){return this._client.post(p`/organization/projects/${e}/service_accounts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/service_accounts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/service_accounts`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rn=class extends y{create(e,r,n){return this._client.post(p`/organization/projects/${e}/spend_alerts`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/spend_alerts/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/spend_alerts`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var nn=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/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(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/groups/${e}/roles`,Y,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,group_id:s}=r;return this._client.delete(p`/projects/${o}/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var zt=class extends y{constructor(){super(...arguments),this.roles=new nn(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/groups`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o,...s}=r;return this._client.get(p`/organization/projects/${o}/groups/${e}`,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/groups`,Y,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};zt.Roles=nn;var on=class extends y{create(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/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(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r,n){let{project_id:o,...s}=r;return this._client.getAPIList(p`/projects/${o}/users/${e}/roles`,Y,{query:s,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o,user_id:s}=r;return this._client.delete(p`/projects/${o}/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends y{constructor(){super(...arguments),this.roles=new on(this._client)}create(e,r,n){return this._client.post(p`/organization/projects/${e}/users`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{project_id:o}=r;return this._client.get(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){let{project_id:o,...s}=r;return this._client.post(p`/organization/projects/${o}/users/${e}`,{body:s,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/projects/${e}/users`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{project_id:o}=r;return this._client.delete(p`/organization/projects/${o}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Ut.Roles=on;var ie=class extends y{constructor(){super(...arguments),this.users=new Ut(this._client),this.serviceAccounts=new tn(this._client),this.apiKeys=new Gr(this._client),this.rateLimits=new Xr(this._client),this.modelPermissions=new Yr(this._client),this.hostedToolPermissions=new Qr(this._client),this.groups=new zt(this._client),this.roles=new en(this._client),this.dataRetention=new Zr(this._client),this.spendAlerts=new rn(this._client),this.certificates=new Jr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(p`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/projects/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(p`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};ie.Users=Ut;ie.ServiceAccounts=tn;ie.APIKeys=Gr;ie.RateLimits=Xr;ie.ModelPermissions=Yr;ie.HostedToolPermissions=Qr;ie.Groups=zt;ie.Roles=en;ie.DataRetention=Zr;ie.SpendAlerts=rn;ie.Certificates=Jr;var sn=class extends y{create(e,r,n){return this._client.post(p`/organization/users/${e}/roles`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,n){let{user_id:o}=r;return this._client.get(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/organization/users/${e}/roles`,Y,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{user_id:o}=r;return this._client.delete(p`/organization/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends y{constructor(){super(...arguments),this.roles=new sn(this._client)}retrieve(e,r){return this._client.get(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,n){return this._client.post(p`/organization/users/${e}`,{body:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",D,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(p`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};qt.Roles=sn;var ae=class extends y{constructor(){super(...arguments),this.auditLogs=new jr(this._client),this.adminAPIKeys=new Fr(this._client),this.usage=new Wr(this._client),this.invites=new qr(this._client),this.users=new qt(this._client),this.groups=new gt(this._client),this.roles=new Br(this._client),this.dataRetention=new Ur(this._client),this.spendAlerts=new Kr(this._client),this.certificates=new zr(this._client),this.projects=new ie(this._client)}};ae.AuditLogs=jr;ae.AdminAPIKeys=Fr;ae.Usage=Wr;ae.Invites=qr;ae.Users=qt;ae.Groups=gt;ae.Roles=Br;ae.DataRetention=Ur;ae.SpendAlerts=Kr;ae.Certificates=zr;ae.Projects=ie;var yt=class extends y{constructor(){super(...arguments),this.organization=new ae(this._client)}};yt.Organization=ae;var uu=Symbol("brand.privateNullableHeaders");function*Gf(t){if(!t)return;if(uu 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():Vi(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=Vi(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var T=t=>{let e=new Headers,r=new Set;for(let n of t){let o=new Set;for(let[s,i]of Gf(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),r.add(a)):(e.append(s,i),r.delete(a))}}return{[uu]:!0,values:e,nulls:r}};var an=class extends y{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:T([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ln=class extends y{create(e,r){return this._client.post("/audio/transcriptions",pe({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var cn=class extends y{create(e,r){return this._client.post("/audio/translations",pe({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var De=class extends y{constructor(){super(...arguments),this.transcriptions=new ln(this._client),this.translations=new cn(this._client),this.speech=new an(this._client)}};De.Transcriptions=ln;De.Translations=cn;De.Speech=an;var Bt=class extends y{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var un=class extends y{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/assistants/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/assistants/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var dn=class extends y{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var pn=class extends y{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var _t=class extends y{constructor(){super(...arguments),this.sessions=new dn(this._client),this.transcriptionSessions=new pn(this._client)}};_t.Sessions=dn;_t.TranscriptionSessions=pn;var mn=class extends y{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/chatkit/sessions/${e}/cancel`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var fn=class extends y{retrieve(e,r){return this._client.get(p`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",D,{query:e,...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/chatkit/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},n){return this._client.getAPIList(p`/chatkit/threads/${e}/items`,D,{query:r,...n,headers:T([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var wt=class extends y{constructor(){super(...arguments),this.sessions=new mn(this._client),this.threads=new fn(this._client)}};wt.Sessions=mn;wt.Threads=fn;var hn=class extends y{create(e,r,n){return this._client.post(p`/threads/${e}/messages`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/messages/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/messages`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{thread_id:o}=r;return this._client.delete(p`/threads/${o}/messages/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var gn=class extends y{retrieve(e,r,n){let{thread_id:o,run_id:s,...i}=r;return this._client.get(p`/threads/${o}/runs/${s}/steps/${e}`,{query:i,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r,n){let{thread_id:o,...s}=r;return this._client.getAPIList(p`/threads/${o}/runs/${e}/steps`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var du=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 ve=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var le,Wt,Ca,Fe,vs,Ie,Ht,yn,Kt,Ss,we,Is,Ts,To,vo,Io,pu,mu,fu,hu,gu,yu,_u,Ve=class extends mt{constructor(){super(...arguments),le.add(this),Ca.set(this,[]),Fe.set(this,{}),vs.set(this,{}),Ie.set(this,void 0),Ht.set(this,void 0),yn.set(this,void 0),Kt.set(this,void 0),Ss.set(this,void 0),we.set(this,void 0),Is.set(this,void 0),Ts.set(this,void 0),To.set(this,void 0)}[(Ca=new WeakMap,Fe=new WeakMap,vs=new WeakMap,Ie=new WeakMap,Ht=new WeakMap,yn=new WeakMap,Kt=new WeakMap,Ss=new WeakMap,we=new WeakMap,Is=new WeakMap,Ts=new WeakMap,To=new WeakMap,le=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,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Wt;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=Le.fromReadableStream(e,this.controller);for await(let s of o)_(this,le,"m",vo).call(this,s);if(o.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",Io).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,o){let s=new Wt;return s._run(()=>s._runToolAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...o,signal:this.controller.signal});this._connected();for await(let c of a)_(this,le,"m",vo).call(this,c);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",Io).call(this))}static createThreadAssistantStream(e,r,n){let o=new Wt;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 Wt;return s._run(()=>s._runAssistantStream(e,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return _(this,Is,"f")}currentRun(){return _(this,Ts,"f")}currentMessageSnapshot(){return _(this,Ie,"f")}currentRunStepSnapshot(){return _(this,To,"f")}async finalRunSteps(){return await this.done(),Object.values(_(this,Fe,"f"))}async finalMessages(){return await this.done(),Object.values(_(this,vs,"f"))}async finalRun(){if(await this.done(),!_(this,Ht,"f"))throw Error("Final run was not received.");return _(this,Ht,"f")}async _createThreadAssistantStream(e,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},i=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of i)_(this,le,"m",vo).call(this,a);if(i.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",Io).call(this))}async _createAssistantStream(e,r,n,o){let s=o?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...o,signal:this.controller.signal});this._connected();for await(let c of a)_(this,le,"m",vo).call(this,c);if(a.controller.signal?.aborted)throw new H;return this._addRun(_(this,le,"m",Io).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(io(s)&&io(o))s=this.accumulateDelta(s,o);else if(Array.isArray(s)&&Array.isArray(o)){if(s.every(i=>typeof i=="string"||typeof i=="number")){s.push(...o);continue}for(let i of o){if(!io(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s.push(i):s[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,o){return await this._createAssistantStream(r,e,n,o)}async _runToolAssistantStream(e,r,n,o){return await this._createToolAssistantStream(r,e,n,o)}};Wt=Ve,vo=function(e){if(!this.ended)switch(E(this,Is,e,"f"),_(this,le,"m",fu).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":_(this,le,"m",_u).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":_(this,le,"m",mu).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":_(this,le,"m",pu).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Io=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");if(!_(this,Ht,"f"))throw Error("Final run has not been received");return _(this,Ht,"f")},pu=function(e){let[r,n]=_(this,le,"m",gu).call(this,e,_(this,Ie,"f"));E(this,Ie,r,"f"),_(this,vs,"f")[r.id]=r;for(let o of n){let s=r.content[o.index];s?.type=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let s=o.text,i=r.content[o.index];if(i&&i.type=="text")this._emit("textDelta",s,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=_(this,yn,"f")){if(_(this,Kt,"f"))switch(_(this,Kt,"f").type){case"text":this._emit("textDone",_(this,Kt,"f").text,_(this,Ie,"f"));break;case"image_file":this._emit("imageFileDone",_(this,Kt,"f").image_file,_(this,Ie,"f"));break}E(this,yn,o.index,"f")}E(this,Kt,r.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(_(this,yn,"f")!==void 0){let o=e.data.content[_(this,yn,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,_(this,Ie,"f"));break;case"text":this._emit("textDone",o.text,_(this,Ie,"f"));break}}_(this,Ie,"f")&&this._emit("messageDone",e.data),E(this,Ie,void 0,"f")}},mu=function(e){let r=_(this,le,"m",hu).call(this,e);switch(E(this,To,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==_(this,Ss,"f")?this._emit("toolCallDelta",s,r.step_details.tool_calls[s.index]):(_(this,we,"f")&&this._emit("toolCallDone",_(this,we,"f")),E(this,Ss,s.index,"f"),E(this,we,r.step_details.tool_calls[s.index],"f"),_(this,we,"f")&&this._emit("toolCallCreated",_(this,we,"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":E(this,To,void 0,"f"),e.data.step_details.type=="tool_calls"&&_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),E(this,we,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},fu=function(e){_(this,Ca,"f").push(e),this._emit("event",e)},hu=function(e){switch(e.event){case"thread.run.step.created":return _(this,Fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=_(this,Fe,"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=Wt.accumulateDelta(r,n.delta);_(this,Fe,"f")[e.data.id]=o}return _(this,Fe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":_(this,Fe,"f")[e.data.id]=e.data;break}if(_(this,Fe,"f")[e.data.id])return _(this,Fe,"f")[e.data.id];throw new Error("No snapshot available")},gu=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let s of o.delta.content)if(s.index in r.content){let i=r.content[s.index];r.content[s.index]=_(this,le,"m",yu).call(this,s,i)}else r.content[s.index]=s,n.push(s);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},yu=function(e,r){return Wt.accumulateDelta(r,e)},_u=function(e){switch(E(this,Ts,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":E(this,Ht,e.data,"f"),_(this,we,"f")&&(this._emit("toolCallDone",_(this,we,"f")),E(this,we,void 0,"f"));break;case"thread.run.cancelling":break}};var Vt=class extends y{constructor(){super(...arguments),this.steps=new gn(this._client)}create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/threads/${e}/runs`,{query:{include:o},body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{thread_id:o}=r;return this._client.get(p`/threads/${o}/runs/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/threads/${e}/runs`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{thread_id:o}=r;return this._client.post(p`/threads/${o}/runs/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(o.id,{thread_id:e},n)}createAndStream(e,r,n){return Ve.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...o}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,r,n){return Ve.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:o,...s}=r;return this._client.post(p`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,n){let o=await this.submitToolOutputs(e,r,n);return await this.poll(o.id,r,n)}submitToolOutputsStream(e,r,n){return Ve.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Vt.Steps=gn;var bt=class extends y{constructor(){super(...arguments),this.runs=new Vt(this._client),this.messages=new hn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/threads/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/threads/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ve.createThreadAssistantStream(e,this._client.beta.threads,r)}};bt.Runs=Vt;bt.Messages=hn;var Te=class extends y{constructor(){super(...arguments),this.realtime=new _t(this._client),this.chatkit=new wt(this._client),this.assistants=new un(this._client),this.threads=new bt(this._client)}};Te.Realtime=_t;Te.ChatKit=wt;Te.Assistants=un;Te.Threads=bt;var Gt=class extends y{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var _n=class extends y{retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Jt=class extends y{constructor(){super(...arguments),this.content=new _n(this._client)}create(e,r,n){return this._client.post(p`/containers/${e}/files`,pt({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{container_id:o}=r;return this._client.get(p`/containers/${o}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/containers/${e}/files`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{container_id:o}=r;return this._client.delete(p`/containers/${o}/files/${e}`,{...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Jt.Content=_n;var At=class extends y{constructor(){super(...arguments),this.files=new Jt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/containers/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};At.Files=Jt;var wn=class extends y{create(e,r,n){let{include:o,...s}=r;return this._client.post(p`/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(p`/conversations/${o}/items/${e}`,{query:s,...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/conversations/${e}/items`,D,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{conversation_id:o}=r;return this._client.delete(p`/conversations/${o}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var xt=class extends y{constructor(){super(...arguments),this.items=new wn(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/conversations/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};xt.Items=wn;var Zt=class extends y{create(e,r){let n=!!e.encoding_format,o=n?e.encoding_format:"base64";n&&Z(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:(Z(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=du(c)}),i)))}};var bn=class extends y{retrieve(e,r,n){let{eval_id:o,run_id:s}=r;return this._client.get(p`/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(p`/evals/${o}/runs/${e}/output_items`,R,{query:s,...n,__security:{bearerAuth:!0}})}};var Qt=class extends y{constructor(){super(...arguments),this.outputItems=new bn(this._client)}create(e,r,n){return this._client.post(p`/evals/${e}/runs`,{body:r,...n,__security:{bearerAuth:!0}})}retrieve(e,r,n){let{eval_id:o}=r;return this._client.get(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/evals/${e}/runs`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{eval_id:o}=r;return this._client.delete(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,r,n){let{eval_id:o}=r;return this._client.post(p`/evals/${o}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Qt.OutputItems=bn;var vt=class extends y{constructor(){super(...arguments),this.runs=new Qt(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/evals/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};vt.Runs=Qt;var Yt=class extends y{create(e,r){return this._client.post("/files",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(p`/files/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let o=new Set(["processed","error","deleted"]),s=Date.now(),i=await this.retrieve(e);for(;!i.status||!o.has(i.status);)if(await $e(r),i=await this.retrieve(e),Date.now()-s>n)throw new Me({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var An=class extends y{};var xn=class extends y{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var Xt=class extends y{constructor(){super(...arguments),this.graders=new xn(this._client)}};Xt.Graders=xn;var vn=class extends y{create(e,r,n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,de,{body:r,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},n){return this._client.get(p`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/checkpoints/${e}/permissions`,D,{query:r,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,r,n){let{fine_tuned_model_checkpoint:o}=r;return this._client.delete(p`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var er=class extends y{constructor(){super(...arguments),this.permissions=new vn(this._client)}};er.Permissions=vn;var In=class extends y{list(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var tr=class extends y{constructor(){super(...arguments),this.checkpoints=new In(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(p`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},n){return this._client.getAPIList(p`/fine_tuning/jobs/${e}/events`,R,{query:r,...n,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(p`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};tr.Checkpoints=In;var Se=class extends y{constructor(){super(...arguments),this.methods=new An(this._client),this.jobs=new tr(this._client),this.checkpoints=new er(this._client),this.alpha=new Xt(this._client)}};Se.Methods=An;Se.Jobs=tr;Se.Checkpoints=er;Se.Alpha=Xt;var Tn=class extends y{};var It=class extends y{constructor(){super(...arguments),this.graderModels=new Tn(this._client)}};It.GraderModels=Tn;var rr=class extends y{createVariation(e,r){return this._client.post("/images/variations",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",pe({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 nr=class extends y{retrieve(e,r){return this._client.get(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",de,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var or=class extends y{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Sn=class extends y{accept(e,r,n){return this._client.post(p`/realtime/calls/${e}/accept`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(p`/realtime/calls/${e}/hangup`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,n){return this._client.post(p`/realtime/calls/${e}/refer`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},n){return this._client.post(p`/realtime/calls/${e}/reject`,{body:r,...n,headers:T([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var Cn=class extends y{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Ge=class extends y{constructor(){super(...arguments),this.clientSecrets=new Cn(this._client),this.calls=new Sn(this._client)}};Ge.ClientSecrets=Cn;Ge.Calls=Sn;function wu(t,e){return!e||!Th(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:Ea(t,e)}function Ea(t,e){let r=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:Eh(e,o)};if(o.type==="message"){let s=o.content.map(i=>i.type==="output_text"?{...i,parsed:Ih(e,i.text)}:i);return{...o,content:s}}return o}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||So(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let s of o.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function Ih(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Th(t){return!!ho(t.text?.format)}function Sh(t){return t?.$brand==="auto-parseable-tool"}function Ch(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Eh(t,e){let r=Ch(t.tools??[],e.name);return{...e,...e,parsed_arguments:Sh(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function So(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var En,Cs,Tt,Es,bu,Au,xu,vu,ks=class t extends mt{constructor(e){super(),En.add(this),Cs.set(this,void 0),Tt.set(this,void 0),Es.set(this,void 0),E(this,Cs,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){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_(this,En,"m",bu).call(this);let s,i=null;"response_id"in r?(s=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=r.starting_after??null):s=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)_(this,En,"m",Au).call(this,a,i);if(s.controller.signal?.aborted)throw new H;return _(this,En,"m",xu).call(this)}[(Cs=new WeakMap,Tt=new WeakMap,Es=new WeakMap,En=new WeakSet,bu=function(){this.ended||E(this,Tt,void 0,"f")},Au=function(r,n){if(this.ended)return;let o=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},s=_(this,En,"m",vu).call(this,r);switch(o("event",r),r.type){case"response.output_text.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new C(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new C(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=s.output[r.output_index];if(!i)throw new C(`missing output at index ${r.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:o(r.type,r);break}},xu=function(){if(this.ended)throw new C("stream has ended, this shouldn't happen");let r=_(this,Tt,"f");if(!r)throw new C("request ended without sending any events");E(this,Tt,void 0,"f");let n=kh(r,_(this,Cs,"f"));return E(this,Es,n,"f"),n},vu=function(r){let n=_(this,Tt,"f");if(!n){if(r.type!=="response.created")throw new C(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=E(this,Tt,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);let s=o.type,i=r.part;s==="message"&&i.type!=="reasoning_text"?o.content.push(i):s==="reasoning"&&i.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(i));break}case"response.output_text.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);if(o.type==="message"){let s=o.content[r.content_index];if(!s)throw new C(`missing content at index ${r.content_index}`);if(s.type!=="output_text")throw new C(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta}break}case"response.function_call_arguments.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);o.type==="function_call"&&(o.arguments+=r.delta);break}case"response.reasoning_text.delta":{let o=n.output[r.output_index];if(!o)throw new C(`missing output at index ${r.output_index}`);if(o.type==="reasoning"){let s=o.content?.[r.content_index];if(!s)throw new C(`missing content at index ${r.content_index}`);if(s.type!=="reasoning_text")throw new C(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.completed":{E(this,Tt,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let s=r.shift();s?s.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let s of r)s.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,i)=>r.push({resolve:s,reject:i})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=_(this,Es,"f");if(!e)throw new C("stream ended without producing a ChatCompletion");return e}};function kh(t,e){return wu(t,e)}var kn=class extends y{list(e,r={},n){return this._client.getAPIList(p`/responses/${e}/input_items`,R,{query:r,...n,__security:{bearerAuth:!0}})}};var On=class extends y{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var je=class extends y{constructor(){super(...arguments),this.inputItems=new kn(this._client),this.inputTokens=new On(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"&&So(n),n))}retrieve(e,r={},n){return this._client.get(p`/responses/${e}`,{query:r,...n,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&So(o),o))}delete(e,r){return this._client.delete(p`/responses/${e}`,{...r,headers:T([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>Ea(n,e))}stream(e,r){return ks.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(p`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};je.InputItems=kn;je.InputTokens=On;var Pn=class extends y{retrieve(e,r){return this._client.get(p`/skills/${e}/content`,{...r,headers:T([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Mn=class extends y{retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}/content`,{...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var sr=class extends y{constructor(){super(...arguments),this.content=new Mn(this._client)}create(e,r={},n){return this._client.post(p`/skills/${e}/versions`,pt({body:r,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,n){let{skill_id:o}=r;return this._client.get(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/skills/${e}/versions`,R,{query:r,...n,__security:{bearerAuth:!0}})}delete(e,r,n){let{skill_id:o}=r;return this._client.delete(p`/skills/${o}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};sr.Content=Mn;var Je=class extends y{constructor(){super(...arguments),this.content=new Pn(this._client),this.versions=new sr(this._client)}create(e={},r){return this._client.post("/skills",pt({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/skills/${e}`,{body:r,...n,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};Je.Content=Pn;Je.Versions=sr;var Rn=class extends y{create(e,r,n){return this._client.post(p`/uploads/${e}/parts`,pe({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var St=class extends y{constructor(){super(...arguments),this.parts=new Rn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(p`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,n){return this._client.post(p`/uploads/${e}/complete`,{body:r,...n,__security:{bearerAuth:!0}})}};St.Parts=Rn;var Iu=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 $n=class extends y{create(e,r,n){return this._client.post(p`/vector_stores/${e}/file_batches`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/file_batches/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,n){let{vector_store_id:o}=r;return this._client.post(p`/vector_stores/${o}/file_batches/${e}/cancel`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r);return await this.poll(e,o.id,n)}listFiles(e,r,n){let{vector_store_id:o,...s}=r;return this._client.getAPIList(p`/vector_stores/${o}/file_batches/${e}/files`,R,{query:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:s,response:i}=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},o){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=o?.maxConcurrency??5,i=Math.min(s,r.length),a=this._client,c=r.values(),l=[...n];async function u(f){for(let h of f){let w=await a.files.create({file:h,purpose:"assistants"},o);l.push(w.id)}}let m=Array(i).fill(c).map(u);return await Iu(m),await this.createAndPoll(e,{file_ids:l})}};var Nn=class extends y{create(e,r,n){return this._client.post(p`/vector_stores/${e}/files`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,n){let{vector_store_id:o}=r;return this._client.get(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){let{vector_store_id:o,...s}=r;return this._client.post(p`/vector_stores/${o}/files/${e}`,{body:s,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,r={},n){return this._client.getAPIList(p`/vector_stores/${e}/files`,R,{query:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,r,n){let{vector_store_id:o}=r;return this._client.delete(p`/vector_stores/${o}/files/${e}`,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,n){let o=await this.create(e,r,n);return await this.poll(e,o.id,n)}async poll(e,r,n){let o=T([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let s=await this.retrieve(r,{vector_store_id:e},{...n,headers:o}).withResponse(),i=s.data;switch(i.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await $e(a);break;case"failed":case"completed":return i}}}async upload(e,r,n){let o=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:o.id},n)}async uploadAndPoll(e,r,n){let o=await this.upload(e,r,n);return await this.poll(e,o.id,n)}content(e,r,n){let{vector_store_id:o}=r;return this._client.getAPIList(p`/vector_stores/${o}/files/${e}/content`,de,{...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Ze=class extends y{constructor(){super(...arguments),this.files=new Nn(this._client),this.fileBatches=new $n(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,n){return this._client.post(p`/vector_stores/${e}`,{body:r,...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",R,{query:e,...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/vector_stores/${e}`,{...r,headers:T([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,n){return this._client.getAPIList(p`/vector_stores/${e}/search`,de,{body:r,method:"post",...n,headers:T([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};Ze.Files=Nn;Ze.FileBatches=$n;var ir=class extends y{create(e,r){return this._client.post("/videos",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",D,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(p`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},n){return this._client.get(p`/videos/${e}/content`,{query:r,...n,headers:T([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",pe({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(p`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,n){return this._client.post(p`/videos/${e}/remix`,pt({body:r,...n,__security:{bearerAuth:!0}},this._client))}};var Ln,Tu,Os,ar=class extends y{constructor(){super(...arguments),Ln.add(this)}async unwrap(e,r,n=this._client.webhookSecret,o=300){return await this.verifySignature(e,r,n,o),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");_(this,Ln,"m",Tu).call(this,n);let s=T([r]).values,i=_(this,Ln,"m",Os).call(this,s,"webhook-signature"),a=_(this,Ln,"m",Os).call(this,s,"webhook-timestamp"),c=_(this,Ln,"m",Os).call(this,s,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new Re("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>o)throw new Re("Webhook timestamp is too old");if(l>u+o)throw new Re("Webhook timestamp is too new");let m=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=c?`${c}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of m)try{let v=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",w,v,new TextEncoder().encode(h)))return}catch{continue}throw new Re("The given webhook signature does not match the expected signature")}};Ln=new WeakSet,Tu=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")},Os=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 ka,Oa,Ps,Cu,Fh="workload-identity-auth",O=class{constructor({baseURL:e=ve("OPENAI_BASE_URL"),apiKey:r=ve("OPENAI_API_KEY")??null,adminAPIKey:n=ve("OPENAI_ADMIN_KEY")??null,organization:o=ve("OPENAI_ORG_ID")??null,project:s=ve("OPENAI_PROJECT_ID")??null,webhookSecret:i=ve("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:a,...c}={}){ka.add(this),Ps.set(this,void 0),this.completions=new Gt(this),this.chat=new ht(this),this.embeddings=new Zt(this),this.files=new Yt(this),this.images=new rr(this),this.audio=new De(this),this.moderations=new or(this),this.models=new nr(this),this.fineTuning=new Se(this),this.graders=new It(this),this.vectorStores=new Ze(this),this.webhooks=new ar(this),this.beta=new Te(this),this.batches=new Bt(this),this.uploads=new St(this),this.admin=new yt(this),this.responses=new je(this),this.realtime=new Ge(this),this.conversations=new xt(this),this.evals=new vt(this),this.containers=new At(this),this.skills=new Je(this),this.videos=new ir(this);let l={apiKey:r,adminAPIKey:n,organization:o,project:s,webhookSecret:i,workloadIdentity:a,...c,baseURL:e||"https://api.openai.com/v1"};if(r&&a)throw new C("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!r&&!n&&!a)throw new C("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&kc())throw new C(`It looks like you're running in a browser-like environment.
|
|
52
|
-
|
|
53
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
54
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
55
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
56
|
-
|
|
57
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
58
|
-
|
|
59
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
60
|
-
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Oa.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=sa(l.logLevel,"ClientOptions.logLevel",this)??sa(ve("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ss(),E(this,Ps,Mc,"f");let m=ve("OPENAI_CUSTOM_HEADERS");if(m){let f={};for(let h of m.split(`
|
|
61
|
-
`)){let w=h.indexOf(":");w>=0&&(f[h.substring(0,w).trim()]=h.substring(w+1).trim())}l.defaultHeaders=T([f,l.defaultHeaders])}this._options=l,a&&(this._workloadIdentityAuth=new ps(a,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=n,this.organization=o,this.project=s,this.webhookSecret=i}withOptions(e){return new this.constructor({...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,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return T([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return T([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return T([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return T([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Uc(e)}getUserAgent(){return`${this.constructor.name}/JS ${dt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hi()}`}makeStatusError(e,r,n,o){return W.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof C?n:new C(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new C(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!_(this,ka,"m",Cu).call(this)&&n||this.baseURL,s=xc(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!Gi(i)||!Gi(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){(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 Lt(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,s=o.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(o);let{req:i,url:a,timeout:c}=await this.buildRequest(o,{retryCount:s-r});await this.prepareRequest(i,{url:a,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if(Z(this).debug(`[${l}] sending request`,Be({retryOfRequestLogID:n,method:o.method,url:a,options:o,headers:i.headers})),o.signal?.aborted)throw new H;let f=o.__security??{bearerAuth:!0},h=new AbortController,w=await this.fetchWithAuth(a,i,c,h,f).catch(oo),b=Date.now();if(w instanceof globalThis.Error){let x=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new H;let S=no(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(r)return Z(this).info(`[${l}] connection ${S?"timed out":"failed"} - ${x}`),Z(this).debug(`[${l}] connection ${S?"timed out":"failed"} (${x})`,Be({retryOfRequestLogID:n,url:a,durationMs:b-m,message:w.message})),this.retryRequest(o,r,n??l);throw Z(this).info(`[${l}] connection ${S?"timed out":"failed"} - error; no more retries left`),Z(this).debug(`[${l}] connection ${S?"timed out":"failed"} (error; no more retries left)`,Be({retryOfRequestLogID:n,url:a,durationMs:b-m,message:w.message})),w instanceof $t||w instanceof so?w:S?new Me:new ut({message:jh(w),cause:w})}let v=[...w.headers.entries()].filter(([x])=>x==="x-request-id").map(([x,S])=>", "+x+": "+JSON.stringify(S)).join(""),g=`[${l}${u}${v}] ${i.method} ${a} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${b-m}ms`;if(!w.ok){if(w.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Qi(w.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},r,n??l);let x=await this.shouldRetry(w);if(r&&x){let q=`retrying, ${r} attempts remaining`;return await Qi(w.body),Z(this).info(`${g} - ${q}`),Z(this).debug(`[${l}] response error (${q})`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),this.retryRequest(o,r,n??l,w.headers)}let S=x?"error; no more retries left":"error; not retryable";Z(this).info(`${g} - ${S}`);let $=await w.text().catch(q=>oo(q).message),z=Tc($),P=z?void 0:$;throw Z(this).debug(`[${l}] response error (${S})`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:P,durationMs:Date.now()-m})),this.makeStatusError(w.status,z,P,w.headers)}return Z(this).info(g),Z(this).debug(`[${l}] response start`,Be({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:b-m})),{response:w,options:o,controller:h,requestLogID:l,retryOfRequestLogID:n,startTime:m}}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 uo(this,n,e)}async fetchWithAuth(e,r,n,o,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){let a=r.headers,c=a.get("Authorization");if(!c||c===`Bearer ${Fh}`){let l=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,r,n,o)}async fetchWithTimeout(e,r,n,o){let{signal:s,method:i,...a}=r||{},c=this._makeAbort(o);s&&s.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,m={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,o){let s,i=o?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(s=c)}let a=o?.get("retry-after");if(a&&!s){let c=parseFloat(a);Number.isNaN(c)?s=Date.parse(a)-Date.now():s=c*1e3}if(s===void 0){let c=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,c)}return await $e(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,i=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:o,path:s,query:i,defaultBaseURL:a}=n,c=this.buildURL(s,i,a);"timeout"in n&&Ic("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u,isStreamingBody:m}=this.buildBody({options:n});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:l,retryCount:r});return{req:{method:o,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let i=T([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Oc(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=T([r]),o=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,s=!o&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||o?{bodyHeaders:void 0,body:e,isStreamingBody:!s}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:is(e),isStreamingBody:!0}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{..._(this,Ps,"f").call(this,{body:e,headers:n}),isStreamingBody:!1}}};Oa=O,Ps=new WeakMap,ka=new WeakSet,Cu=function(){return this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=Oa;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=C;O.APIError=W;O.APIConnectionError=ut;O.APIConnectionTimeoutError=Me;O.APIUserAbortError=H;O.NotFoundError=Ir;O.ConflictError=Tr;O.RateLimitError=Cr;O.BadRequestError=Ar;O.AuthenticationError=xr;O.InternalServerError=Er;O.PermissionDeniedError=vr;O.UnprocessableEntityError=Sr;O.InvalidWebhookSignatureError=Re;O.toFile=mo;O.Completions=Gt;O.Chat=ht;O.Embeddings=Zt;O.Files=Yt;O.Images=rr;O.Audio=De;O.Moderations=or;O.Models=nr;O.FineTuning=Se;O.Graders=It;O.VectorStores=Ze;O.Webhooks=ar;O.Beta=Te;O.Batches=Bt;O.Uploads=St;O.Admin=yt;O.Responses=je;O.Realtime=Ge;O.Conversations=xt;O.Evals=vt;O.Containers=At;O.Skills=Je;O.Videos=ir;function jh(t){if(zh(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 zh(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 Uh(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===Me.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===H.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):Uh(t)?e=zl.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=ro(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=ro(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=ro(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=ro(t,"MODEL_NOT_FOUND"):e=t,e}var Ce=t=>t();function Qe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function qh(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 Ms(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var Bh="LC_AUTOGENERATED";function lr(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'."),Bh)}function Ye(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(!Ko.isInstance(t))throw new Error("Invalid generic chat message");return qh(t);default:throw new Error(`Unknown message type: ${e}`)}}function Eu(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function Xe(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:s,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((n||i)&&o&&e)return`${o}/${e}`;if((n||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(n||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return s}function Ma(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function ku(t){let e=Ce(()=>{if(Ma(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ma(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 Ou(){let t=jl();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function et(t,e=!1,r="1.0.0"){let n=ku(t),o=Ou(),s=`langchainjs${e?"-azure":""}-openai`;return{...n,"User-Agent":n["User-Agent"]?`${s}/${r} (${o})${n["User-Agent"]}`:`${s}/${r} (${o})`}}function Pu(t,e){let r;return _r(t)?r=Pi(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function Kh(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Mu(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(Ru(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
62
|
-
`)}function Ru(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}: ${Rs(o,e)},`):r.push(`${n}?: ${Rs(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
|
|
63
|
-
`)}function Rs(t,e){if(Kh(t))return t.anyOf.map(r=>Rs(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["{",Ru(t,e+2),"}"].join(`
|
|
64
|
-
`);case"array":return t.items?`${Rs(t.items,e)}[]`:"any[]";default:return""}}function $s(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 Dn(t){return"type"in t&&t.type!=="function"}function $u(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 Nu(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function cr(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 Ns(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Lu(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 Du(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 Fu(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function ju(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 zu(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 Uu(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 Bu=Symbol("Let zodToJsonSchema decide on which parser to use"),qu={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"},Ku=t=>typeof t=="string"?{...qu,basePath:["#"],definitions:{},name:t}:{...qu,basePath:["#"],definitions:{},...t};var Co=t=>"_def"in t?t._def:t;function Wu(t){if(!t)return!0;for(let e in t)return!1;return!0}var Hu=t=>{let e=Ku(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])=>[Co(o),{def:Co(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Ra(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function F(t,e,r,n,o){t[e]=r,Ra(t,e,n,o)}function Vu(){return{}}function Gu(t,e){let r={type:"array"};return t.type?._def?.typeName!==N.ZodAny&&(r.items=M(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&F(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&F(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(F(r,"minItems",t.exactLength.value,t.exactLength.message,e),F(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Ju(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?F(r,"minimum",n.value,n.message,e):F(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),F(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?F(r,"maximum",n.value,n.message,e):F(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),F(r,"maximum",n.value,n.message,e));break;case"multipleOf":F(r,"multipleOf",n.value,n.message,e);break}return r}function Zu(){return{type:"boolean"}}function Qu(t,e){return M(t.type._def,e)}var Yu=(t,e)=>M(t.innerType._def,e);function $a(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>$a(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 Wh(t,e)}}var Wh=(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":F(r,"minimum",n.value,n.message,e);break;case"max":F(r,"maximum",n.value,n.message,e);break}return r};function Xu(t,e){return{...M(t.innerType._def,e),default:t.defaultValue()}}function ed(t,e,r){return e.effectStrategy==="input"?M(t.schema._def,e,r):{}}function td(t){return{type:"string",enum:[...t.values]}}var Hh=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function rd(t,e){let r=[M(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),M(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(Hh(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function nd(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 Na,ur={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:()=>(Na===void 0&&(Na=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Na),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 Ls(t,e){let r={type:"string"};function n(o){return e.patternStrategy==="escape"?Vh(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":F(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":F(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":Ee(r,"email",o.message,e);break;case"format:idn-email":Ee(r,"idn-email",o.message,e);break;case"pattern:zod":ke(r,ur.email,o.message,e);break}break;case"url":Ee(r,"uri",o.message,e);break;case"uuid":Ee(r,"uuid",o.message,e);break;case"regex":ke(r,o.regex,o.message,e);break;case"cuid":ke(r,ur.cuid,o.message,e);break;case"cuid2":ke(r,ur.cuid2,o.message,e);break;case"startsWith":ke(r,RegExp(`^${n(o.value)}`),o.message,e);break;case"endsWith":ke(r,RegExp(`${n(o.value)}$`),o.message,e);break;case"datetime":Ee(r,"date-time",o.message,e);break;case"date":Ee(r,"date",o.message,e);break;case"time":Ee(r,"time",o.message,e);break;case"duration":Ee(r,"duration",o.message,e);break;case"length":F(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),F(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ke(r,RegExp(n(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ee(r,"ipv4",o.message,e),o.version!=="v4"&&Ee(r,"ipv6",o.message,e);break}case"emoji":ke(r,ur.emoji,o.message,e);break;case"ulid":{ke(r,ur.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ee(r,"binary",o.message,e);break}case"contentEncoding:base64":{F(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ke(r,ur.base64,o.message,e);break}}break}case"nanoid":ke(r,ur.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var Vh=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ee=(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}}})):F(t,"format",e,r,n)},ke=(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:od(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):F(t,"pattern",od(e,n),r,n)},od=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let n={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},o=n.i?r.source.toLowerCase():r.source,s="",i=!1,a=!1,c=!1;for(let l=0;l<o.length;l++){if(i){s+=o[l],i=!1;continue}if(n.i){if(a){if(o[l].match(/[a-z]/)){c?(s+=o[l],s+=`${o[l-2]}-${o[l]}`.toUpperCase(),c=!1):o[l+1]==="-"&&o[l+2]?.match(/[a-z]/)?(s+=o[l],c=!0):s+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){s+=`[${o[l]}${o[l].toUpperCase()}]`;continue}}if(n.m){if(o[l]==="^"){s+=`(^|(?<=[\r
|
|
65
|
-
]))`;continue}else if(o[l]==="$"){s+=`($|(?=[\r
|
|
66
|
-
]))`;continue}}if(n.s&&o[l]==="."){s+=a?`${o[l]}\r
|
|
67
|
-
`:`[${o[l]}\r
|
|
68
|
-
]`;continue}s+=o[l],o[l]==="\\"?i=!0:a&&o[l]==="]"?a=!1:!a&&o[l]==="["&&(a=!0)}try{let l=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return s};function Ds(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Ls(t.keyType._def,e)).reduce((o,[s,i])=>s==="type"?o:{...o,[s]:i},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function sd(t,e){if(e.mapStrategy==="record")return Ds(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function id(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 ad(){return{not:{}}}function ld(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Eo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ud(t,e){if(e.target==="openApi3")return cd(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Eo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Eo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return cd(t,e)}var cd=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function dd(t,e){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:Eo[t.innerType._def.typeName],nullable:!0}:{type:[Eo[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function pd(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",Ra(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?F(r,"minimum",n.value,n.message,e):F(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),F(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?F(r,"maximum",n.value,n.message,e):F(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),F(r,"maximum",n.value,n.message,e));break;case"multipleOf":F(r,"multipleOf",n.value,n.message,e);break}return r}function Gh(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":M(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function md(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,s])=>{if(s===void 0||s._def===void 0)return n;let i=[...e.currentPath,"properties",o],a=M(s._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return n;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof s._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...n.properties,[o]:a},required:s.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]}},{properties:{},required:[]}),additionalProperties:Gh(t,e)};return r.required.length||delete r.required,r}var fd=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return M(t.innerType._def,{...e,currentPath:e.currentPath});let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var hd=(t,e)=>{if(e.pipeStrategy==="input")return M(t.in._def,e);if(e.pipeStrategy==="output")return M(t.out._def,e);let r=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function gd(t,e){return M(t.type._def,e)}function yd(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&F(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&F(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function _d(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function wd(){return{not:{}}}function bd(){return{}}var Ad=(t,e)=>M(t.innerType._def,e);function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let i=e.override?.(t,e,n,r);if(i!==Bu)return i}if(n&&!r){let i=Jh(n,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Qh(t,t.typeName,e,r);return s&&Yh(t,e,s),o.jsonSchema=s,s}var Jh=(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).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:Zh(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}},Zh=(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("/")},Qh=(t,e,r,n)=>{switch(e){case N.ZodString:return Ls(t,r);case N.ZodNumber:return pd(t,r);case N.ZodObject:return md(t,r);case N.ZodBigInt:return Ju(t,r);case N.ZodBoolean:return Zu();case N.ZodDate:return $a(t,r);case N.ZodUndefined:return wd();case N.ZodNull:return ld(r);case N.ZodArray:return Gu(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return ud(t,r);case N.ZodIntersection:return rd(t,r);case N.ZodTuple:return _d(t,r);case N.ZodRecord:return Ds(t,r);case N.ZodLiteral:return nd(t,r);case N.ZodEnum:return td(t);case N.ZodNativeEnum:return id(t);case N.ZodNullable:return dd(t,r);case N.ZodOptional:return fd(t,r);case N.ZodMap:return sd(t,r);case N.ZodSet:return yd(t,r);case N.ZodLazy:return M(t.getter()._def,r);case N.ZodPromise:return gd(t,r);case N.ZodNaN:case N.ZodNever:return ad();case N.ZodEffects:return ed(t,r,n);case N.ZodAny:return Vu();case N.ZodUnknown:return bd();case N.ZodDefault:return Xu(t,r);case N.ZodBranded:return Qu(t,r);case N.ZodReadonly:return Ad(t,r);case N.ZodCatch:return Yu(t,r);case N.ZodPipeline:return hd(t,r);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(o=>{})(e)}},Yh=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var La=(t,e)=>{let r=Hu(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=M(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s);let i=(()=>{if(Wu(r.definitions))return;let c={},l=new Set;for(let u=0;u<500;u++){let m=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(m.length===0)break;for(let[f,h]of m)c[f]=M(Co(h),{...r,currentPath:[...r.basePath,r.definitionPath,f]},!0)??{},l.add(f)}return c})(),a=n===void 0?i?{...o,[r.definitionPath]:i}:o:r.nameStrategy==="duplicate-ref"?{...o,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[n]:o}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function xd(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 tt(e,[],e)}function Da(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Da(e))return!0;for(let e of t.anyOf??[])if(Da(e))return!0;return!1}function tt(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!dr(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let n=t.$defs;if(dr(n))for(let[f,h]of Object.entries(n))tt(h,[...e,"$defs",f],r);let o=t.definitions;if(dr(o))for(let[f,h]of Object.entries(o))tt(h,[...e,"definitions",f],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(dr(a)){for(let[f,h]of Object.entries(a))if(!Da(h)&&!i.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([f,h])=>[f,tt(h,[...e,"properties",f],r)]))}let c=t.items;dr(c)&&(t.items=tt(c,[...e,"items"],r));let l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,h)=>tt(f,[...e,"anyOf",String(h)],r)));let u=t.allOf;if(Array.isArray(u))if(u.length===1){let f=tt(u[0],[...e,"allOf","0"],r);Object.assign(t,f),delete t.allOf}else t.allOf=u.map((f,h)=>tt(f,[...e,"allOf",String(h)],r));t.default===null&&delete t.default;let m=t.$ref;if(m&&eg(t,1)){if(typeof m!="string")throw new TypeError(`Received non-string $ref - ${m}; path=${e.join("/")}`);let f=Xh(r,m);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${m}\` to resolve to an object schema but got boolean`);if(!dr(f))throw new Error(`Expected \`$ref: ${m}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,tt(t,e,r)}return t}function Xh(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(!dr(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 dr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function eg(t,e){let r=0;for(let n in t)if(r++,r>e)return!0;return!1}function tg(t,e){return La(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function rg(t){return xd(Vl(t,{target:"draft-7"}))}function ng(t){return"_zod"in t}function vd(t,e,r){return eu({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:ng(t)?rg(t):tg(t,{name:e})}},n=>t.parse(JSON.parse(n)))}var Id=["jsonSchema","functionCalling","jsonMode"];function Td(t,e){if(typeof e<"u"&&!Id.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Id.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 og(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Sd(t,e,r){if(Gl(t))return vd(t,e,r);if(Vo(t))return og({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Mt(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>Wl(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}function Cd(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 Ed={"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 Fn(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var pr=class extends Qo{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??xe("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??xe("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(!Qe(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&&Pt(t.json_schema.schema)?Sd(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=Xe({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=et(r.defaultHeaders),this.client=new O(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return cr(t)?Uu(t.metadata.customTool):Jo(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Pu(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(Dn(n)||cr(n))return n;if($u(n))return n.extras.providerToolDefinition;let o=this._convertChatOpenAIToolToCompletionsTool(n,{strict:r});return _r(n)&&n.extras?.defer_loading===!0?{...o,defer_loading:!0}:o}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,n=0;this.model==="gpt-3.5-turbo-0301"?(r=4,n=-1):(r=3,n=1);let o=await Promise.all(t.map(async s=>{let[i,a]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(Ye(s))]),c=s.name!==void 0?n+await this.getNumTokens(s.name):0,l=i+r+a+c,u=s;if(u._getType()==="function"&&(l-=2),u.additional_kwargs?.function_call&&(l+=3),u?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(u.additional_kwargs.function_call?.name)),u.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(u.additional_kwargs.function_call?.arguments)))}catch(m){console.error("Error parsing function arguments",m,JSON.stringify(u.additional_kwargs.function_call)),l+=await this.getNumTokens(u.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:o}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let n=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let o=Mu(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 Ed[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,n,{schema:o,name:s,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=Td(this.model,e?.method);if(a==="jsonMode"){n=ki(o);let c=Mt(o);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...c}}})}else if(a==="jsonSchema"){let c=Mt(o),l={name:s??"extract",description:Ci(c),schema:Pt(o)?o:c,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:l},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:l.name,description:l.description,...c}}}),Pt(o)||Ho(o)){let u=ki(o);n=lt.from(async m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:u.invoke(m.content))}else n=new Ql}else{let c=s??"extract",l=Mt(o),u;Pt(o)||Ho(o)?u={name:c,description:l.description,parameters:l}:typeof o.name=="string"&&typeof o.parameters=="object"&&o.parameters!=null?(u=o,c=o.name):(c=o.title??c,u={name:c,description:o.description??"",parameters:o}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:u}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...l}},...e?.strict!==void 0?{strict:e.strict}:{}}),n=Yl(o,c)}return Xl(r,n,i)}};var Fs={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=Ii({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=vi(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=vi(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=Ii({dataUrl:t.url}),r=lr(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=lr(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`)}},Fa=({message:t,rawResponse:e,includeRawResponse:r})=>{let n=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let s=[],i=[];for(let l of n??[])try{s.push(Zo(l,{returnId:!0}))}catch(u){i.push(yr(l,u.message))}let a={function_call:t.function_call,tool_calls:n};r!==void 0&&(a.__raw_response=e),o!==void 0&&(a.reasoning_content=o);let c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new j({content:Cd(t.content||"",e.choices?.[0]?.message),tool_calls:s,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Ko(t.content||"",t.role??"unknown")}},ja=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:n})=>{let o=t.role??n,s=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Si({content:s,response_metadata:a});if(o==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let l of t.tool_calls)c.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new at({content:s,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return o==="system"?new Wo({content:s,response_metadata:a}):o==="developer"?new Wo({content:s,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new ql({content:s,additional_kwargs:i,name:t.name,response_metadata:a}):o==="tool"?new Ti({content:s,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new Ul({content:s,role:o,response_metadata:a})},kd=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=Bl(()=>{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=lr(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}}}},Od=({message:t,model:e})=>{let r=Ye(t);if(r==="system"&&Qe(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 j.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(Ei):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(r==="tool"&&B.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*n(o){for(let s of o){s.type==="text"&&(yield{type:"text",text:s.text});let i=kd(s);i&&(yield i)}}return{role:"user",content:Array.from(n(t.contentBlocks))}},jn=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Od({message:r});let n=Ye(r);n==="system"&&Qe(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>qo(i)?Bo(i,Fs):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),s={role:n,content:o};return r.name!=null&&(s.name=r.name),r.additional_kwargs.function_call!=null&&(s.function_call=r.additional_kwargs.function_call),j.isInstance(r)&&r.tool_calls?.length?s.tool_calls=r.tool_calls.map(Ei):(r.additional_kwargs.tool_calls!=null&&(s.tool_calls=r.additional_kwargs.tool_calls),B.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 js=class extends pr{constructor(t,e){super(Fn(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let n={};t?.stream_options!==void 0?n={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(n={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:$s(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),Qe(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=jn({messages:t,model:this.model});if(o.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let h of i){h.message.response_metadata={...h.generationInfo,...h.message.response_metadata};let w=h.generationInfo?.completion??0;a[w]===void 0?a[w]=h:a[w]=a[w].concat(h)}let c=Object.entries(a).sort(([h],[w])=>parseInt(h,10)-parseInt(w,10)).map(([h,w])=>w),{functions:l,function_call:u}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,l,u),f=await this._getNumTokensFromGenerations(c);return n.input_tokens=m,n.output_tokens=f,n.total_tokens=m+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}else{let i=await this.completionWithRetry({...o,stream:!1,messages:s},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:l,prompt_tokens_details:u,completion_tokens_details:m}=i?.usage??{};a&&(n.output_tokens=(n.output_tokens??0)+a),c&&(n.input_tokens=(n.input_tokens??0)+c),l&&(n.total_tokens=(n.total_tokens??0)+l),(u?.audio_tokens!==null||u?.cached_tokens!==null)&&(n.input_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.cached_tokens!==null&&{cache_read:u?.cached_tokens}}),(m?.audio_tokens!==null||m?.reasoning_tokens!==null)&&(n.output_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.reasoning_tokens!==null&&{reasoning:m?.reasoning_tokens}});let f=[];for(let h of i?.choices??[]){let w={text:h.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(h.message??{role:"assistant"},i)};w.generationInfo={...h.finish_reason?{finish_reason:h.finish_reason}:{},...h.logprobs?{logprobs:h.logprobs}:{}},it(w.message)&&(w.message.usage_metadata=n),w.message=new j(Object.fromEntries(Object.entries(w.message).filter(([b])=>!b.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let n=jn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s=await this.completionWithRetry(o,e),i=this.streamUsage??e.streamUsage;yield*Yo(async function*(c,l){for await(let u of c){if(l?.aborted)return;yield u}}(s,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=jn({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:n,stream:!0},s,i=await this.completionWithRetry(o,e),a;for await(let c of i){if(e.signal?.aborted)return;let l=c?.choices?.[0];if(c.usage&&(a=c.usage),!l)continue;let{delta:u}=l;if(!u)continue;let m=this._convertCompletionsDeltaToBaseMessageChunk(u,c,s);s=u.role??s;let f={prompt:e.promptIndex??0,completion:l.index??0};if(typeof m.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let h={...f};l.finish_reason!=null&&(h.finish_reason=l.finish_reason,h.system_fingerprint=c.system_fingerprint,h.model_name=c.model,h.service_tier=c.service_tier),this.logprobs&&(h.logprobs=l.logprobs);let w=new Yn({message:m,text:m.content,generationInfo:h});yield w,await r?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},l={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},u=new Yn({message:new at({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""});yield u,await r?.handleLLMNewToken(u.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:u})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=this._getClientOptions(e),n=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return n&&!t.stream?await this.client.chat.completions.parse(t,r):await this.client.chat.completions.create(t,r)}catch(o){throw be(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return ja({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Fa({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var zs="__openai_function_call_ids__",Us="__openai_custom_tool_call_ids__";function Dd(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 ig(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var ko=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},qs=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(Dd),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Zo(c,{returnId:!0}))}catch(l){let u;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(u=l.message),n.push(yr(c,u))}i[zs]??={},a.id&&(i[zs][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(l=>l.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=Lu(a);c?(r.push(c),i[Us]??={},a.id&&a.call_id&&(i[Us][a.call_id]=a.id)):n.push(yr(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=Du(a);c?r.push(c):n.push(yr(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new j({id:t.id,content:e,tool_calls:r,invalid_tool_calls:n,usage_metadata:ko(t.usage),additional_kwargs:i,response_metadata:s})},Fd=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}},za=t=>{let e=[],r={},n,o=[],s={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[Dd(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[zs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[Us]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let c=qs(t.response);if(n=ko(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[l,u]of Object.entries(t.response))l!=="id"&&(l==="output"?s[l]=c.response_metadata.output:s[l]=u)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,c,l]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:l}}}else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let c=t.item.summary?t.item.summary.map((u,m)=>({...u,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let l=t.item.summary?.map(u=>u.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new Yn({text:e.map(c=>c.text).join(""),message:new at({id:a,content:e,tool_call_chunks:o,usage_metadata:n,additional_kwargs:i,response_metadata:s}),generationInfo:r})},jd=t=>{let e=j.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=Ce(()=>{try{let g=Ye(t);return g==="system"||g==="developer"||g==="assistant"||g==="user"?g:"assistant"}catch{return"assistant"}}),o,s=new Set,i=new Set,a=new Map,c=new Map;function*l(){if(!o)return;let g=o.content;(typeof g=="string"&&g.length>0||Array.isArray(g)&&g.length>0)&&(yield o),o=void 0}let u=(g,x)=>{o||(o={type:"message",role:n,content:[],...x?{phase:x}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...g]:[...g]:o.content.push(...g)},m=g=>{if(typeof g=="string")return g;try{return JSON.stringify(g??{})}catch{return"{}"}},f=g=>{let x=Ce(()=>{let S=g.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(g.fileId)return{type:"input_image",detail:x,file_id:g.fileId};if(g.url)return{type:"input_image",detail:x,image_url:g.url};if(g.data){let S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_image",detail:x,image_url:`data:${g.mimeType??"image/png"};base64,${S}`}}},h=g=>{if(g.fileId){let x=Ms(g);return{type:"input_file",file_id:g.fileId,...x?{filename:x}:{}}}if(g.url){let x=Ms(g);return{...x?{filename:x}:{},type:"input_file",file_url:g.url}}if(g.data){let x=lr(g),S=typeof g.data=="string"?g.data:Buffer.from(g.data).toString("base64");return{type:"input_file",file_data:`data:${g.mimeType??"application/octet-stream"};base64,${S}`,filename:x}}},w=g=>{let x=Ce(()=>{if(Array.isArray(g.summary)){let $=g.summary?.map(z=>z?.text).filter(z=>typeof z=="string")??[];if($.length>0)return $}return g.reasoning?[g.reasoning]:[]}),S=x.length>0?x.map($=>({type:"summary_text",text:$})):[{type:"summary_text",text:""}];return{type:"reasoning",...g.id?{id:g.id}:{},summary:S}},b=g=>({type:"function_call",name:g.name??"",call_id:g.id??"",arguments:m(g.args)}),v=g=>{let x=m(g.output),S=g.status==="success"?"completed":g.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:g.toolCallId??"",output:x,...S?{status:S}:{}}};for(let g of t.contentBlocks)if(g.type==="text"){let x=Ce(()=>{if("extras"in g&&typeof g.extras=="object"&&g.extras!==null&&"phase"in g.extras)return g.extras.phase});u([{type:"input_text",text:g.text}],x)}else if(g.type!=="invalid_tool_call"){if(g.type==="reasoning")yield*l(),yield w(g);else if(g.type==="tool_call"){yield*l();let x=g.id??"";x&&(s.add(x),a.delete(x)),yield b(g)}else if(g.type==="tool_call_chunk"){if(g.id){let x=a.get(g.id)??{name:g.name,args:[]};g.name&&(x.name=g.name),g.args&&x.args.push(g.args),a.set(g.id,x)}}else if(g.type==="server_tool_call"){yield*l();let x=g.id??"";x&&(i.add(x),c.delete(x)),yield b(g)}else if(g.type==="server_tool_call_chunk"){if(g.id){let x=c.get(g.id)??{name:g.name,args:[]};g.name&&(x.name=g.name),g.args&&x.args.push(g.args),c.set(g.id,x)}}else if(g.type==="server_tool_call_result")yield*l(),yield v(g);else if(g.type!=="audio")if(g.type==="file"){let x=h(g);x&&u([x])}else if(g.type==="image"){let x=f(g);x&&u([x])}else if(g.type==="video"){let x=h(g);x&&u([x])}else g.type==="text-plain"?g.text&&u([{type:"input_text",text:g.text}]):g.type==="non_standard"&&e&&(yield*l(),yield g.value)}yield*l();for(let[g,x]of a){if(!g||s.has(g))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:g,name:x.name??"",arguments:S})}for(let[g,x]of c){if(!g||i.has(g))continue;let S=x.args.join("");!x.name&&!S||(yield{type:"function_call",call_id:g,name:x.name??"",arguments:S})}}return Array.from(r())},Oo=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(n=>{let o=n.response_metadata;if(o?.output_version==="v1")return jd(n);let s=n.additional_kwargs,i=Ye(n);if(i==="system"&&Qe(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=n;if(s?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let l=a.content.find(f=>f.type==="input_image");if(l)return l;let u=a.content.find(f=>f.type==="computer_screenshot");if(u)return u;let m=a.content.find(f=>f.type==="image_url");if(m)return{type:"input_image",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(l=>typeof l=="object"&&l!==null&&"type"in l&&(l.type==="input_file"||l.type==="input_image"||l.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(b=>"type"in b))return o?.output;let a=[],c=s?.reasoning,l=!!c?.encrypted_content;if(c&&(!e||l)){let b=Fd(c);a.push(b)}let{content:u}=n;if(s?.refusal&&(typeof u=="string"&&(u=[{type:"output_text",text:u,annotations:[]}]),u=[...u,{type:"refusal",refusal:s.refusal}]),typeof u=="string"||u.length>0){let b={type:"message",role:"assistant",...n.id&&!e&&n.id.startsWith("msg_")?{id:n.id}:{},content:Ce(()=>typeof u=="string"?u:u.flatMap(v=>{if(v.type==="text"){let g=v;return{type:"output_text",text:g.text,annotations:(g.annotations??[]).map(ig)}}return v.type==="output_text"||v.type==="refusal"?v:[]})),phase:Ce(()=>{if(Array.isArray(u))return u.find(v=>"phase"in v&&typeof v.phase=="string")?.phase})};a.push(b)}let m=s?.[zs],f=s?.[Us];j.isInstance(n)&&n.tool_calls?.length?a.push(...n.tool_calls.map(b=>ju(b,f)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:f?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:Fu(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:m?.[b.id]}})):s?.tool_calls&&a.push(...s.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:m?.[b.id]}})));let h=o?.output?.length?o?.output:s.tool_outputs,w=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(h!=null){let b=h?.filter(v=>w.includes(v.type));b.length>0&&a.push(...b)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof n.content=="string")return{type:"message",role:i,content:n.content};let a=[],c=n.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),qo(l)){if(l.type==="file"){let u=Ms(l);if(l.source_type==="url")return{type:"input_file",file_url:l.url,...u?{filename:u}:{}};if(l.source_type==="id")return{type:"input_file",file_id:l.id,...u?{filename:u}:{}};if(l.source_type==="base64")return{type:"input_file",file_data:`data:${l.mime_type??""};base64,${l.data}`,filename:lr(l)}}return Bo(l,Fs)}return l.type==="text"?{type:"input_text",text:l.text}:l.type==="image_url"?{type:"input_image",image_url:Ce(()=>{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:Ce(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail})}:l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Ua(t,e={}){let r=e.streamUsage??!0,n=e.provider??"openai",o=new Map,s=new Map,i=0,a=!1,c,l,u,m,f=new Set,h=(v,g)=>{let x=s.get(v);if(x!==void 0)return{index:x,isNew:!1};let S=i++;return s.set(v,S),o.set(S,{...g}),{index:S,isNew:!0}},w=function*(){a||(a=!0,yield{event:"message-start",id:c})},b=function*(v){if(f.has(v))return;let g=o.get(v);g&&(f.add(v),yield{event:"content-block-finish",index:v,content:ec(g)})};for await(let v of t){if(v.type==="response.created"){c=v.response.id,yield*w(),yield{event:"provider",provider:n,name:"response.created",payload:{model:v.response.model,id:v.response.id}};continue}if(v.type==="response.output_text.delta"){yield*w();let{index:g,isNew:x}=h(`text:${v.output_index}:${v.content_index}`,{type:"text",text:""});x&&(yield{event:"content-block-start",index:g,content:{type:"text",text:""}});let S=o.get(g);S.text=(S.text??"")+v.delta,yield{event:"content-block-delta",index:g,delta:{type:"text-delta",text:v.delta}};continue}if(v.type==="response.reasoning_summary_text.delta"){yield*w();let{index:g,isNew:x}=h(`reasoning:${v.output_index}:${v.summary_index}`,{type:"reasoning",reasoning:""});x&&(yield{event:"content-block-start",index:g,content:{type:"reasoning",reasoning:""}});let S=o.get(g);S.reasoning=(S.reasoning??"")+v.delta,yield{event:"content-block-delta",index:g,delta:{type:"reasoning-delta",reasoning:v.delta}};continue}if(v.type==="response.output_item.added"&&(v.item.type==="function_call"||v.item.type==="custom_tool_call")){yield*w();let g=`tool:${v.output_index}`,x=v.item.type==="custom_tool_call",S=v.item.type==="function_call"?v.item.arguments??"":v.item.input??"",{index:$,isNew:z}=h(g,{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:S,index:v.output_index,...x?{isCustomTool:!0}:{}});if(z&&(yield{event:"content-block-start",index:$,content:{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:S,index:v.output_index}}),S){let P=o.get($);yield{event:"content-block-delta",index:$,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...P.id!=null?{id:P.id}:{},...P.name!=null?{name:P.name}:{},args:P.args}}}}continue}if(v.type==="response.function_call_arguments.delta"||v.type==="response.custom_tool_call_input.delta"){yield*w();let{index:g,isNew:x}=h(`tool:${v.output_index}`,{type:"tool_call_chunk",args:"",index:v.output_index,...v.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});x&&(yield{event:"content-block-start",index:g,content:{type:"tool_call_chunk",args:"",index:v.output_index}});let S=o.get(g);S.args=(S.args??"")+v.delta,yield{event:"content-block-delta",index:g,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...S.id!=null?{id:S.id}:{},...S.name!=null?{name:S.name}:{},args:S.args}}};continue}if(v.type==="response.output_item.done"&&(v.item.type==="function_call"||v.item.type==="custom_tool_call")){yield*w();let g=`tool:${v.output_index}`,x=v.item.type==="function_call"?v.item.arguments??"":v.item.input??"",{index:S,isNew:$}=h(g,{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:x,index:v.output_index});if($)yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:x,index:v.output_index}};else{let z=o.get(S);z.args=x,z.id=v.item.call_id,z.name=v.item.name}yield*b(S);continue}if(v.type==="response.completed"||v.type==="response.incomplete"){yield*w(),c=v.response.id,u=ag(v.response.status,v.type),m={model_provider:n,id:v.response.id,model:v.response.model,status:v.response.status},r&&v.response.usage&&(l=ko(v.response.usage),yield{event:"usage",usage:l});continue}v.type!=="response.image_generation_call.partial_image"&&(yield*w(),yield{event:"provider",provider:n,name:v.type,payload:v})}a||(yield{event:"message-start"});for(let[v]of o)f.has(v)||(yield*b(v));yield{event:"message-finish",reason:u,...l?{usage:l}:{},...m?{responseMetadata:m}:{}}}function ag(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var Bs=class extends pr{constructor(t,e){super(Fn(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:Nu(t?.tool_choice)?t?.tool_choice:(()=>{let o=$s(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},n=this._getReasoningParams(t);return n!==void 0&&(r.reasoning=n),r}async _generate(t,e,r){e.signal?.throwIfAborted();let n=this.invocationParams(e);if(n.stream){let o=this._streamResponseChunks(t,e,r),s;for await(let i of o)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},s=s?.concat(i)??i;return{generations:s?[s]:[],llmOutput:{estimatedTokenUsage:s?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:Oo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:qs(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:Oo({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Ua(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(n,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let n=await this.completionWithRetry({...this.invocationParams(e),input:Oo({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=za(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(Dn(n))n.type==="image_generation"&&e?.stream&&(n.partial_images=1),r.push(n);else if(cr(n)){let o=n.metadata.customTool;r.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Jo(n)){let o={};for(let[s,i]of Object.entries(n))s!=="type"&&s!=="function"&&(o[s]=i);r.push({type:"function",name:n.function.name,parameters:n.function.parameters,description:n.function.description,strict:e?.strict??null,...o})}else Ns(n)&&r.push(zu(n));return r}};var Ks=class zd extends pr{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=Fn(e,r);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Bs(n),this.completions=n?.completions??new js(n)}_useResponsesApi(e){let r=e?.tools?.some(Dn),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(Ns)||e?.tools?.some(cr);return this.useResponsesApi||r||n||o||Eu(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 zd(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ws=class extends Jl{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??xe("OPENAI_API_KEY");this.organization=e?.configuration?.organization??xe("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Oi(this.stripNewLines?t.map(s=>s.replace(/\n/g," ")):t,this.batchSize),r=e.map(s=>{let i={model:this.model,input:s};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),n=await Promise.all(r),o=[];for(let s=0;s<n.length;s+=1){let i=e[s],{data:a}=n[s];for(let c=0;c<i.length;c+=1)o.push(a[c].embedding)}return o}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Xe({baseURL:this.clientConfig.baseURL}),n={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};n.baseURL||delete n.baseURL,n.defaultHeaders=et(n.defaultHeaders),this.client=new O(n)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw be(r)}})}};var dg=I.object({type:I.literal("screenshot")}),pg=I.object({type:I.literal("click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),mg=I.object({type:I.literal("double_click"),x:I.number(),y:I.number(),button:I.enum(["left","right","wheel","back","forward"]).default("left")}),fg=I.object({type:I.literal("drag"),path:I.array(I.object({x:I.number(),y:I.number()}))}),hg=I.object({type:I.literal("keypress"),keys:I.array(I.string())}),gg=I.object({type:I.literal("move"),x:I.number(),y:I.number()}),yg=I.object({type:I.literal("scroll"),x:I.number(),y:I.number(),scroll_x:I.number(),scroll_y:I.number()}),_g=I.object({type:I.literal("type"),text:I.string()}),wg=I.object({type:I.literal("wait"),duration:I.number().optional()}),bg=I.union([dg,pg,mg,fg,hg,gg,yg,_g,wg]),NB=I.object({action:bg});var Ag=I.object({type:I.literal("exec"),command:I.array(I.string()),env:I.record(I.string(),I.string()).optional(),working_directory:I.string().optional(),timeout_ms:I.number().optional(),user:I.string().optional()}),jB=I.union([Ag]);var BB=I.object({commands:I.array(I.string()).describe("Array of shell commands to execute"),timeout_ms:I.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:I.number().optional().describe("Optional maximum number of characters to return from each command")});var xg=I.object({type:I.literal("create_file"),path:I.string(),diff:I.string()}),vg=I.object({type:I.literal("update_file"),path:I.string(),diff:I.string()}),Ig=I.object({type:I.literal("delete_file"),path:I.string()}),VB=I.union([xg,vg,Ig]);var qd={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Ba={default:"text-embedding-ada-002"},qa=new Map,Hs=null,Eg=()=>{let t=Ud.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},Bd=async t=>{let e=Eg();qa.size===0&&(Hs||(Hs=(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=>qa.set(o.name,o))}catch(n){throw Hs=null,n}})()),await Hs);let r=qa.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},kg=async(t="default")=>await Bd(qd[t]),Kd=async(t="default")=>await Bd(Ba[t]),Un=(t,e)=>e,Wd=(t,e)=>({...t,...e}),Hd=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let n=t.trim();if(!n)return r;if(n===r)return t;let o=n.split(`
|
|
69
|
-
|
|
70
|
-
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
71
|
-
|
|
72
|
-
${r}`},Vd=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Ct=()=>({agentExecutionContext:k({reducer:Wd,default:Vd}),outputMessage:k({reducer:Hd,default:()=>""}),summary:k({reducer:Un,default:()=>""}),status:k({reducer:Un})}),Ka=()=>({...Ct(),sharedStatePatch:k({reducer:Un})}),Og=k.Root({agentExecutionContext:k({default:Vd,reducer:Wd}),currentIntent:k({default:()=>"none",reducer:Un}),lastExecutedAgent:k({default:()=>"",reducer:Un}),requiresFollowUp:k({default:()=>!0,reducer:Un}),stepCount:k({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:k({default:()=>"",reducer:Hd})});var Pg=t=>typeof t=="string"&&t.length>0?t:void 0,Mg=()=>Tl(),Rg=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,$g=t=>{let e=t?.configurable;return{conversationId:Pg(e?.thread_id),abortSignal:t?.signal,requestId:Mg(),requestSource:Rg(Cg.applicationName)}},Gd=async({config:t})=>{let e=Ud.getDefault(),r=(await Sg.getCredential(`${e.url}/sharing`))?.token;return async(n,o)=>{let{conversationId:s,abortSignal:i,requestId:a,requestSource:c}=$g(t),l=new Headers(o?.headers);l.delete("Authorization"),l.delete("api-key"),r&&r.length>0&&(l.set("X-Esri-Authorization",`Bearer ${r}`),l.set("X-Esri-Request-Source",c)),s&&s.length>0&&l.set("X-Esri-Conversation-Id",s),a.length>0&&l.set("X-Esri-Request-Id",a);let u=i&&o?.signal?AbortSignal.any([i,o.signal]):o?.signal??i;return await fetch(n,{...o,headers:l,signal:u})}},Wa=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:n}=t,o=qd[e],s=await kg(e);return new Ks({modelName:o,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:s,fetch:await Gd({config:n})}})},Jd=async(t={})=>{let{tier:e="default",config:r}=t,n=Ba[e],o=await Kd(e);return new Ws({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:await Gd({config:r})},batchSize:2048,maxConcurrency:10})},Ng=I.object({id:I.string().min(1),name:I.string().min(1),description:I.string().min(1)});I.array(Ng);var Zd="0.1",zn=1536,Qd="openai",Yd=Ba.default,Xd=`Name: {name}
|
|
73
|
-
Title: {title}
|
|
74
|
-
Description: {description}`,ep=`Name: {name}
|
|
75
|
-
Alias: {alias}
|
|
76
|
-
Description: {description}`,tp=I.object({schemaVersion:I.literal(Zd),modified:I.number().int().nonnegative(),embeddings:I.object({modelProvider:I.literal(Qd),model:I.literal(Yd),dimensions:I.literal(zn),templates:I.object({layer:I.string().default(Xd),field:I.string().default(ep)})}),layers:I.array(I.object({id:I.string().min(1),name:I.string().min(1),title:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(zn,{message:`Layer vector must be exactly ${zn} dimensions`}),fields:I.array(I.object({name:I.string().min(1),alias:I.string().catch(""),description:I.string().catch(""),vector:I.array(I.number()).length(zn,{message:`Field vector must be exactly ${zn} dimensions`})}))})).default([])});var rp=(t,e)=>{let r=tc.fromTemplate(t);return rc.fromMessages([r,...e])},Lg=async t=>{let{promptText:e,modelTier:r,temperature:n,messages:o,config:s}=t,i=rp(e,o??[]),a=await Wa({modelTier:r,temperature:n,config:s});return i.pipe(a)},Vs=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,config:i}=t,a=await(await Lg({promptText:e,modelTier:r,temperature:n,messages:o,config:i})).invoke(s??{},i);if(typeof a=="string")return a;let c=a.content;return typeof c=="string"?c:JSON.stringify(c)},Po=async t=>{let{promptText:e,modelTier:r="default",temperature:n=0,messages:o,inputVariables:s,schema:i,config:a}=t,c=rp(e,o??[]),l=(await Wa({modelTier:r,temperature:n,config:a})).withStructuredOutput(i);return await c.pipe(l).invoke(s??{},a)};var Dg=d.object({name:d.string(),description:d.string(),valueType:d.string(),alias:d.string()}),g2=d.object({fields:d.array(Dg)});var y2=d.object({title:d.string(),description:d.string(),name:d.string().nullable()});var np=async t=>{try{return await(await Jd()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}};var sp=t=>Array.isArray(t)&&t.every(Qn),jg=t=>typeof t=="object"&&t!=null&&"messages"in t&&sp(t.messages),zg=t=>typeof t=="object"&&t!=null&&"lg_tool_call"in t,rt=class extends nc{tools;handleToolErrors=!0;trace=!1;constructor(t,e){let{name:r,tags:n,handleToolErrors:o}=e??{};super({name:r,tags:n,func:(s,i)=>this.run(s,i)}),this.tools=t,this.handleToolErrors=o??this.handleToolErrors}async runTool(t,e,r){let n=this.tools.find(o=>o.name===t.name);try{if(n===void 0)throw new Error(`Tool "${t.name}" not found.`);let o={...t,type:"tool_call"},s={...e,state:r,toolCallId:t.id??"",config:e,context:e.context,store:e.store??null,writer:e.writer??e.configurable?.writer??null},i=await n.invoke(o,s);return Qn(i)&&i.getType()==="tool"||Ot(i)?i:new B({status:"success",name:n.name,content:typeof i=="string"?i:JSON.stringify(i),tool_call_id:t.id})}catch(o){if(!this.handleToolErrors||Uo(o))throw o;return new B({status:"error",content:`Error: ${o.message}
|
|
77
|
-
Please fix your mistakes.`,name:t.name,tool_call_id:t.id??""})}}async run(t,e){let r;if(zg(t)){let{lg_tool_call:s,...i}=t;r=[await this.runTool(s,e,i)]}else{let s;if(sp(t))s=t;else if(jg(t))s=t.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),a;for(let c=s.length-1;c>=0;c-=1){let l=s[c];if(it(l)){a=l;break}}if(a==null||!it(a))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(a.tool_calls?.filter(c=>c.id==null||!i.has(c.id)).map(c=>this.runTool(c,e,t))??[])}if(!r.some(Ot))return Array.isArray(t)?r:{messages:r};let n=[],o=null;for(let s of r)Ot(s)?s.graph===qe.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Fl(i))?o?o.goto.push(...s.goto):o=new qe({graph:qe.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(t)?[s]:{messages:[s]});return o&&n.push(o),n}};var gW=k.Root({llmInputMessages:k({reducer:(t,e)=>Xn([],e),default:()=>[]})});var Mo=(t,e)=>e??t,Ay=k.Root({...Ka(),intent:k({reducer:Mo}),vectorSearchLayerResults:k({reducer:Mo,default:()=>[]}),vectorSearchFieldResults:k({reducer:Mo}),navigationInternalState:k({reducer:Mo,default:()=>({toolCallMessage:void 0})})});async function xy(t,e){let r=mr.getDefault().helperServices,n=r.geocode.find(u=>u.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!n)throw new Error("No geocoding service found in helperServices.");let o=n.url,s=`${Ha.assetsPath?.endsWith("/")?Ha.assetsPath:`${Ha.assetsPath}/`}esri/images/search/search-symbol-32.png`,i=(await Bg(o,{address:{SingleLine:t},outFields:["Match_addr"]}))?.[0];if(!i?.extent||!i.location)throw new Error(`Could not find location for: ${t}`);let a=new Kg({url:s,width:24,height:24}),c=new qg({geometry:i.location,symbol:a});e.graphics.removeAll(),e.graphics.add(c),await e.goTo(i.extent);let l={address:i.address??"",location:i.location?i.location.toJSON():null,extent:i.extent?i.extent.toJSON():null};return{text:`Successfully zoomed to ${t}.`,sharedStatePatch:{lastResolvedLocation:{value:l}}}}var vy=["mapView"];function ze(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("NavigationAgent context missing");let r=vy.filter(n=>!(n in e));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return e}async function Iy({address:t},e){let{mapView:r}=ze(e);return await xy(t,r)}var Ty=d.object({address:d.string().describe("The full address or place name to locate.")}),Sy=L(Iy,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Ty});async function Cy(t,e){let r=e.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let n=r.find(s=>s.name===t);if(!n)throw new Error(`Bookmark with name "${t}" not found.`);let o=n.viewpoint;if(!o)throw new Error(`Bookmark with name "${t}" does not have a valid viewpoint.`);return await e.goTo(o),{text:`Navigated to bookmark: ${t}`}}async function Ey({bookmarkName:t},e){let{mapView:r}=ze(e);return await Promise.resolve(Cy(t,r))}var ky=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),Oy=L(Ey,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:ky});async function Py(t,e,r){let n=r.map?.allLayers.find(i=>i.id===t);if(!n)return{text:`Error: Layer with id ${t} not found`};let o=e?.trim()?e:"1=1",s=n.createQuery();s.where=o;try{let{extent:i,count:a}=await n.queryExtent(s);if(a===0)return{text:`No features found in ${n.title} matching: ${o}`,where:o};if(i)await r.goTo(i);else return{text:`Error: Unable to determine extent for ${n.title}`,where:o};let c={layerId:t,layerTitle:n.title??t,where:o,count:a};return{text:`Successfully zoomed to ${a} feature(s) in ${n.title} matching: ${o}`,where:o,sharedStatePatch:{lastNavigatedFeatures:{value:c}}}}catch(i){return console.error("Error in goToFeatures:",i),{text:`Error: ${i instanceof Error?i.message:"Unknown error"}`,where:o}}}async function My({layerId:t,where:e},r){let{mapView:n}=ze(r);return await Py(t,e,n)}var Ry=I.object({layerId:I.string().describe("The layerId of the layer to zoom to."),where:I.string().describe("The sql-92 where clause used to query features to zoom to")}),$y=L(My,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Ry});async function Ny(t){let e=new Wg({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 Ly(t,e){let{mapView:r}=ze(e);return await Ny(r)}var Dy=I.object({}),Fy=L(Ly,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Dy});async function jy(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 zy(t,e){let{mapView:r}=ze(e);return await jy(r)}var Uy=d.object({}),qy=L(zy,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:Uy});async function By(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 Ky({layerId:t},e){let{mapView:r}=ze(e);return await By(t,r)}var Wy=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),Hy=L(Ky,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Wy});async function Vy(t,e){return await e.goTo({scale:t}),{text:`Successfully zoomed to: ${t}`}}async function Gy({scale:t},e){let{mapView:r}=ze(e);return await Vy(t,r)}var Jy=d.object({scale:d.number().describe("The map scale of the view to go to.")}),Zy=L(Gy,{name:"goToScale",description:"Go to the specified view scale.",schema:Jy});async function Qy(t,e,r){let n={target:new fp({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 Yy({center:t,zoom:e,scale:r},n){let{mapView:o}=ze(n);return await Qy(t,o,{zoom:e,scale:r})}var Xy=d.object({center:d.object({longitude:d.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:d.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:d.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:d.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),e_=L(Yy,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:Xy});async function t_(t,e){return await e.goTo({zoom:t}),{text:`Successfully zoomed to: ${t}`}}async function r_({zoom:t},e){let{mapView:r}=ze(e);return await t_(t,r)}var n_=d.object({zoom:d.number().min(1).max(20).describe("The zoom level of the view to go to.")}),o_=L(r_,{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:n_}),dp=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./O4VO5GNH.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./U5FCUMGO.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_cypher_query_prompt.md":()=>import("./6ND2JXTN.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./MV7GEGP5.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./A2LPB576.js").then(t=>t.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./EL3OIP52.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./TLIIJ2QC.js").then(t=>t.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./PLXHBQBF.js").then(t=>t.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./YPDXQEUA.js").then(t=>t.default),"../agents/help/prompts/help_prompt.md":()=>import("./U76GHEKJ.js").then(t=>t.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./54TJQLYJ.js").then(t=>t.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./6WPQPRJ5.js").then(t=>t.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./VDZT4UXB.js").then(t=>t.default)});async function nt(t){let e=Object.entries(dp).find(([r])=>r.endsWith(`/${t}.md`));if(!e)throw new Error(`Prompt not found: ${t}
|
|
78
|
-
Available prompts:
|
|
79
|
-
${Object.keys(dp).join(`
|
|
80
|
-
`)}`);return await e[1]()}var Kn=(t,e)=>{let r=t?.configurable?.services?.[e];if(r==null)throw new Error(`${e} missing in config.configurable.services`);return r};async function s_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s?i=Vg({basemapTheme:await lp(n),geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,8)})[0]:i=Gg({basemapTheme:await lp(n),geometryType:r.geometryType,numColors:Math.min(e.length,8)}).primaryScheme,{layer:r,view:n,attributes:e.map(a=>({field:a,label:r.fields.find(c=>c.name===a)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:i}}async function i_(t){return await Hg(t)}async function a_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"chart-size":"chart",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=await s_(c),u=await i_(l);return a.renderer=u.renderer,a.visible=!0,`Chart renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying chart renderer: ${l instanceof Error?l.message:String(l)}`}}var l_=["mapView"];function Oe(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("LayerStylingAgent context missing");let r=l_.filter(n=>!(n in e));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return e}async function c_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await a_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var u_=d.object({layerId:d.string().describe("The id of the layer to apply the chart renderer to"),fields:d.array(d.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),d_=L(c_,{name:"chart",description:`Label: Charts
|
|
81
|
-
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
82
|
-
Keywords: pie, chart, all categories, breakdown, proportion
|
|
83
|
-
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
84
|
-
Fields: This style requires 2-8 number fields.
|
|
85
|
-
|
|
86
|
-
Label: Charts and Size
|
|
87
|
-
Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
|
|
88
|
-
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
89
|
-
Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
|
|
90
|
-
Fields: This style requires 2-8 number fields.`,schema:u_});function p_(t){let{fields:e,layer:r,view:n,theme:o,colorSchemeTags:s}=t,i=e[0],a;return s&&(a=rl({geometryType:r.geometryType,includedTags:s,theme:o||"high-to-low"})[0]),{layer:r,view:n,startTime:i,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:a}}async function m_(t){return await Jg(t)}async function f_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=p_(c),u=await m_(l);return a.renderer=u.renderer,a.visible=!0,`Color-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function h_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await f_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var g_=d.object({layerId:d.string().describe("The id of the layer to apply the color-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),y_=L(h_,{name:"color-age",description:`Label: Age (color)
|
|
91
|
-
Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
92
|
-
Keywords: since, age, how old, how long
|
|
93
|
-
Example: Show the age of each feature based on its reported date.
|
|
94
|
-
Fields: This style requires at least one field with a date type.`,schema:g_});function __(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,{theme:s}=t,i=e[1],a=e[0],c;return o&&(c=rl({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:a,normalizationField:i,theme:s,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function w_(t){return await Zg(t)}async function b_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=__(c),u=await w_(l);return a.renderer=u.renderer,a.visible=!0,`Color renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color renderer: ${l instanceof Error?l.message:String(l)}`}}async function A_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await b_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var x_=d.object({layerId:d.string().describe("The id of the layer to apply the color renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the color renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),v_=L(A_,{name:"color",description:`Label: Counts and Amounts (color)
|
|
95
|
-
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
96
|
-
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
97
|
-
Example: Color each feature based on the population density.
|
|
98
|
-
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:x_});function I_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o,theme:s}=t,i,a,c=e[0];return o&&(a=rl({geometryType:r.geometryType,includedTags:o,theme:s||"high-to-low"})[0]),{layer:r,view:n,field:c,normalizationField:i,theme:s,colorOptions:{colorScheme:a}}}async function T_(t){return await Qg(t)}async function S_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=I_(c),u=await T_(l);return a.renderer=u.renderer,a.visible=!0,`Color-size-univariate renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying color-size-univariate renderer: ${l instanceof Error?l.message:String(l)}`}}async function C_({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await S_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var E_=d.object({layerId:d.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:d.array(d.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),k_=L(C_,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
99
|
-
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
100
|
-
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
101
|
-
Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
|
|
102
|
-
Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:E_});function O_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s;return o&&(s=Xg({includedTags:o,numColors:Math.min(e.length,8)})[0]),{layer:r,view:n,legendOptions:{unit:"units"},attributes:e.map(i=>({field:i,label:r.fields.find(a=>a.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:s}}async function P_(t){return await Yg(t)}async function M_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"dot-density",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=O_(a),l=await P_(c);return i.renderer=l.renderer,i.visible=!0,`Dot Density renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function R_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await M_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var $_=d.object({layerId:d.string().describe("The id of the layer to apply the dot density renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),N_=L(R_,{name:"dot-density",description:`Dot Density
|
|
103
|
-
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
104
|
-
**Use cases:**
|
|
105
|
-
- Population distribution visualization
|
|
106
|
-
- Comparing multiple categories within areas
|
|
107
|
-
- Showing spatial distribution patterns
|
|
108
|
-
**Examples:**
|
|
109
|
-
- Show the density of the population based on various race/ethnic groups
|
|
110
|
-
- Visualize distribution of different crops across regions
|
|
111
|
-
- Display demographic patterns within census tracts
|
|
112
|
-
**Fields:** Requires 2-8 number fields.
|
|
113
|
-
**Keywords:** density, how much, how many, total, number, amount`,schema:$_});function L_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i=e[0];return o&&(s=ty({includedTags:o,basemap:n.map?.basemap||"topo"})[0]),{layer:r,view:n,field:i,heatmapScheme:s}}async function D_(t){return await ey(t)}async function F_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"heatmap",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=L_(a),l=await D_(c);return i.renderer=l.renderer,i.visible=!0,`Heatmap renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function j_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await F_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var z_=d.object({layerId:d.string().describe("The id of the layer to apply the heatmap renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),U_=L(j_,{name:"heatmap",description:`Label: Heat Map
|
|
114
|
-
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
115
|
-
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
116
|
-
Example: Create a heatmap
|
|
117
|
-
Fields: This typically requires zero or one field of type number.`,schema:z_});function q_(t){let{fields:e,layer:r,view:n,styleName:o,colorSchemeTags:s}=t,i;return s&&(i=ny({geometryType:r.geometryType,includedTags:s,numColors:Math.min(e.length,10)})[0]),{layer:r,view:n,fields:e.map(a=>({name:a})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:i}}async function B_(t){return await ry(t)}async function K_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,includeSize:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:s?"predominance-size":"predominance",fields:n,layer:a,view:i,colorSchemeTags:o};try{let l=q_(c),u=await B_(l);return a.renderer=u.renderer,a.visible=!0,`Predominance renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying predominance renderer: ${l instanceof Error?l.message:String(l)}`}}async function W_({layerId:t,fields:e,colorSchemes:r,includeSize:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await K_({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,includeSize:n})}var H_=d.object({layerId:d.string().describe("The id of the layer to apply the predominance renderer to"),fields:d.array(d.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),includeSize:d.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),V_=L(W_,{name:"predominance",description:`Label: Predominant category
|
|
118
|
-
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
119
|
-
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
120
|
-
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
121
|
-
Fields: This style relies on 2-10 number fields.
|
|
122
|
-
|
|
123
|
-
Label: Predominant category and Size
|
|
124
|
-
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
|
|
125
|
-
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
126
|
-
Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
|
|
127
|
-
Fields: This style relies on 2-10 number fields.`,schema:H_});function G_(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s,i={field:e[0]},a={field:e[1]};return o&&(s=sy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field1:i,field2:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:s}}async function J_(t){return await oy(t)}async function Z_({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o}){let s=e,i=t?.allLayers.find(c=>c.id===r);if(!i)return`Could not find layer for id: ${r}`;let a={styleName:"relationship",fields:n,layer:i,view:s,colorSchemeTags:o};try{let c=G_(a),l=await J_(c);return i.renderer=l.renderer,i.visible=!0,`Relationship renderer applied to layer: ${i.title??i.id} using fields ${n.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Q_({layerId:t,fields:e,colorSchemes:r},n){let{mapView:o}=Oe(n);return await ge({type:"show-legend",data:{layerIds:[t]}},n),await Z_({arcgisMap:o.map,arcgisMapView:o,layerId:t,fields:e,colorSchemes:r})}var Y_=d.object({layerId:d.string().describe("The id of the layer to apply the relationship renderer to"),fields:d.array(d.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use")}),X_=L(Q_,{name:"relationship",description:`Label: Relationship
|
|
128
|
-
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
129
|
-
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
130
|
-
Example: Show the relationship between tree height and carbon storage
|
|
131
|
-
Fields: This style requires two number fields.`,schema:Y_});function ew(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 tw(t){return await iy(t)}async function rw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=ew(c),u=await tw(l);return a.renderer=u.renderer,a.visible=!0,`Size-age renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size-age renderer: ${l instanceof Error?l.message:String(l)}`}}async function nw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await rw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var ow=d.object({layerId:d.string().describe("The id of the layer to apply the size-age renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),sw=L(nw,{name:"size-age",description:`Label: Age (size)
|
|
132
|
-
Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
133
|
-
Keywords: since, age, how old, how long
|
|
134
|
-
Example: Change the size of features so older features are larger than new features.
|
|
135
|
-
Fields: This style requires at least one field with a date type.`,schema:ow});function iw(t){let{fields:e,layer:r,view:n}=t,{theme:o}=t,s=e[1],i=e[0];return{layer:r,view:n,field:i,normalizationField:s,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function aw(t){return await ay(t)}async function lw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=iw(c),u=await aw(l);return a.renderer=u.renderer,a.visible=!0,`Size renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying size renderer: ${l instanceof Error?l.message:String(l)}`}}async function cw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await lw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var uw=d.object({layerId:d.string().describe("The id of the layer to apply the size renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),dw=L(cw,{name:"size",description:`Label: Counts and Amounts (size)
|
|
136
|
-
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
137
|
-
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
138
|
-
Example: Vary the size of each point based on the total population.
|
|
139
|
-
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.
|
|
140
|
-
|
|
141
|
-
Label: Continuous Timeline (size)
|
|
142
|
-
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
143
|
-
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
144
|
-
Example: Vary the size of each feature based on the date a ticket was completed.
|
|
145
|
-
Fields: This style requires a single field with a date type.`,schema:uw});function pw(t){let{fields:e,layer:r,view:n,colorSchemeTags:o}=t,s=e[0],i=e[1],a=e[2],c;return o&&(c=cy({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:n,field:s,field2:i,field3:a,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function mw(t){return await ly(t)}async function fw({arcgisMap:t,arcgisMapView:e,layerId:r,fields:n,colorSchemes:o,theme:s}){let i=e,a=t?.allLayers.find(l=>l.id===r);if(!a)return`Could not find layer for id: ${r}`;let c={styleName:"type",fields:n,layer:a,view:i,colorSchemeTags:o,theme:s};try{let l=pw(c),u=await mw(l);return a.renderer=u.renderer,a.visible=!0,`Type renderer applied to layer: ${a.title??a.id} using fields ${n.join(", ")}`}catch(l){return`Error applying type renderer: ${l instanceof Error?l.message:String(l)}`}}async function hw({layerId:t,fields:e,colorSchemes:r,theme:n},o){let{mapView:s}=Oe(o);return await ge({type:"show-legend",data:{layerIds:[t]}},o),await fw({arcgisMap:s.map,arcgisMapView:s,layerId:t,fields:e,colorSchemes:r,theme:n})}var gw=d.object({layerId:d.string().describe("The id of the layer to apply the type renderer to"),fields:d.array(d.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:d.array(d.string()).optional().describe("Optional color scheme tags to use"),theme:d.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),yw=L(hw,{name:"type",description:`Label: Types (unique symbols)
|
|
146
|
-
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
147
|
-
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
148
|
-
Example: Color each feature based on the region it belongs to
|
|
149
|
-
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:gw}),_w=k.Root({...Ct(),vectorSearchLayerIds:k(),vectorSearchFieldResults:k(),layerFieldInfo:k(),selectedLayerId:k()}),ww=k.Root({...Ct(),vectorSearchLayerIds:k(),vectorSearchFieldResults:k(),layerFieldInfo:k(),queryResponse:k(),dataExplorationMessages:k({reducer:Xn,default:()=>[]})}),bw=["mapView"];function Et(t){let e=t?.configurable?.context;if(!e||typeof e!="object")throw new Error("DataExplorationAgent context missing");let r=bw.filter(n=>!(n in e));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return e}var Aw=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."},xw=async(t,e)=>{let{mapView:r}=Et(e);return Aw(r)},TH=L(xw,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:d.object({})}),vw=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."},Iw=async(t,e)=>{let{mapView:r}=Et(e);return await vw(r)},SH=L(Iw,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:d.object({})}),pp=750;function Qs(t){return"point"in t&&t.point!==void 0}function Ro(t){return"layerId"in t&&t.layerId!==void 0}var ei=async(t,e)=>{if(Qs(t)){let{point:r}=t;return{geometry:new fp({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:e.spatialReference})}}if(Ro(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:pp+1});if(!s.features.length)return{error:`No features found in geometry layer "${n}" with the specified where clause: ${o}`};if(s.features.length>pp)return{error:`Geometry filter for layer "${n}" matched too many features (${s.features.length}+). Please narrow the geometry layer filter.`};let i=s.features.map(c=>c.geometry).filter(c=>!!c);if(!i.length)return{error:"No valid geometries found for the matched geometry layer features."};let a=i.length===1?i[0]:gp.executeMany(i);return a?(a.spatialReference||(a.spatialReference=e.spatialReference),{geometry:a}):{error:"Failed to combine geometries from geometry layer."}}catch(s){return{error:`Failed to query geometry: ${String(s)}`}}}return{error:"Invalid geometry configuration provided"}},Tw=async(t,e,r,n,o,s)=>{let i=t.map?.allLayers.find(c=>c.id===e);if(!i)return{success:!1,error:`Layer '${e}' not found.`};let a=i.createQuery();a.where=r??"1=1",n&&(a.geometry=n,a.spatialRelationship="intersects",o&&(a.distance=o),s&&(a.units=s));try{let{extent:c,count:l}=await i.queryExtent(a);return!c||l===0?{success:!1,error:`No features found for filter (where: ${a.where}${n?", spatial filter used":""})`}:(await t.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},Sw=async(t,e,r,n,o,s)=>{let i=e.map?.allLayers.find(m=>m.id===t.layerId);if(!i)return`Could not find target layer with ID: ${t.layerId}`;let a;if(o){let m=await ei(o,e);if("error"in m)return m.error;a=m.geometry}if(i.featureEffect=null,i.featureEffect=new uy({filter:new hp({...t.objectIds?.length?{objectIds:t.objectIds}:{where:t.where},geometry:a,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:n}),i.visible=!0,s)return`Applied feature effects to "${i.title??t.layerId}" within current map extent.`;let c=t.objectIds?.length?`${i.objectIdField} IN (${t.objectIds.join(",")})`:t.where,l=await Tw(e,t.layerId,c,a,o?.distance,o?.units),u=i.title??t.layerId;return l.success?`Applied feature effects to target layer "${i.title??t.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${u}" but no features matched. ${l.error}`},Cw=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],kt=d.enum(Cw),Ew=async({targetLayer:t,geometryFilter:e,useCurrentExtent:r,includedEffect:n="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},s)=>{let{mapView:i}=Et(s);return await Sw(t,i,n,o,e,r)},kw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:kt.optional().describe("The units for the distance buffer.")}),Ow=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:kt.optional().describe("The units for the distance buffer.")}),Pw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer on which to set a feature effect."),where:d.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:d.array(d.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:d.union([kw,Ow]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:d.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:d.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:d.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),CH=L(Ew,{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:Pw}),Ga=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},Mw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Rw=t=>{if(typeof t=="string"&&t)return t;let e=Ga(t);return e?e.toISOString().slice(0,10):null};var $w=(t,e,r)=>{let n=e?.toLowerCase();if(n==="date-only"){let s=Rw(t);return s?dy(s,Gs("short-date")):t}if(n==="time-only"){if(typeof t=="string"&&t)return py(t,Gs("long-time"));let s=Ga(t);return s?cp(s,{...Gs("long-time"),timeZone:"UTC"}):t}let o=Ga(t);return o?cp(o,{...Gs("short-date-short-time"),timeZone:Mw(r)}):t},_p=(t,e,r)=>{if(t&&typeof t!="function"){let n="getField"in r&&r.getField?.(t),o=n&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(n.name):null;if(o?.type==="coded-value"){let s=o.codedValues.find(i=>i.code===e);return s?s.name:null}}return null},Nw=t=>!t||t==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:t==="unknown"?"UTC":t,Lw=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},Dw=(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}},Fw=(t,e,r)=>{let n=Lw(t);if(!n)return t;let o={};e.dateStyle?o.dateStyle=e.dateStyle:(e.year&&(o.year=e.year),e.month&&(o.month=e.month)),e.timeStyle&&(o.timeStyle=e.timeStyle),e.timeStyle&&e.hour12==="always"?o.hour12=!0:e.timeStyle&&e.hour12==="never"&&(o.hour12=!1),o.timeZone=Nw(r);try{return new Intl.DateTimeFormat(void 0,o).format(n)}catch{return t}},wp=(t,e)=>t.getFieldAlias?.(e)??t.fieldsIndex?.get(e)?.alias??t.fieldsIndex?.get(e)?.name??e,bp=(t,e,r,n,o)=>{if(r==null)return r;let s=t.getFieldConfiguration?.(e)?.fieldFormat;return s?.type==="number"?Dw(r,s):s?.type==="date-time"?Fw(r,s,o):$w(r,n,o)},jw=(t,e,r,n)=>{let o=t.fieldsIndex?.get(e),s=_p(e,r,t)??r;return bp(t,e,s,o?.type,n)},zw=(t,e)=>wp(t,e),Ap=(t,e,r)=>{let n=t.objectIdField,o=e.features.map(i=>i.attributes[n]),s=e.features.map(i=>{let a=i.attributes,c={};return t.fields.forEach(l=>{if(!Object.hasOwn(a,l.name))return;let u=a[l.name];if(l.name===n){c[l.name]=u;return}let m=_p(l.name,u,t)??u,f=wp(t,l.name);c[f]=bp(t,l.name,m,l.type,r)}),c});return{objectIds:o,attributes:s}},Uw=(t,e,r)=>{let n=t.createQuery();return n.outFields=[e],n.where=r||"1=1",n.num=1,n},qw=async(t,e,r,n)=>{let o=n.map?.allLayers.find(u=>u.id===t),s=Uw(o,e,r.where),i=(await o.queryFeatures(s)).features[0],a=i?i.attributes[e]:null,c=jw(o,e,a,n.timeZone),l=zw(o,e);return{tool:"getAttribute",layerName:o.title??t,summary:`${l} = ${c}`,details:{fieldName:e,fieldAlias:l!==e?l:void 0,value:c,where:r.where}}};async function Bw({layerId:t,fieldName:e,query:r},n){let{mapView:o}=Et(n),s=await qw(t,e,r,o);return JSON.stringify(s,null,2)}var Kw=d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:d.string().describe("The name of the field/attribute from which to get a field value."),query:d.object({where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Ww=L(Bw,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Kw}),nl=(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 Ys(t,e){let r=t??"";return e!=null&&e&&(r=r?`(${r}) AND (${e})`:e),r||null}var Hw=async t=>{let{targetLayer:e,fieldName:r,statisticType:n,mapView:o,layersAndFieldsRegistry:s,geometryFilter:i}=t,a=o.map?.allLayers.find(g=>g.id===e.layerId);if(!a)throw new Error(`Layer '${e.layerId}' not found.`);let c=await o.whenLayerView(a),l=s.get(e.layerId)?.fieldRegistry.get(r),u=l?.alias;if(!l)throw new Error(`Field '${r}' not found.`);let m,f;if(i){let g=await ei(i,o);if("error"in g)throw new Error(g.error);if(!g.geometry)throw Ro(i)?new Error(`No features found matching: ${i.where}`):new Error("Failed to create geometry");if(Ro(i)){let x=o.map?.allLayers.find(S=>S.id===i.layerId);m={geometryLayerName:x?.title??x?.id,geometryLayerId:i.layerId,geometryWhere:i.where,distance:i.distance,units:i.units,applied:!0}}else Qs(i)&&(m={point:i.point,distance:i.distance,units:i.units,applied:!0});f=new hp({geometry:g.geometry,distance:i.distance,units:i.units,spatialRelationship:"intersects"})}let h=nl(c,[r],!1),w=null,b=null,v=10;if(l.type!=="geometry"&&l.type!=="oid"&&l.type!=="global-id")try{let g={layer:a,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:Ys(a.definitionExpression,e.where),...f&&{filter:f},outStatisticTypes:{include:[n]}};w=await my(g);let x=["string","small-integer","integer"],S=l.domain?.type==="coded-value"?l.domain:null;(x.includes(l.type)||S)&&(b=(await fy({layer:a,useFeaturesInView:h,view:h?o:void 0,field:r,sqlWhere:Ys(a.definitionExpression,e.where),...f&&{filter:f}})).uniqueValueInfos.sort(($,z)=>z.count-$.count).slice(0,v)),b&&l.domain?.type==="coded-value"&&(b=b.map($=>({...$,value:S?S.getName($.value)??$.value:$.value})))}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:a.title??e.layerId,summary:`${n} = ${typeof w?.[n]=="number"?w[n]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:n,statistic:w?.[n]??null,summaryStatistics:w,uniqueValues:b,where:e.where,spatialFilterInfo:m}}};async function Vw({targetLayer:t,fieldName:e,statisticType:r,geometryFilter:n},o){let s=Kn(o,"layersAndFieldsRegistry"),{mapView:i}=Et(o),a=await Hw({targetLayer:t,fieldName:e,statisticType:r,mapView:i,layersAndFieldsRegistry:s,geometryFilter:n});return JSON.stringify(a,null,2)}var Gw=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:kt.optional().describe("The units for the distance buffer.")}),Jw=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:kt.optional().describe("The units for the distance buffer.")}),Zw=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:d.union([Gw,Jw]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:d.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:d.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Qw=L(Vw,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
150
|
-
|
|
151
|
-
USE THIS TOOL FOR:
|
|
152
|
-
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
153
|
-
- "Most common/frequent value of [field]?" \u2014 frequency analysis
|
|
154
|
-
- Questions requiring a mathematical aggregation across many features
|
|
155
|
-
|
|
156
|
-
DO NOT USE FOR:
|
|
157
|
-
- "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
|
|
158
|
-
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
159
|
-
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
160
|
-
|
|
161
|
-
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Zw}),Yw=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),Xw=async(t,e,r,n,o)=>{let s=r.map?.allLayers.find(f=>f.id===t.layerId),i=await r.whenLayerView(s),a=s.title??t.layerId,c;if(n){let f=await ei(n,r);if("error"in f)return{tool:"getTopFeatures",layerName:a,summary:"Geometry lookup failed",details:{error:f.error}};if(!f.geometry)return{tool:"getTopFeatures",layerName:a,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in n?n.where:"unknown criteria"}`}};c=f.geometry}else o&&(c=r.extent.clone());let l=e.groupByFields&&e.groupByFields.length>0,u=s.objectIdField,m=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])];try{let f;if(l){let b=new hy({where:t.where||"1=1",outFields:m,orderByFields:t.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:n?.distance,units:n?.units,topFilter:new gy({topCount:e.topCount,groupByFields:e.groupByFields,orderByFields:e.orderByFields})});f=await s.queryTopFeatures(b)}else{let b=s.createQuery();b.where=Ys(s.definitionExpression,t.where||"1=1"),b.outFields=m.length?m:["*"],b.orderByFields=e.orderByFields,b.returnGeometry=!1,b.num=e.topCount,c&&(b.geometry=c,b.spatialRelationship="intersects"),n?.distance&&(b.distance=n.distance),n?.units&&(b.units=n.units),b.outSpatialReference=r.spatialReference;let v=[...new Set([...t.outFields,...Yw(e.orderByFields)])],g=nl(i,v,o??!1);try{f=g?await i.queryFeatures(b):await s.queryFeatures(b)}catch(x){console.warn("Client-side query failed, falling back to server:",x),f=await s.queryFeatures(b)}}let h=f.features.map(b=>b.attributes[u]),{attributes:w}=Ap(s,f,r.timeZone);return{tool:"getTopFeatures",layerName:a,summary:`Top ${e.topCount} features extracted`,details:{topCount:e.topCount,attributes:w,objectIds:h,objectIdField:u,where:t.where,orderByFields:e.orderByFields,...l&&{groupByFields:e.groupByFields}}}}catch(f){return{tool:"getTopFeatures",layerName:a,summary:"Query failed",details:{error:f instanceof Error?f.message:String(f)}}}},eb=async({targetLayer:t,topFilter:e,geometryFilter:r,useCurrentExtent:n},o)=>{let{mapView:s}=Et(o),i=await Xw(t,e,s,r,n);return JSON.stringify(i,null,2)},tb=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:kt.optional().describe("The units for the distance buffer.")}),rb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:kt.optional().describe("The units for the distance buffer.")}),nb=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([tb,rb]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:d.object({topCount:d.number().describe("Number of top features to return per group."),orderByFields:d.array(d.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:d.array(d.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),ob=L(eb,{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:nb}),Va=25,sb=t=>t.flatMap(e=>e.split(",")).map(e=>e.trim()).map(e=>e.split(/\s+/u)[0]?.replace(/^"|"$/gu,"")).filter(e=>!!e),ib=async(t,e,r,n)=>{let o=e.map?.allLayers.find(v=>v.id===t.layerId),s=await e.whenLayerView(o),i=o.title??t.layerId,a;if(r){let v=await ei(r,e);if("error"in v){let g={error:v.error};if(Ro(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);g.geometryLayerName=x?.title??x?.id,g.geometryLayerId=r.layerId,g.geometryWhere=r.where}else Qs(r)&&(g.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"Geometry lookup failed",details:g}}if(!v.geometry){let g={};if(Ro(r)){let x=e.map?.allLayers.find(S=>S.id===r.layerId);g.error=`No features found matching: ${r.where}`,g.geometryLayerName=x?.title??x?.id,g.geometryLayerId=r.layerId,g.geometryWhere=r.where}else Qs(r)&&(g.error="Failed to create point geometry",g.point=r.point);return{tool:"queryFeatures",layerName:i,summary:"No features found for geometry filter",details:g}}a=v.geometry}else n&&(a=e.extent.clone());let c=[...new Set([...t.outFields,...sb(t.orderByFields)])],l=nl(s,c,n??!1),u=o.objectIdField,m=o.createQuery();m.where=Ys(o.definitionExpression,t.where||"1=1"),m.outFields=t.outFields.includes("*")?["*"]:[...new Set([...t.outFields,u])],m.orderByFields=t.orderByFields,a&&(m.geometry=a,m.spatialRelationship="intersects"),r?.distance&&(m.distance=r.distance),r?.units&&(m.units=r.units),m.outSpatialReference=e.spatialReference;let f,h;try{f=l?await s.queryFeatureCount(m):await o.queryFeatureCount(m),f>0&&f<=Va&&(h=l?await s.queryFeatures(m):await o.queryFeatures(m))}catch(v){console.warn("Client-side query failed, falling back to server:",v),f=await o.queryFeatureCount(m),f>0&&f<=Va&&(h=await o.queryFeatures(m))}let{objectIds:w,attributes:b}=h?Ap(o,h,e.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:i,summary:`${f} features found`,details:{totalCount:f,where:t.where,orderByFields:t.orderByFields,outFields:t.outFields,...w&&{objectIds:w,objectIdField:u},...b&&{attributes:b},...f>Va&&{note:`${f} features found.`}}}};async function ab({targetLayer:t,geometryFilter:e,useCurrentExtent:r},n){let{mapView:o}=Et(n),s=await ib(t,o,e,r);return JSON.stringify(s,null,2)}var lb=d.object({layerId:d.string().describe("The layerId of the layer containing the geometry by which to filter."),where:d.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:d.number().optional().describe("The buffer distance around the geometry."),units:kt.optional().describe("The units for the distance buffer.")}),cb=d.object({point:d.object({x:d.number().describe("X coordinate (longitude) from navigation result"),y:d.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:d.object({wkid:d.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:d.number().optional().describe("Optional buffer distance around the point."),units:kt.optional().describe("The units for the distance buffer.")}),ub=d.object({targetLayer:d.object({layerId:d.string().describe("The layerId of the layer containing the field from which to get a value."),where:d.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:d.array(d.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:d.array(d.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:d.union([lb,cb]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:d.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),db=L(ab,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
162
|
-
|
|
163
|
-
USE THIS TOOL FOR:
|
|
164
|
-
- "Show / display / list features where..." \u2014 finding and listing features
|
|
165
|
-
- "How many X are Y?" \u2014 counting features that match a condition
|
|
166
|
-
- "Which features..." / "Find features..." \u2014 identifying specific features
|
|
167
|
-
- Spatial queries \u2014 finding features near/within/intersecting other features
|
|
168
|
-
- Any question where the user wants to SEE or COUNT matching features
|
|
169
|
-
|
|
170
|
-
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:ub}),xp=[Ww,Qw,ob,db];var EH=new rt(xp,{handleToolErrors:!1});var pb=k.Root({...Ct(),helpInternalState:k({reducer:Mo,default:()=>({toolCallMessage:void 0})})}),mb=(t,e)=>{let r=Array.from(t.values()).find(({layerItem:s})=>s.title?.toLowerCase().includes(e.toLowerCase()));if(!r){let s=Array.from(t.values()).map(i=>i.layerItem.title).join(", ");return`Could not find a layer matching "${e}". Available layers: ${s}`}let n=Array.from(r.fieldRegistry.values()),o=n.map(s=>`- **${s.alias||s.name}** (\`${s.name}\`, ${s.type})${s.description?`: ${s.description}`:""}`).join(`
|
|
171
|
-
`);return`**${r.layerItem.title}** has ${n.length} field(s):
|
|
172
|
-
|
|
173
|
-
${o}`},fb=async({layerTitle:t},e)=>{let r=Kn(e,"layersAndFieldsRegistry");return mb(r,t)},hb=L(fb,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:d.object({layerTitle:d.string().describe("The title or partial title of the layer to list fields for.")})}),gb=k.Root({...Ct(),intent:k({reducer:(t,e)=>e}),arcgisKnowledgeMessages:k({reducer:Xn,default:()=>[]}),arcgisKnowledgeToolResult:k({reducer:(t,e)=>e,default:()=>null})});function vp(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 Wn(t){return!!t?.map&&!("activeLinkChartLayer"in t.map)}async function ti(t){!t||Wn(t)||!t.map?.diagramNodesExtent||await t.goTo(t.map.diagramNodesExtent)}function No(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)&&vp(r),{view:r}}async function Hn(t){let e=t?.configurable?.context;if(yb(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 up(n)}}else{vp(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 up(n)}}}}function yb(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 Ja=class{constructor(e){this.dataModel=e,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=Xs.fromDataModel(e)}},Xs=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($o.fromEntityType(n));for(let n of e.relationshipTypes)r.relationshipTypes.push(Za.fromRelationshipType(n));return r.identifierInfo={mappingInfo:{identifierMapsTo:_b(e.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:e.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(e.spatialReference)),r}static getDataModelTypesSummary(e){let r=e.entityTypes.map(o=>o.name).join(", "),n=e.relationshipTypes.map(o=>o.name).join(", ");return`Entity Types: ${r}.
|
|
174
|
-
Relationship Types: ${n}.`}},$o=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=wb(e.role);for(let n of e.properties){let o={name:n.name,alias:n.alias?n.alias:void 0,fieldType:n.fieldType,role:bb(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}},Za=class extends $o{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(e){let r=$o.fromEntityType(e);r.observedEndPoints=[];for(let n of e.endPoints)r.observedEndPoints.push({originEntityType:n.originEntityType,destinationEntityType:n.destinationEntityType});return r}},_b=t=>{switch(t){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return t}},wb=t=>{switch(t){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return t}};function bb(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 ri(t){return t?.signal}async function Ab(t,e){let r=await nt("arcgis_knowledge_cypher_query_prompt");return e?`${t} ${r}
|
|
175
|
-
|
|
176
|
-
Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
|
|
177
|
-
|
|
178
|
-
Attempt Number: ${e.attemptCount}
|
|
179
|
-
Execution Error: ${e.executionError}
|
|
180
|
-
Failed Query:
|
|
181
|
-
${e.failedGraphQuery}`:`${t} ${r}`}async function xb(t,e,r,n){let{graphQuery:o,explanation:s}=await ol(t,e,r,n);return{graphQuery:o,explanation:s}}async function ol(t,e,r,n,o){let s={message:await Ab(t,o),context:new Ja(e)},i=ri(n);await J({text:"Attempting to generate a cypher query from your prompt..."},n);let a=await ap(`${r}/chat`,{method:"post",body:JSON.stringify(s),headers:{"Content-Type":"application/json",token:ip.findCredential(mr.getDefault().url)?.token??""},signal:i});if(a.httpStatus!==200)throw new Error(`Graph query service returned an error: ${a.httpStatus}`,{cause:a.data});let c=!1,l=Date.now(),u=a.data.sequenceNumber,m="",f="",h=1;for(;!c;){await new Promise(b=>setTimeout(b,1e3)),await J({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,h)}`},n),h=h%3+1;let w=await ap(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:a.data.conversationId,inquiryId:a.data.inquiryId,ackSequenceNumber:u}),headers:{"Content-Type":"application/json",token:ip.findCredential(mr.getDefault().url)?.token??""},signal:i});if(w.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${w.httpStatus}`,{cause:w.data});if(w.data.context?.kind){if(w.data.context.kind!=="GraphQueryGenerationResponse")throw new Error(`Unexpected response from graph query service polling. Message: ${w.data.message}`,{cause:w.data});m=w.data.context.graphQuery,f=w.data.message||"",c=!0}else if(!w.data.hasMore)c=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");u=w.data.sequenceNumber}return{graphQuery:m,explanation:f}}function vb(t,e){qn(t,r=>{e.set(`${r.typeName}__${r.id}`,{id:r.id,typeName:r.typeName})})}function qn(t,e){if(!(!t||typeof t!="object")){if(Tb(t))for(let r of t.path)qn(r,e);else if(Ib(t))e(t);else if(Array.isArray(t))for(let r of t)qn(r,e);else if(Sb(t))for(let r of Object.values(t.properties??{}))qn(r,e)}}function Ib(t){return!t||typeof t!="object"||Array.isArray(t)?!1:"id"in t&&"typeName"in t}function Tb(t){return!t||typeof t!="object"||Array.isArray(t)?!1:t&&"path"in t&&Array.isArray(t.path)}function Sb(t){return!t||typeof t!="object"||Array.isArray(t)||"id"in t?!1:"properties"in t&&typeof t.properties=="object"}function Cb(t,e){let r=[],n=[],o=[[e.dataModel.entityTypes,r],[e.dataModel.relationshipTypes,n]];for(let[s,i]of o)for(let a of s){let c=t.getMemberIdsByType(a.name);i.push(...c)}return{entityIds:r,relationshipIds:n}}function Eb(t,e){let r={entityIds:new Array,relationshipIds:new Array},n=[],o=t?.allLayers.find(a=>a.type==="knowledge-graph")?.inclusionModeDefinition;if(!o)return{allNamedTypesFullyDynamic:!0,bindParameters:r,nonDynamicTypes:n};let s=[[e.dataModel.entityTypes,r.entityIds],[e.dataModel.relationshipTypes,r.relationshipIds]],i=!0;for(let[a,c]of s)for(let l of a){let u=o.namedTypeDefinitions.get(l.name);if(!u){i=!1,n.push(l.name);continue}if(!u.useAllData){i=!1,n.push(l.name);for(let[m]of u.members||[])c.push(m)}}return{allNamedTypesFullyDynamic:i,bindParameters:r,nonDynamicTypes:n}}var Bn=3;function Ip(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 Vn(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 kb=async({kg:t,queryParams:e,targetStructure:r,targetStructureReducer:n,requestOptions:o,queryRowLimit:s,queryTimeoutMs:i})=>{let a=null,c=r,l=new AbortController,u=o?.signal,m=()=>{l.abort(u?.reason)};u&&(u.aborted?l.abort(u.reason):u.addEventListener("abort",m,{once:!0}));try{let f=await _y(t,e,o);a=f.resultHeader;let h=f.resultRowsStream.getReader(),w=0,b=Date.now(),v=!1;for(;;){let{done:g,value:x}=await h.read();if(g)break;if(!v&&i&&Date.now()-b>i)return l.abort(),{type:"timeout"};for(let S of x){if(w++,s&&w>s)return l.abort(),{type:"success",rowLimitReached:!0,resultHeader:a,processedResult:c};c=n(c,S)}}}catch(f){return l.signal.aborted?{type:"aborted"}:{type:"error",errorMessage:Vn(f),error:f}}finally{u?.removeEventListener("abort",m)}return{type:"success",rowLimitReached:!1,resultHeader:a,processedResult:c}};async function Tp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c,config:l}){let u;for(let m=1;m<=Bn;m++){let f;try{f=await ol(t,r.dataModel,n,l,u)}catch(b){return{type:"generation-error",errorMessage:Vn(b),error:b}}await J({text:`Attempting to execute query: ${f.graphQuery.substring(0,500)}${f.graphQuery.length>500?"...":""}`},l);let h=await kb({kg:r,queryParams:new yp({openCypherQuery:f.graphQuery,bindParameters:e}),targetStructure:o,targetStructureReducer:s,requestOptions:i,queryRowLimit:a,queryTimeoutMs:c}),w=h.type==="aborted"?"Query execution was aborted.":h.type==="timeout"?"Query execution timed out.":h.type==="error"?`Query failed with error: ${h.errorMessage}`:"";if(h.type==="success")return{type:"success",graphQuery:f.graphQuery,explanation:f.explanation,rowLimitReached:h.rowLimitReached,resultHeader:h.resultHeader,processedResult:h.processedResult};if(h.type==="aborted")return{type:"aborted",errorMessage:w,graphQuery:f.graphQuery,explanation:f.explanation};if(m>=Bn)return h.type==="timeout"?{type:"timeout",errorMessage:w,graphQuery:f.graphQuery,explanation:f.explanation}:{type:"execution-error",errorMessage:w,error:h.error,graphQuery:f.graphQuery,explanation:f.explanation};u={failedGraphQuery:f.graphQuery,executionError:w,attemptCount:m},await J({text:`Attempt ${m} failed with error: ${w}. Retrying...`},l)}throw new Error(`Failed to execute generated cypher due to an unexpected error after ${Bn} attempts.`)}var Ob=async({kg:t,searchQuery:e,typeCategoryFilter:r,namedTypesFilter:n,searchResultLimit:o,requestOptions:s})=>{let i=[],a=[r];r==="both"&&!t.serviceDefinition.serviceCapabilities.searchCapabilities.searchTypeFilterCapabilities.includes("esriTypeBoth")&&(a=["entity","relationship"]);let c=o??1/0;try{for(let l of a){let u=c-i.length;if(u<=0)break;let m=(await wy(t,new by({searchQuery:e,typeCategoryFilter:l,namedTypesFilter:n??void 0,num:u}),s)).resultRowsStream.getReader(),f=!1;for(;!f;){let{done:h,value:w}=await m.read();if(h){f=!0;break}for(let b of w)for(let v of b)i.push(v)}}}catch(l){let u=Vn(l);return s?.signal?.aborted?{type:"aborted",errorMessage:u,error:l}:{type:"error",errorMessage:u,error:l}}return{type:"success",results:i}},Sp="IMPORTANT: The generated cypher query must return entire entities and relationships ONLY.";async function Cp({prompt:t,view:e,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:n=!1}){let o=[t];if(n&&o.push(Sp),!Wn(e)){let u=await nt("arcgis_knowledge_current_lc_context"),m=Cb(e.map,r);return o.push(u),{enhancedPrompt:o.join(`
|
|
182
|
-
|
|
183
|
-
`),bindParameters:m,allNamedTypesFullyDynamic:!1}}let s=e.map,{allNamedTypesFullyDynamic:i,bindParameters:a,nonDynamicTypes:c}=Eb(s,r);if(i)return{enhancedPrompt:o.join(`
|
|
184
|
-
|
|
185
|
-
`),bindParameters:a,allNamedTypesFullyDynamic:!0};let l=(await nt("arcgis_knowledge_current_map_context")).replaceAll("{nonDynamicTypes}",JSON.stringify(c));return o.push(l),{enhancedPrompt:o.join(`
|
|
186
|
-
|
|
187
|
-
`),bindParameters:a,allNamedTypesFullyDynamic:i}}async function Pb(t,e,r,n,o,s){let{view:i}=o,a=await Tp({prompt:t,bindParameters:e,kg:r,graphQueryServiceUrl:n,targetStructure:new Map,targetStructureReducer:(f,h)=>{for(let w of h)vb(w,f);return f},requestOptions:{signal:ri(s),timeout:s?.timeout},config:s});if(a.type!=="success"){let f=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;throw new Error(`Failed to add records to the link chart. ${f}`)}let{graphQuery:c,explanation:l,processedResult:u}=a,m=Array.from(u.values());return await J({text:`Query Results parsed into ${m.length} unique relationships and entities. Atempting to add to link chart...`},s),!Wn(i)&&i?.map?(await i.map.addRecords(m),await ti(i),{generatedQuery:c,explanation:l,addedIdTypePairs:m}):(await i?.map?.allLayers.find(f=>f.type==="knowledge-graph")?.addRecords(m),{generatedQuery:c,explanation:l,addedIdTypePairs:m})}var Js="addRecords",Mb=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to add records to the link chart.")}),Rb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Hn(e),n=No(e),{view:o}=n,s=mr.getDefault().helperServices,{enhancedPrompt:i,bindParameters:a,allNamedTypesFullyDynamic:c}=await Cp({prompt:t,view:o,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!0});if(c)return{toolName:Js,status:"success",summary:"No records have been added to the map because all data in the knowledge graph is contained in the map.",details:{generatedQuery:"N/A",explanation:"All named types in the knowledge graph are fully dynamic and therefore all data is already contained in the map. No records have been added.",addedIdTypePairs:[]}};try{let{generatedQuery:l,explanation:u,addedIdTypePairs:m}=await Pb(i,a,r,`${s.aiAssistantServices.url}${s.aiAssistantServices.graphQueryAssistant}`,n,e);return{toolName:Js,status:"success",summary:`Records added successfully. Cypher Query used: ${l}
|
|
188
|
-
|
|
189
|
-
Number of records added: ${m.length}`,details:{generatedQuery:l,explanation:u,addedIdTypePairs:m}}}catch(l){let u=Vn(l);return{toolName:Js,status:"error",errorMessage:`Failed to add records to the link chart. ${u}`,error:l}}},$b=L(Rb,{name:Js,description:`Adds records (entities or relationships) to the current link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt. "add to new link chart" is not a valid prompt for this tool.
|
|
190
|
-
|
|
191
|
-
example prompts:
|
|
192
|
-
- "add all suppliers and the parts they produce to the link chart"
|
|
193
|
-
- "show me the competitors of company x and add them to the link chart"
|
|
194
|
-
- "add the relationships between company x and company y to the link chart"
|
|
195
|
-
- "expand all the companies"
|
|
196
|
-
- "expand company x through all the buildings it owns"
|
|
197
|
-
- "connect company x and company y"
|
|
198
|
-
- "connect all buildings on the link chart"
|
|
199
|
-
`,schema:Mb});async function Nb(t,e){return await e.map?.applyLayout(t),await ti(e),{appliedLayout:t}}var Qa="applyLayout",Lb=d.object({layout:d.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),Db=async({layout:t},e)=>{let{view:r}=No(e);if(Wn(r))return{toolName:Qa,status:"error",errorMessage:"The applyLayout tool can only be used with a LinkChartView.",error:new Error};{let{appliedLayout:n}=await Nb(t,r);return{toolName:Qa,status:"success",summary:`Successfully applied layout: ${n}.`,details:{appliedLayout:n}}}},Fb=L(Db,{name:Qa,description:"Apply a diagram layout to the link chart",schema:Lb});async function jb(t,e){return e.map?.changeNonspatialDataDisplay(t),await ti(e),{appliedNonspatialDataDisplayMode:t}}var Ya="changeNonspatialVisibility",zb=d.object({setting:d.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Ub=async({setting:t},e)=>{let{view:r}=No(e);if(Wn(r))return{toolName:Ya,status:"error",errorMessage:"The changeNonspatialVisibility tool can only be used with a LinkChartView.",error:new Error};{let{appliedNonspatialDataDisplayMode:n}=await jb(t,r);return{toolName:Ya,status:"success",summary:`Successfully applied nonspatial visibility setting: ${n}.`,details:{appliedNonspatialDataDisplayMode:n}}}},qb=L(Ub,{name:Ya,description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:zb});async function Bb(t,e,r,n,o){let s,i="";for(let a=1;a<=Bn;a++){let{graphQuery:c,explanation:l}=await ol(t,e.dataModel,r,o,s);try{await J({text:`Attempting to create link chart from derived query: ${c}`},o);let u=await yy.fromCypherQuery(e,new yp({openCypherQuery:c}));await J({text:"Link chart created successfully, loading..."},o),await u.load();let m=n.map;return n.map=u,await n.when(),await mp.whenOnce(()=>!n.updating),u.entityCount===0&&u.relationshipCount===0?(n.map===u&&(n.map=m),u.destroy(),{type:"error",errorMessage:`Query returned no results. Cypher Query used to create the link chart:
|
|
200
|
-
${c}
|
|
201
|
-
|
|
202
|
-
Explanation: ${l}`}):(await ti(n),{type:"success",graphQuery:c,explanation:l})}catch(u){let m=Vn(u);if(a>=Bn){i=m;break}s={failedGraphQuery:c,executionError:m,attemptCount:a},await J({text:`Attempt ${a} to create link chart failed with error: ${m}. Retrying ...`},o)}}return{type:"error",errorMessage:`Failed to create link chart after ${Bn} attempts. Last error: ${i}`}}var Zs="createLinkChart",Kb=d.object({prompt:d.string().describe("The user's inquiry and context required in order to generate a cypher query that will be used to create a link chart visualization. Only include information relevant to generating a cypher query. Do not suggest entity types, relationship types or properties. Do not include limits or formatting instructions for the query results unless specifically requested by the user. The prompt should be focused on the data the user wants to see in the link chart, not how to generate it.")}),Wb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Hn(e),{view:n}=No(e);if(Wn(n))return{toolName:Zs,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let o=mr.getDefault().helperServices,s=await Bb(`${t}
|
|
203
|
-
|
|
204
|
-
${Sp}`,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,n,e);if(s.type==="error")return{toolName:Zs,status:"error",errorMessage:s.errorMessage,error:new Error};let{graphQuery:i,explanation:a}=s;return{toolName:Zs,status:"success",summary:`Link chart created successfully. Cypher Query used to create the link chart:
|
|
205
|
-
${i}
|
|
206
|
-
|
|
207
|
-
Explanation: ${a}`,details:{generatedQuery:i,explanation:a}}}},Hb=L(Wb,{name:Zs,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:Kb}),Xa="queryGraphData",Vb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. Only include entity types, relationship types or properties if they are provided in the user prompt or prior steps. Do not suggest entity types, relationship types or properties. Do not include limits, information on what to return, instructions on how to write the query, or formatting instructions for the query results unless specifically requested by the user.")}),Gb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Hn(e),n=mr.getDefault().helperServices,o=t,s=null,i=null;try{({view:i}=No(e))}catch{}i&&({enhancedPrompt:o,bindParameters:s}=await Cp({prompt:t,view:i,knowledgeGraph:r,includeReturnEntityAndRelationshipContext:!1}));let a=await Tp({prompt:o,bindParameters:s,kg:r,graphQueryServiceUrl:`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(b,v)=>(b.push(v),b),requestOptions:{signal:ri(e),timeout:e?.timeout},config:e});if(a.type!=="success"){let b=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;return{toolName:Xa,status:"error",errorMessage:`Failed to query the knowledge graph. ${b}`,error:"error"in a?a.error:null}}let{graphQuery:c,explanation:l,processedResult:u,resultHeader:m}=a,f=m.headerKeys;for(let b of u)for(let v of b)qn(v,g=>Ip(g));let h=50,w=u.slice(0,h).map(b=>JSON.stringify(b));return{toolName:Xa,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
208
|
-
|
|
209
|
-
\`\`\`cypher
|
|
210
|
-
${c}
|
|
211
|
-
\`\`\`
|
|
212
|
-
|
|
213
|
-
Query Results:
|
|
214
|
-
${w.length} result(s) found.
|
|
215
|
-
|
|
216
|
-
Column Headers: ${f.join(", ")}
|
|
217
|
-
|
|
218
|
-
${w.length>h?`Showing top ${h} results:
|
|
219
|
-
|
|
220
|
-
`:`Results:
|
|
221
|
-
|
|
222
|
-
`}${w.join(`
|
|
223
|
-
`)}
|
|
224
|
-
`,details:{generatedQuery:c,explanation:l,resultHeader:m,queryResults:u}}},Jb=L(Gb,{name:Xa,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:Vb}),el="generateCypher",Zb=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Qb=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Hn(e),n=mr.getDefault().helperServices;try{let{graphQuery:o,explanation:s}=await xb(t,r.dataModel,`${n.aiAssistantServices.url}${n.aiAssistantServices.graphQueryAssistant}`,e);return{toolName:el,status:"success",summary:`Generated Graph Query:
|
|
225
|
-
${o}
|
|
226
|
-
|
|
227
|
-
Explanation: ${s}`,details:{generatedQuery:o,explanation:s}}}catch(o){let s=Vn(o);return{toolName:el,status:"error",errorMessage:`Failed to generate Cypher query. ${s}`,error:o}}},Yb=L(Qb,{name:el,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:Zb}),Xb=t=>{let e=t.dataModel,r=new Map;for(let a of e.searchIndexes)if(a.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[c,l]of a.searchProperties.entries()){let u=r.get(c)??new Set;l.propertyNames.forEach(m=>u.add(m)),r.set(c,u)}let n=e.entityTypes.filter(a=>r.has(a.name)),o=e.relationshipTypes.filter(a=>r.has(a.name)),s=`Entity Types:
|
|
228
|
-
${n.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
|
|
229
|
-
`)}`,i=`Relationship Types:
|
|
230
|
-
${o.map(({name:a})=>`${a}: [${Array.from(r.get(a)??[]).join(", ")}]`).join(`
|
|
231
|
-
`)}`;return`${s}
|
|
232
|
-
|
|
233
|
-
${i}`};async function eA(t,e,r){let n=await nt("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:t,dataModelForSearch:Xb(e)},s=d.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),i=d.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),a=d.array(d.enum(e.dataModel.entityTypes.map(l=>l.name).concat(e.dataModel.relationshipTypes.map(l=>l.name)))).min(1),c=d.object({query:d.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:a.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:s,resultLimit:i});return await Po({promptText:n,inputVariables:o,schema:c,config:r})}var tl="searchGraphData",tA=d.object({prompt:d.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),rA=async({prompt:t},e)=>{let{knowledgeGraph:r}=await Hn(e);await J({text:"Generating search query for the user inquiry"},e);let n=await eA(t,r,e);await J({text:"Executing graph search with generated search query"},e);let o=await Ob({kg:r,searchQuery:n.query,typeCategoryFilter:n.typeCategoryFilter,namedTypesFilter:n.typeFilters,searchResultLimit:n.resultLimit,requestOptions:{signal:ri(e),timeout:e?.timeout}});if(o.type!=="success")return{toolName:tl,status:"error",errorMessage:o.errorMessage,error:"error"in o?o.error:null};for(let a of o.results)qn(a,c=>Ip(c));let s=10,i=o.results.slice(0,s);return{toolName:tl,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
|
|
234
|
-
Query: ${n.query}
|
|
235
|
-
Type Category Filter: ${n.typeCategoryFilter}
|
|
236
|
-
Named Type Filters: ${n.typeFilters?n.typeFilters.join(", "):"None"}
|
|
237
|
-
Result Limit: ${n.resultLimit??"No limit"}
|
|
238
|
-
|
|
239
|
-
Search Results: ${o.results.length} result(s) found.
|
|
240
|
-
|
|
241
|
-
${o.results.length>s?`Showing top ${s} results:
|
|
242
|
-
|
|
243
|
-
`:""}${i.map(a=>JSON.stringify(a)).join(`
|
|
244
|
-
`)}`,details:{generatedSearchQuery:n,searchResults:o.results}}},nA=L(rA,{name:tl,description:`
|
|
245
|
-
Search the knowledge graph using one or more search texts, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.
|
|
246
|
-
Example prompts:
|
|
247
|
-
- "Find 'Bradley'"
|
|
248
|
-
- "find the person john smith"
|
|
249
|
-
- "find all people named smith"
|
|
250
|
-
- "Find all references to 'delayed parts shipment'"
|
|
251
|
-
- "Find all reports authored by someone with the title of 'Researcher'"
|
|
252
|
-
- "Find the first 5 reports where summary mentions flood zoning near Sacramento, and the organization name is the City of Sacramento Utilities, and tags containing stormwater".
|
|
253
|
-
- "Search for all john smiths and show their global ids`,schema:tA});var WH=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
254
|
-
This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
|
|
255
|
-
|
|
256
|
-
Supported actions:
|
|
257
|
-
- **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
|
|
258
|
-
- **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
|
|
259
|
-
- **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
|
|
260
|
-
- **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
|
|
261
|
-
- **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
|
|
262
|
-
- **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
|
|
263
|
-
- **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").
|
|
264
|
-
- **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
|
|
265
|
-
|
|
266
|
-
_Example: “Zoom to Texas”_
|
|
267
|
-
_Example: “Go to the water mains layer”_
|
|
268
|
-
_Example: “Zoom to to the extent of my link chart”_
|
|
269
|
-
_Example: “Center the map on San Francisco at scale 50000”_
|
|
270
|
-
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
271
|
-
_Example: “Go to the Downtown bookmark”_
|
|
272
|
-
_Example: “Where is Mount Rainier?”_`;var AV=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
|
|
273
|
-
_Example: “Color points by sales amount”_
|
|
274
|
-
_Example: “Show population density with a color gradient”_
|
|
275
|
-
_Example: “Create a relationship map between height and depth”_
|
|
276
|
-
_Example: “Vary circle sizes according to population”_`;var WV=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
|
|
277
|
-
The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
|
|
278
|
-
_Example: “Only show stations where Brand is Shell”_
|
|
279
|
-
_Example: “Make Shell stations stand out on the map”_
|
|
280
|
-
_Example: “Gray out all stations that aren’t Shell”_
|
|
281
|
-
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.
|
|
282
|
-
_Example: “How many features are there?”_
|
|
283
|
-
_Example: “What’s the average population?”_
|
|
284
|
-
_Example: “Which values are in the status field?”_
|
|
285
|
-
|
|
286
|
-
This agent does NOT handle help/metadata requests such as listing available layers, listing field names/columns/attributes for a layer, or capability guidance.`;var lG=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
|
|
287
|
-
|
|
288
|
-
_Example: “Tell me about this map”_
|
|
289
|
-
_Example: “List all layers in this map”_
|
|
290
|
-
_Example: “List fields in protected areas layer”_
|
|
291
|
-
_Example: “What agents are available to me?”_
|
|
292
|
-
_Example: “What can you do?”_
|
|
293
|
-
_Example: “What can I ask”_
|
|
294
|
-
|
|
295
|
-
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.
|
|
296
|
-
|
|
297
|
-
IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond that the requested action is not supported.
|
|
298
|
-
_Example: "Create a chart"_
|
|
299
|
-
_Example: "Create a table"_`;var SG=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
|
|
300
|
-
This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
|
|
301
|
-
For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
|
|
302
|
-
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
|
|
303
|
-
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.
|
|
304
|
-
This agent is designed to handle requests that manipulate the specific link chart.
|
|
305
|
-
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,
|
|
306
|
-
and can alternatively use those queries to create a new link chart visualization from the results if requested.
|
|
307
|
-
|
|
308
|
-
Supported actions:
|
|
309
|
-
- **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.
|
|
310
|
-
- **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.
|
|
311
|
-
- **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.
|
|
312
|
-
- **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
|
|
313
|
-
- **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.
|
|
314
|
-
- **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.
|
|
315
|
-
- **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.
|
|
316
|
-
|
|
317
|
-
_example: "Change the layout to hierarchical-bottom-to-top"_
|
|
318
|
-
_example: "Apply radial-root-centric layout"_
|
|
319
|
-
_example: "Show nonspatial data"_
|
|
320
|
-
_example: "Hide nonspatial data"_
|
|
321
|
-
_example: "Turn off nonspatial visibility"_
|
|
322
|
-
_example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
|
|
323
|
-
_example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
|
|
324
|
-
_example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
|
|
325
|
-
_example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
|
|
326
|
-
_example: "Find all people who work for Microsoft and put them on a new link chart"_
|
|
327
|
-
_example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
|
|
328
|
-
_example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
|
|
329
|
-
_example: "Find all the products supplied by Supplier X and add them to my visualization"_
|
|
330
|
-
_example: "Expand the link chart from 'Entity D' to show its direct connections"_
|
|
331
|
-
_example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
|
|
332
|
-
_example: "Connect Emma and Rob on the link chart if there is a relationship between them"
|
|
333
|
-
_example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_
|
|
334
|
-
_example: "Show me all entities with a name similar to 'Smith' and add them to the link chart"_
|
|
335
|
-
_example: "Find reports in my graph that have a title similar to 'Quarterly Earnings'"_
|
|
336
|
-
_example: "Find John Smith and all people he has made phone calls to in the last year"_
|
|
337
|
-
_example: "What is the average age of all people who work for Esri?"_`;var iA=(t,e)=>{if(t.length!==e.length)throw new Error("Vectors must be the same length");let r=0,n=0,o=0;for(let a=0;a<t.length;++a){let c=t[a],l=e[a];r+=c*l,n+=c*c,o+=l*l}let s=Math.sqrt(n*o);if(s===0)return 0;let i=r/s;return Math.max(-1,Math.min(1,i))},Ep=Vs,ot=Po;var Pe=J,kp=np,Op=iA;var oi=()=>Ct();var il={};xl(il,{JsonPatchError:()=>V,_areEquals:()=>jo,applyOperation:()=>fr,applyPatch:()=>Jn,applyReducer:()=>dA,deepClone:()=>cA,getValueByPointer:()=>ci,validate:()=>Mp,validator:()=>ui});var aA=(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)o.hasOwnProperty(s)&&(n[s]=o[s])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),lA=Object.prototype.hasOwnProperty;function ii(t,e){return lA.call(t,e)}function ai(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var o in t)ii(t,o)&&n.push(o);return n}function ce(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function li(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function Ue(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Do(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function si(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(si(t[e]))return!0}else if(typeof t=="object"){for(var n=ai(t),o=n.length,s=0;s<o;s++)if(si(t[n[s]]))return!0}}return!1}function Pp(t,e){var r=[t];for(var n in e){var o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(n+": "+o)}return r.join(`
|
|
338
|
-
`)}var Fo=(function(t){aA(e,t);function e(r,n,o,s,i){var a=this.constructor,c=t.call(this,Pp(r,{name:n,index:o,operation:s,tree:i}))||this;return c.name=n,c.index=o,c.operation=s,c.tree=i,Object.setPrototypeOf(c,a.prototype),c.message=Pp(r,{name:n,index:o,operation:s,tree:i}),c}return e})(Error);var V=Fo,cA=ce,Gn={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=ci(r,this.path);n&&(n=ce(n));var o=fr(r,{op:"remove",path:this.from}).removed;return fr(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=ci(r,this.from);return fr(r,{op:"add",path:this.path,value:ce(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:jo(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},uA={add:function(t,e,r){return li(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Gn.move,copy:Gn.copy,test:Gn.test,_get:Gn._get};function ci(t,e){if(e=="")return t;var r={op:"_get",path:e};return fr(t,r),r.value}function fr(t,e,r,n,o,s){if(r===void 0&&(r=!1),n===void 0&&(n=!0),o===void 0&&(o=!0),s===void 0&&(s=0),r&&(typeof r=="function"?r(e,0,t,e.path):ui(e,0)),e.path===""){var i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=ci(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=jo(t,e.value),i.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new V("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=ce(t));var a=e.path||"",c=a.split("/"),l=t,u=1,m=c.length,f=void 0,h=void 0,w=void 0;for(typeof r=="function"?w=r:w=ui;;){if(h=c[u],h&&h.indexOf("~")!=-1&&(h=Do(h)),o&&(h=="__proto__"||h=="prototype"&&u>0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&f===void 0&&(l[h]===void 0?f=c.slice(0,u).join("/"):u==m-1&&(f=e.path),f!==void 0&&w(e,0,t,f)),u++,Array.isArray(l)){if(h==="-")h=l.length;else{if(r&&!li(h))throw new V("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);li(h)&&(h=~~h)}if(u>=m){if(r&&e.op==="add"&&h>l.length)throw new V("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var i=uA[e.op].call(e,l,h,t);if(i.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(u>=m){var i=Gn[e.op].call(e,l,h,t);if(i.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(l=l[h],r&&u<m&&(!l||typeof l!="object"))throw new V("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Jn(t,e,r,n,o){if(n===void 0&&(n=!0),o===void 0&&(o=!0),r&&!Array.isArray(e))throw new V("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=ce(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=fr(t,e[i],r,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function dA(t,e,r){var n=fr(t,e);if(n.test===!1)throw new V("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function ui(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new V("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Gn[t.op]){if(typeof t.path!="string")throw new V("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new V('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new V("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new V("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&si(t.value))throw new V("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,s=n.split("/").length;if(o!==s+1&&o!==s)throw new V("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new V("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},a=Mp([i],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new V("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new V("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Mp(t,e,r){try{if(!Array.isArray(t))throw new V("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Jn(ce(e),ce(t),r||!0);else{r=r||ui;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(o){if(o instanceof V)return o;throw o}}function jo(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),o,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!jo(t[o],e[o]))return!1;return!0}if(r!=n)return!1;var a=Object.keys(t);if(s=a.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=s;o--!==0;)if(i=a[o],!jo(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var ul={};xl(ul,{compare:()=>wA,generate:()=>al,observe:()=>_A,unobserve:()=>yA});var ll=new WeakMap,pA=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),mA=(function(){function t(e,r){this.callback=e,this.observer=r}return t})();function fA(t){return ll.get(t)}function hA(t,e){return t.observers.get(e)}function gA(t,e){t.observers.delete(e.callback)}function yA(t,e){e.unobserve()}function _A(t,e){var r=[],n,o=fA(t);if(!o)o=new pA(t),ll.set(t,o);else{var s=hA(o,e);n=s&&s.observer}if(n)return n;if(n={},o.value=ce(t),e){n.callback=e,n.next=null;var i=function(){al(n)},a=function(){clearTimeout(n.next),n.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return n.patches=r,n.object=t,n.unobserve=function(){al(n),clearTimeout(n.next),gA(o,n),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new mA(e,n)),n}function al(t,e){e===void 0&&(e=!1);var r=ll.get(t.object);cl(r.value,t.object,t.patches,"",e),t.patches.length&&Jn(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function cl(t,e,r,n,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=ai(e),i=ai(t),a=!1,c=!1,l=i.length-1;l>=0;l--){var u=i[l],m=t[u];if(ii(e,u)&&!(e[u]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof m=="object"&&m!=null&&typeof f=="object"&&f!=null&&Array.isArray(m)===Array.isArray(f)?cl(m,f,r,n+"/"+Ue(u),o):m!==f&&(a=!0,o&&r.push({op:"test",path:n+"/"+Ue(u),value:ce(m)}),r.push({op:"replace",path:n+"/"+Ue(u),value:ce(f)}))}else Array.isArray(t)===Array.isArray(e)?(o&&r.push({op:"test",path:n+"/"+Ue(u),value:ce(m)}),r.push({op:"remove",path:n+"/"+Ue(u)}),c=!0):(o&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),a=!0)}if(!(!c&&s.length==i.length))for(var l=0;l<s.length;l++){var u=s[l];!ii(t,u)&&e[u]!==void 0&&r.push({op:"add",path:n+"/"+Ue(u),value:ce(e[u])})}}}function wA(t,e,r){r===void 0&&(r=!1);var n=[];return cl(t,e,n,"",r),n}var XG=Object.assign({},il,ul,{JsonPatchError:Fo,deepClone:ce,escapePathComponent:Ue,unescapePathComponent:Do});var xA=vl`:host{display:block;height:100%}.margin-lg{margin:var(--calcite-spacing-lg)}.display-flex-row{display:flex;flex-direction:row}.assistant-split-container{display:flex;width:100%;height:calc(100vh - 78px);overflow:hidden;border-radius:10px}.assistant-panel{display:flex;flex-direction:column;height:100%;border:1px solid var(--calcite-color-surface-3);background-color:var(--calcite-color-surface-2);overflow:hidden}.chat-panel{min-width:320px}.builder-panel{min-width:320px;max-width:100%;border-left:1px solid var(--calcite-color-surface-3)}.panel-actions{display:flex;gap:8px;padding:6px;align-items:center}.builder-header,.builder-footer{padding:10px;background:var(--calcite-color-surface-1);border-bottom:1px solid var(--calcite-color-surface-3)}.builder-content{flex:1;overflow:auto;padding:12px}.builder-content pre{white-space:pre-wrap;word-wrap:break-word;max-height:100%;overflow:auto}.builder-actions{display:flex;gap:6px;align-items:center}.padding-left-10{padding-left:10px}.chat-container{display:flex;flex-direction:column;gap:0px;max-width:600px;height:75%;background-color:var(--calcite-color-surface-4);padding:1px}.chat-container_expanded{display:flex;flex-direction:column;gap:0px;max-width:100%;height:95%;background-color:var(--calcite-color-surface-1);border-radius:10px;padding:10px}.chat-panel{--calcite-color-focus: var(--calcite-color-brand);--calcite-panel-border-color: var(--calcite-color-border-2);--calcite-internal-panel-header-vertical-padding: 0px;--calcite-panel-header-content-space: 0px;border:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);height:100%}.header-content{display:flex;align-items:center;gap:var(--calcite-spacing-sm);height:65px;box-sizing:border-box;padding-inline-start:var(--calcite-space-2xl)}@media(resolution:1.25dppx),(resolution:1.75dppx){.chat-panel{margin-top:.5px}}.header-title{font-size:var(--calcite-font-size-md);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-text-1)}.beta-chip{--calcite-chip-corner-radius: var(--calcite-corner-radius-half)}.chat-panel calcite-card,.chat-panel calcite-text-area,.chat-panel calcite-button,.chat-panel .chat-messages,.chat-panel .chat-input{--calcite-color-focus: var(--calcite-color-brand)}.assistant-followup-chip:focus{outline:2px solid var(--calcite-color-brand)}.chat-panel-heading{font-size:var(--calcite-font-size-0);font-weight:var(--calcite-font-weight-medium);color:var(--calcite-color-surface-1, var(--calcite-color-text-1))}.chat-messages{display:flex;flex-direction:column;gap:20px;padding:4px;height:100%;overflow-y:auto}.user-message{align-self:flex-end;background:var(--calcite-color-brand);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-brand);--calcite-card-border-color: var(--calcite-color-brand);color:var(--calcite-color-text-inverse);text-align:left}.system-message{align-self:flex-start;background:var(--calcite-color-surface-3);border-radius:8px;max-width:90%;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4);color:var(--calcite-color-inverse);text-align:left}.loader-message{align-self:flex-start;background:var(--calcite-color-surface-4);border-radius:8px;--calcite-card-corner-radius: 8px;--calcite-card-background-color: var(--calcite-color-surface-4);--calcite-card-border-color: var(--calcite-color-surface-4)}.message-content{padding:0;font-size:14px}.response-message.message-content>p:first-of-type{margin-top:0}.message-content img{max-width:100%;height:auto;display:block;object-fit:contain}.message-content-pad{padding-bottom:10px;font-size:14px}.message-content-summary{padding-bottom:14px}.message-content-alignment{display:flex;align-items:center;gap:var(--calcite-spacing-md);font-size:var(--calcite-font-size--1);color:var(--calcite-color-text-1)}.padding-top-10{padding-top:10px}.padding-right-8{padding-right:8px}.padding-left-right-5{padding-right:5px;padding-left:5px}.chip-content{padding:5px 5px 5px 0}.chat-input{display:flex;flex-direction:row;flex-grow:1}.table-cell{--calcite-table-cell-background: var(--calcite-color-surface-4)}.cursor-pointer{cursor:pointer}.notice-border-color{--temp-initial-brand: var(--calcite-color-brand)}.notice-border-color calcite-notice{--calcite-color-brand: #ddd;--calcite-icon-color: var(--temp-initial-brand)}.notice-border-color calcite-notice *{--calcite-color-brand: var(--temp-initial-brand)}.solution-card{padding:5px 0;text-decoration:none;display:block;width:100%;cursor:pointer}.solution-card calcite-card{display:flex;flex-direction:column;max-width:520px;overflow:hidden;--calcite-card-corner-radius: var(--calcite-corner-radius-round) !important;--calcite-card-shadow: var(--calcite-shadow-sm);--calcite-card-background-color: var(--calcite-card-background-color) }.solution-card div[slot=thumbnail]{max-height:100%;width:100%;position:relative;&:after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;transition:all .15s ease-in-out}}.solution-card div[slot=thumbnail] img{max-height:100%;width:100%;object-fit:cover}.solution-card span[slot=description]{padding-top:10px}.solution-card calcite-chip{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);visibility:hidden;pointer-events:none;opacity:0;transition:all .15s ease-in-out;z-index:9999}.solution-card:hover calcite-chip{visibility:visible;opacity:1}.solution-card:hover div[slot=thumbnail]:after{background-color:#00000080}.solution-card:hover h3{text-decoration:underline}.solution-card:focus{outline:2px solid var(--calcite-color-brand)}.references-container{padding-top:10px;display:block}.references-container.collapsed{display:none}.width-100{width:100%}.disclaimer-div{display:flex;align-items:center;gap:var(--calcite-spacing-sm);font-size:var(--calcite-font-size--0);color:var(--calcite-color-text-1)}.display-none{display:none}.chat-messages calcite-fab{position:absolute;bottom:16px;left:50%;transform:translate(-50%);z-index:999}.icon-color-background{--calcite-button-icon-color: var(--calcite-color-surface-1)}#closeAssistantButton{--calcite-action-text-color: var(--calcite-color-text-1)}.icon-color-background:focus{--calcite-color-focus: var(--calcite-color-surface-1)}@media(max-width:430px){.solution-card .solution-snippet{display:none}}.height-32-flex-auto{height:32px;flex:0 0 auto}.margin-top-0.message-content>p:first-of-type{margin-top:0}a:not(.solution-card){color:var(--calcite-link-text-color, var(--calcite-color-text-link));cursor:pointer;text-decoration:none;line-height:inherit;background-image:linear-gradient(currentColor,currentColor),linear-gradient(var(--calcite-color-brand-underline),var(--calcite-color-brand-underline));background-position-x:0%,100%;background-position-y:min(1.5em,100%);background-repeat:no-repeat,no-repeat;background-size:0% 1px,100% 1px;transition-property:background-size,color;transition-duration:var(--calcite-animation-timing, .15s);transition-timing-function:ease-in-out;outline-color:transparent;position:relative}a:not(.solution-card):hover{background-size:100% 1px,100% 1px}a:not(.solution-card):focus{outline:2px solid var(--calcite-color-brand);outline-offset:2px;outline-color:var(--calcite-color-brand)}a:not(.solution-card):active{color:var(--calcite-color-brand-press)}`;async function Ae(t,e){let r=Object.entries(t).find(([n])=>n.endsWith(`/${e}.md`));if(!r)throw new Error(`Prompt not found: ${e}
|
|
339
|
-
Available prompts:
|
|
340
|
-
${Object.keys(t).join(`
|
|
341
|
-
`)}`);return await r[1]()}function hi(t){return t?.configurable?.context?.translations}function Np(t){if(typeof window>"u"||t.length<=1)return;let e=t.map(n=>n.solution.id),r=t.map(n=>n.solution.title);window.dispatchEvent(new CustomEvent("searchTermSet",{detail:{scope:"all-solutions",searchTerm:""}})),window.dispatchEvent(new CustomEvent("solutionMatchesFromAssistant",{detail:{solutionIds:e,solutionTitles:r},bubbles:!0,composed:!0})),window.dispatchEvent(new CustomEvent("navTabSelected",{detail:{tabType:"all-solutions"}}))}function Lp(t){if(typeof window>"u"||!t)return;let e=new CustomEvent("solutionIDFromAssistant",{detail:t,bubbles:!0,composed:!0});window.dispatchEvent(e)}var vA=I.object({needsContext:I.boolean().describe("True when the explorer query requires added context from prior turns."),rewrittenQuery:I.string().min(1).describe("The final query to send to doc AI. Keep original query if no context is needed.")}),Rp=t=>t?.signal?.aborted??!1,Dp=Object.assign({"./prompts/solutions_explorer_description.md":()=>import("./AS6VINEU.js").then(t=>t.default),"./prompts/transformQuery.md":()=>import("./MFVXFKKM.js").then(t=>t.default)});function IA(t){return t.replace(/<sup>\[\[(\d+)\]\]\(([^)]+)\)<\/sup>/g,'<sup><a href="$2">[$1]</a></sup>')}function TA(t){return t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(e,r,n)=>`<img src="${n}" alt="${r}" style="width: 100%;">`)}function Fp(t){let e=(t??"").trim();if(!e)return"en";let r=e.split(/[-_]/)[0]?.toLowerCase();return r?r.slice(0,2):"en"}function SA(t,e){let r=[];return(e?.configurable?.context?.configContext.allCards??[]).forEach(n=>{let o=n.title;if(!o)return;let s=new RegExp(`(?<![\\p{L}\\p{N}])${o}(?![\\p{L}\\p{N}])`,"giu"),i=!1;t=t.replace(s,(a,c,l)=>{let u=l.slice(0,c);return/<img[^>]*alt\s*=\s*["'][^"']*$/i.test(u)?a:(i=!0,`<a href="" target="solutionId:${n.deployCommonId}">${o}</a>`)}),i&&r.push({solution:{title:n.title,id:n.deployCommonId,snippet:n.snippet,description:n.description},score:100})}),{source:t,allMatches:r}}function CA(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/chat`:null}function jp(t){return t&&t.helperServices.aiAssistantServices?`${t.helperServices.aiAssistantServices.url}/skills/doc_ai_assistant/api/pre-chat`:null}async function ml(t,e,r){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",token:r},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status} calling ${e}`);return n.json()}var EA=t=>new Promise(e=>setTimeout(e,t));async function kA(t,e){let r=t.agentExecutionContext.userRequest,n=e?.configurable?.context?.lastTurnAgent,o=t.agentExecutionContext.messages??[];if(!n||o.length<=1||n==="explorer")return r;try{let s=await Ae(Dp,"transformQuery"),i=await ot({promptText:s,modelTier:"advanced",temperature:0,schema:vA,messages:o.slice(-11),inputVariables:{query:r,lastTurnAgent:n}});if(i.needsContext&&i.rewrittenQuery.trim())return console.debug(`Rephrased query from "${r}" to "${i.rewrittenQuery.trim()}"`),i.rewrittenQuery.trim()}catch{}return r}var OA=k.Root({...oi(),solutionResponse:k({reducer:(t,e)=>e??null,default:()=>null}),documentSkillUrl:k({reducer:(t,e)=>e??null,default:()=>null}),conversationId:k({reducer:(t,e)=>e??t,default:()=>null})}),PA=()=>new he(OA).addNode("initializeAgent",RA).addNode("askSolutionsQuestions",MA).addEdge(fe,"initializeAgent").addEdge("initializeAgent","askSolutionsQuestions").addEdge("askSolutionsQuestions",K),zp=async(t,e,r,n)=>{if(!t)return;let o=jp(t);if(!o)return;let s={context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:Fp(r),use_llm:!1}}}}};n&&(s.conversationId=n),ml(s,o,e??"")},MA=async(t,e)=>{if(Rp(e))return{};let r=hi(e),n=t.documentSkillUrl,o=[],s=await kA(t,e);await Pe({text:r.agentProgress.explorerAgentSearching},e);let i=await ml({message:s,conversationId:e?.configurable?.context?.convoId??void 0,context:{kind:"DocAIAssistantRequest",filters:{products:"ArcGIS Solutions",persona:{persona:"apps-solutions"},pipeline:{translation:{allow:!0,language:Fp(e?.configurable?.context?.configContext.locale),use_llm:!1}}}}},n,e?.configurable?.context?.token??"");i.conversationId&&e?.configurable?.context?.setConversationId&&e.configurable.context.setConversationId(i.conversationId);let a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},c="",l=async u=>{let m=u.context?.results?.[0]?.reply??"";if(m!==""){let h=IA(m),w=TA(h),b=SA(w,e);c=b.source,o=[...o,...b.allMatches.filter(v=>!o.some(g=>g.solution.id===v.solution.id))]}let f=u.context?.results?.[0]?.status?.currentStatusStep;if(f){let h="";f===1?h=r.agentProgress.explorerAgentReading:f===2?h=r.agentProgress.explorerAgentReviewing:f===3&&(h=r.agentProgress.explorerAgentPreparing),await Pe({text:h},e)}};for(await l(i);a.hasMore;){if(Rp(e))return{};await EA(500),i=await ml({conversationId:a.conversationId,ackSequenceNumber:a.ackSequenceNumber,inquiryId:a.inquiryId},n,e?.configurable?.context?.token??""),a={message:i.message,conversationId:i.conversationId,hasMore:i.hasMore,ackSequenceNumber:i.sequenceNumber,inquiryId:i.inquiryId},await l(i)}return jp(e?.configurable?.context.portal)&&zp(e?.configurable?.context.portal,e?.configurable?.context.token??"",e?.configurable?.context.configContext.locale??"en",a.conversationId),o.length&&(o.length===1?Lp(o[0].solution.id):Np(o)),{outputMessage:c,summary:c,status:"success",solutionResponse:a,conversationId:a.conversationId}},RA=async(t,e)=>{let r=null;return t.documentSkillUrl===null&&e?.configurable?.context?.portal&&(r=CA(e.configurable.context.portal)),{documentSkillUrl:r}};await Ae(Dp,"solutions_explorer_description");var Up=t=>{if(t&&Array.isArray(t.id)&&t.id.length>0)return t.id[t.id.length-1].replace("Message","").toLowerCase();if(t&&typeof t._getType=="function")try{return t._getType()}catch{return"human"}return"human"},$A=t=>{let e=Up(t);if(t&&t.kwargs)return{role:e,...t.kwargs};if(t&&typeof t=="object"){let r={role:e,content:typeof t.content=="string"?t.content:String(t.content||"")};return t.id&&(r.id=t.id),t.name&&(r.name=t.name),t.additional_kwargs&&(r.additional_kwargs=t.additional_kwargs),t.response_metadata&&(r.response_metadata=t.response_metadata),r}return{role:"human",content:String(t)}},NA=t=>Up(t)==="human",LA=(t,e=3)=>t.filter(r=>NA(r)).slice(-e).map($A),DA=(t,e=" ")=>LA(t).map(r=>r.content).join(e).trim(),FA={understandingRequest:"Understanding your request...",selectTemplatePrompt:"This use case could be supported in a few different ways. Choose the option that best matches what you want to accomplish.",searchingExistingSolutions:"Searching for existing solutions...",existingSolutionMatch:"I found one or more existing solutions that match your use case. These are ready-to-use solutions that may already meet your needs and can be deployed now. Do you want to continue building your own solution?",continueBuildingYes:"Yes, I want to build a new solution",continueBuildingNo:"No, I\u2019ll review existing solutions",continueBuildingDeclined:"Sounds good. We can focus on existing solutions. Let me know if I can help answer any questions or provide more details.",creatingDesign:"Generating solution design...",updatingDesign:"Updating solution design...",applyChangeFailed:"I wasn't able to apply that change. The design was not modified. Please try rephrasing your request.",createDesignFailed:"I wasn't able to create a solution design from that request. Please try rephrasing and try again.",discardMessage:"Are you sure you want to discard your solution?",discardForNewSolution:"I can help you build a new solution, but I will need to discard your current solution design. Do you want to continue?"},jA={builderMessages:FA},fi=class t{constructor(e,r,n=!0){this.isValid=!0,this.issues=[],this.fieldNameRegistry=null,this.response=e,this.template=r,this.newDesign=n,this.validate()}static{this.INVALID_NAME_CHARS=/[><~`$^+=|]/gu}static{this.NAME_MAX_LENGTH=250}static{this.DESCRIPTION_MAX_LENGTH=2048}static{this.FIELD_NAME_MAX_LENGTH=31}static{this.ALLOWED_FIELD_TYPES=new Set(["string","integer","double","date","guid"])}validate(){this.compareModels(),this.validateResponse()}compareModels(){this._compareStrings(),this._compareItems(),this._compareFeatureLayers()}validateResponse(){this._validateSolutionProps(),this._validateItems(),this._validateFeatureLayer()}_compareStrings(){let e=new Set(this.response.solution.strings.map(n=>n.key)),r=new Map(this.template.solution.strings.map(n=>[n.key,n]));[...r.keys()].every(n=>e.has(n))||(this.newDesign?this._reconcileStringKeys():this._logIssue("String keys in llm response do not match the template."));for(let n of this.response.solution.strings){if(n.value)continue;let o=r.get(n.key)?.value;this.newDesign&&o?(n.value=o,this._logAutoFix(`String key '${n.key}' had no value. Auto-fixed by restoring the template value.`)):this._logIssue(`String key '${n.key}' has no value in the design. It must be populated.`)}}_reconcileStringKeys(){let e=new Set(this.response.solution.strings.map(r=>r.key));for(let r of this.template.solution.strings)e.has(r.key)||(this.response.solution.strings.push({...r}),this._logAutoFix(`String key '${r.key}' was missing from the design. Auto-fixed by re-adding it from the template.`))}_compareItems(){let e=new Set(this.template.items.map(n=>n.id)),r=new Set(this.response.items.map(n=>n.id));e.size===r.size&&[...e].every(n=>r.has(n))||(this.newDesign?this._reconcileItems():this._logIssue("Item IDs in design do not match the template."))}_reconcileItems(){let e=new Set(this.template.items.map(i=>i.id)),r=new Set(this.response.items.map(i=>i.id)),n=[...r].filter(i=>!e.has(i)),o=[...e].filter(i=>!r.has(i));if(e.size===r.size&&n.length===1&&o.length===1){let i=n[0],a=o[0],c=this.response.items.find(l=>l.id===i);if(c){c.id=a,this._logAutoFix(`Item id '${i}' did not match the template id '${a}'. Auto-fixed in place.`);return}}n.length&&(this.response.items=this.response.items.filter(i=>e.has(i.id)),this._logAutoFix(`Removed items not present in the template: ${n.join(", ")}.`));let s=this.template.items.filter(i=>!r.has(i.id));if(s.length){this.response.items=[...s.map(i=>({...i})),...this.response.items];for(let i of s)this._logAutoFix(`Item '${i.id}' was missing from the design. Auto-fixed by adding it from the template.`)}}_compareFeatureLayers(){let e=this.template.featureLayer,r=this.response.featureLayer;if(e.itemId!==r.itemId){let n=r.itemId;r.itemId=e.itemId,this._logAutoFix(`Feature Layer itemId '${n}' did not match the template. Auto-fixed to '${e.itemId}'.`)}if(!e.addLayers){let n=new Set(e.layers.map(s=>s.id)),o=new Set(r.layers.map(s=>s.id));if(!(n.size===o.size&&[...n].every(s=>o.has(s))))this._logIssue(`Feature Layer '${e.itemId}' had its layer ids altered.`);else for(let s of e.layers){if(s.type){let a=r.layers.find(c=>c.id===s.id);if(a&&a.type!==s.type)if(this.newDesign){let c=a.type;a.type=s.type,this._logAutoFix(`Layer '${s.id}' type '${c}' is immutable. Auto-fixed back to template type '${s.type}'.`)}else this._logIssue(`Layer '${s.id}' type '${a.type}' does not match template type '${s.type}'. This layer type is immutable.`)}let i=r.layers.find(a=>a.id===s.id);i&&this._validateRequiredFields(i,s)}}}_validateRequiredFields(e,r){let n=new Map(e.requiredFields.map(o=>[o.name.toLowerCase(),o]));for(let o of r.requiredFields){let s=n.get(o.name.toLowerCase());if(!s){this.newDesign?(e.requiredFields.push({...o}),this._logAutoFix(`Layer '${e.name}' was missing required field '${o.name}'. Auto-fixed by re-adding it from the template.`)):this._logIssue(`Layer '${e.name}' is missing required field '${o.name}'.`);continue}this._enforceRequiredFieldImmutability(e,s,o)}}_enforceRequiredFieldImmutability(e,r,n){let o=[];if(r.type!==n.type&&o.push("type"),(r.length??null)!==(n.length??null)&&o.push("length"),this._choiceListsEqual(r.choiceList,n.choiceList)||o.push("choiceList"),!o.length)return;let s=o.length===1?"property":"properties";this.newDesign?(r.type=n.type,r.length=n.length,r.choiceList=Array.isArray(n.choiceList)?[...n.choiceList]:n.choiceList??null,this._logAutoFix(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). Auto-fixed by reverting to the template.`)):this._logIssue(`Layer '${e.name}' required field '${n.name}' changed immutable ${s} (${o.join(", ")}). These cannot be modified.`)}_choiceListsEqual(e,r){let n=Array.isArray(e)?e:null,o=Array.isArray(r)?r:null;if(n===null&&o===null)return!0;if(n===null||o===null)return!1;let s=new Set(n),i=new Set(o);return s.size===i.size&&[...s].every(a=>i.has(a))}_validateSolutionProps(){let e=this.response.solution.title??"",r=this.response.solution.description,n=/[/\\]/u.test(e),o=this.newDesign?e.replace(/[/\\]/gu,""):e;this.newDesign&&o!==e?(this.response.solution.title=o,this._logAutoFix("Solution title contained forward or back slashes. Auto-fixed by removing them.")):!this.newDesign&&n&&this._logIssue("Solution title contains forbidden forward or back slashes.");let s=ts(o);if(s.isValid||this._tryFixName(s.errorType,o,i=>{this.response.solution.title=i},"Solution title","Solution Title")||this._logIssue(`Solution title is invalid (${s.errorType}).`),r){let i=rs(r,t.DESCRIPTION_MAX_LENGTH,!0);i.isValid||this._tryFixDescription(r,a=>{this.response.solution.description=a},"Solution description")||this._logIssue(`Solution description is invalid (${i.errorType}).`)}}_validateItems(){for(let e of this.response.items){let r=ts(e.title??"");if(r.isValid||this._tryFixName(r.errorType,e.title??"",n=>{e.title=n},`Item '${e.id}' title`,"Item Title")||this._logIssue(`Item '${e.id}' title is invalid (${r.errorType}).`),e.description){let n=rs(e.description,t.DESCRIPTION_MAX_LENGTH,!0);n.isValid||this._tryFixDescription(e.description,o=>{e.description=o},`Item '${e.id}' description`)||this._logIssue(`Item '${e.id}' description is invalid (${n.errorType}).`)}}}_validateFeatureLayer(){this.response.featureLayer.layers.length||this._logIssue("Feature layer item must contain at least one layer.");let e=this.response.featureLayer.layers.map(r=>r.name.toLowerCase());e.length!==new Set(e).size&&(this.newDesign?this._dedupeLayerNames(this.response.featureLayer.layers):this._logIssue(`Layer names must be unique (case-insensitive). Layer names in design: ${e}.`));for(let r of this.response.featureLayer.layers)this._validateLayer(r,this.response.featureLayer.addLayers)}_dedupeLayerNames(e){let r=new Set;for(let n of e){let o=(n.name??"").toLowerCase();if(r.has(o)){let s=n.name;n.name=this._makeUniqueName(n.name??"Layer",r),this._logAutoFix(`Duplicate layer name '${s}'. Auto-fixed to '${n.name}'.`)}r.add(n.name.toLowerCase())}}_validateLayer(e,r){!r&&e.typeMutable===!0&&e.type==="Table"&&(this.newDesign?(e.type="Point",this._logAutoFix(`Layer '${e.name}' cannot be a Table. Auto-fixed to 'Point'.`)):this._logIssue(`Layer '${e.name}' cannot be a Table. It may be a Point, Line, or Polygon.`));let n=ts(e.name??"");if(n.isValid||this._tryFixName(n.errorType,e.name??"",o=>{e.name=o},`Layer '${e.name}' name`,"Layer Title")||this._logIssue(`Layer '${e.name}' name is invalid (${n.errorType}).`),e.description){let o=rs(e.description,t.DESCRIPTION_MAX_LENGTH,!0);o.isValid||this._tryFixDescription(e.description,s=>{e.description=s},`Layer '${e.name}' description`)||this._logIssue(`Layer '${e.name}' description is invalid (${o.errorType}).`)}this._validateLayerFields(e)}_validateLayerFields(e){let r=e.systemFields??[];this.fieldNameRegistry=new Set([...e.customFields,...e.requiredFields,...r].map(s=>s.name.toLowerCase()));for(let s of[...e.customFields,...e.requiredFields])this._validateField(s);this.fieldNameRegistry=null;let n=new Set(e.requiredFields.map(s=>s.name.toLowerCase())),o=new Set(n);for(let s of e.customFields){let i=s.name.toLowerCase();if(o.has(i)){let a=n.has(i)?"a required field name":"another field with the same name";if(this.newDesign){let c=s.name;s.name=this._makeUniqueName(s.name,o),this._logAutoFix(`Layer '${e.name}' field '${c}' collided with ${a}. Auto-fixed to '${s.name}'.`)}else this._logIssue(`Layer '${e.name}' field '${s.name}' collides with ${a}.`)}o.add(s.name.toLowerCase())}}_validateField(e){let r=/^\p{L}/u,n=/^.[\p{L}\p{M}\p{N}_]*$/u;e.alias?.trim()||(this.newDesign?(e.alias=e.name,this._logAutoFix(`Field '${e.name}' had no display name (alias). Auto-fixed to '${e.alias}'.`)):this._logIssue(`Field '${e.name}' has no display name (alias).`));let o=r.test(e.name),s=n.test(e.name);if(!o||!s)if(this.newDesign){let c=e.name;e.name=this._makeUniqueName(this._sanitizeFieldName(e.name),this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' had an invalid name. Auto-fixed to '${e.name}'.`)}else o||this._logIssue(`Field '${e.name}' does not start with a letter.`),s||this._logIssue(`Field '${e.name}' contains invalid characters (only letters from any writing system, numbers, and underscores are allowed; emojis and punctuation are not allowed).`);if(e.name.length>t.FIELD_NAME_MAX_LENGTH)if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(e.name,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' exceeds ${t.FIELD_NAME_MAX_LENGTH} characters.`);if(oc.has(e.name.toLowerCase()))if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(c,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' is a SQL reserved keyword. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a SQL reserved keyword.`);if(sc.has(e.name.toLowerCase()))if(this.newDesign){let c=e.name;e.name=this._getUniqueTruncatedFieldName(c,this.fieldNameRegistry),this.fieldNameRegistry.add(e.name.toLowerCase()),this._logAutoFix(`Field '${c}' is a reserved system field name. Auto-fixing to '${e.name}'.`)}else this._logIssue(`Field '${e.name}' is a reserved system field name.`);let i=e.type??"",a=i.toLowerCase();if(i!==a&&(e.type=a),!t.ALLOWED_FIELD_TYPES.has(a))if(this.newDesign){let c=e.type;a==="globalid"?e.type="guid":a==="oid"?e.type="integer":e.type="string",this._logAutoFix(`Field '${e.name}' had unsupported type '${c}'. Auto-fixed to '${e.type}'.`)}else this._logIssue(`Field '${e.name}' has unsupported type '${e.type}'. Allowed types are: string, integer, double, date.`);if(Array.isArray(e.choiceList)&&e.type!=="string"&&(this.newDesign?e.choiceList.length?(e.type="string",this._logAutoFix(`Field '${e.name}' had a domain but was not of type 'string'. Auto-fixed by setting the type to 'string'.`)):(e.choiceList=null,this._logAutoFix(`Field '${e.name}' had an empty domain but is not of type 'string'. Auto-fixed by removing the domain.`)):this._logIssue(`Field '${e.name}' must be of type 'string' to have a domain.`)),e.type==="string"&&this._validateStringFieldLength(e),Array.isArray(e.choiceList)&&(this.newDesign?this._autoFixChoiceList(e):this._logChoiceListIssues(e)),Array.isArray(e.choiceList)&&e.length!=null){let c=Math.max(...e.choiceList.map(l=>l.length));c>e.length&&(this.newDesign?(this._logAutoFix(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${c} characters. Auto-fixing to ${c}.`),e.length=c):this._logIssue(`The choice provided for field '${e.name}' is too long. It must fit within ${e.length} characters, but the choice requires ${c} characters.`))}}_autoFixChoiceList(e){let r=e.choiceList,n=r.filter(s=>s?.trim());n.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had blank domain values. Auto-fixed by removing them.`),r=n,e.choiceList=r);let o=[...new Set(r)];o.length!==r.length&&(this._logAutoFix(`Field '${e.name}' had duplicate domain values. Auto-fixed by removing duplicates.`),r=o,e.choiceList=r),r.length||(this._logAutoFix(`Field '${e.name}' had an empty domain. Auto-fixed by removing the domain.`),e.choiceList=null)}_logChoiceListIssues(e){if(Array.isArray(e.choiceList)){if(!e.choiceList.length){this._logIssue(`Field '${e.name}' has an empty domain. At least one value is required.`);return}e.choiceList.some(r=>!r?.trim())&&this._logIssue(`A blank domain value was added to Field '${e.name}'.`),e.choiceList.length!==new Set(e.choiceList).size&&this._logIssue(`Field '${e.name}' has duplicate domain values.`)}}_validateStringFieldLength(e){if(this.newDesign&&e.length===255&&(e.length=256),typeof e.length!="number"||Number.isNaN(e.length)){this._handleInvalidStringFieldLength(e,256);return}let r=e.length;if(!ac(r).isValid){let n=r>4e3?4e3:256;this._handleInvalidStringFieldLength(e,n)}}_handleInvalidStringFieldLength(e,r){this.newDesign?(this._logAutoFix(`Field '${e.name}' has an invalid length. Auto-fixing to ${r}.`),e.length=r):this._logIssue(`Field '${e.name}' length is invalid (must be a number between 1 and 4000).`)}_makeUniqueName(e,r){let n=e,o=1;for(;r.has(n.toLowerCase());)n=`${e}_${o}`,o+=1;return n}_getUniqueTruncatedFieldName(e,r){let n=t.FIELD_NAME_MAX_LENGTH,o=e.slice(0,n),s=o,i=1;for(;r.has(s.toLowerCase());){let a=`_${i}`,c=Math.max(1,n-a.length);s=`${o.slice(0,c)}${a}`,i+=1}return s}_sanitizeItemName(e,r=t.NAME_MAX_LENGTH){let n=(e??"").replace(new RegExp(ic.source,"gu"),"").replace(t.INVALID_NAME_CHARS,"").replace(/\s+/gu," ").trim();return n.length>r&&(n=n.slice(0,r).trim()),n}_sanitizeDescription(e,r=t.DESCRIPTION_MAX_LENGTH){let n=(e??"").replace(/[<>]/gu,"");return n.length>r&&(n=n.slice(0,r)),n}_sanitizeFieldName(e){let r=(e??"").replace(/[^\p{L}\p{M}\p{N}_]/gu,"");return r.length===0?r="field":/^\p{L}/u.test(r)||(r=`f_${r}`),r}_tryFixName(e,r,n,o,s){if(!this.newDesign)return!1;if(e==="empty")return n(s),this._logAutoFix(`${o} was empty. Auto-fixed to '${s}'.`),!0;let i=this._sanitizeItemName(r)||s;return n(i),this._logAutoFix(`${o} was invalid (${e}). Auto-fixed to '${i}'.`),!0}_tryFixDescription(e,r,n){if(!this.newDesign)return!1;let o=this._sanitizeDescription(e);return r(o),this._logAutoFix(`${n} was invalid. Auto-fixed to a sanitized value.`),!0}_logAutoFix(e){console.debug(e)}_logIssue(e){console.debug(e),this.issues.push(e),this.isValid=!1}},zA=d.object({key:d.string().describe("Stable key identifier for the string."),value:d.string().describe("Display value for the string."),description:d.string().describe("Explanation of where/how the string is used.")}),UA=d.object({id:d.string().describe("ArcGIS item id (32 hex characters)."),title:d.string().describe("Item title."),description:d.string().describe("Item description."),type:d.enum(["Feature Layer (hosted)","Feature Layer (hosted, view)","Web Map","Instant App","Dashboard","Web Experience","Form","Table (hosted)","Table (hosted, view)","Hub Site Application","Hub Page","CSV","Data Pipeline","Desktop Application Template","Group","Notebook","QuickCapture Project"]).describe("ArcGIS item type.")}),$p=d.object({name:d.string().describe("Field name."),type:d.enum(["string","integer","double","date","oid","guid","globalid"]).describe("Field data type."),alias:d.string().describe("Field alias for display."),description:d.string().describe("Field description."),choiceList:d.array(d.string()).nullable().describe("List of allowed values for string fields with a controlled vocabulary. Null if unrestricted or not applicable."),length:d.number().int().nullable().describe("Maximum string length for string fields. Null for non-string fields.")}),qA=d.object({id:d.number().int().describe("Layer/table id within the feature service."),type:d.enum(["Point","Polyline","Polygon","Table"]).describe("Layer type."),typeMutable:d.boolean().describe("Indicates whether the layer type can be changed."),name:d.string().describe("Layer/table name."),description:d.string().describe("Layer/table description."),customFields:d.array($p).describe("User/business fields specific to the solution."),requiredFields:d.array($p).describe("Fields required for solution functionality (e.g., relationship keys).")}),BA=d.object({itemId:d.string().describe("ArcGIS item id for the feature layer."),addLayers:d.boolean().describe("Indicates whether new layers can be added during solution design."),layers:d.array(qA)}),hl=d.object({response:d.string().describe("Conversational response to the user's query."),solution:d.object({itemId:d.string().nullable().describe("ArcGIS item id of the source Solution template used for deployment. Preserve the existing value exactly when known; otherwise use null."),title:d.string().describe("Title of the solution."),description:d.string().describe("Description of the solution."),tags:d.array(d.string()).describe("Keywords/tags associated with the solution."),strings:d.array(zA).describe("Localized strings/labels used by apps (dashboards, forms, etc.).")}),items:d.array(UA).describe("ArcGIS items that belong to the solution (apps, maps, layers, etc.)."),featureLayer:BA.describe("Primary feature layer item and its schema/layers/tables details.")}),KA=d.object({op:d.enum(["add","remove","replace","move","copy"]).describe("RFC 6902 operation type."),path:d.string().describe("RFC 6901 JSON Pointer to the target location."),value:d.string().nullable().describe(`JSON-encoded value to apply (required for add and replace). Must be null \u2014 not an empty string \u2014 for remove, move, and copy operations. Serialize as a JSON string, e.g. '\\"text\\"' for a string, '[\\"a\\",\\"b\\"]' for an array, or '{\\"name\\":\\"x\\"}' for an object.`),from:d.string().nullable().describe("RFC 6901 JSON Pointer to the source location (required for move and copy). Must be null \u2014 not an empty string \u2014 for all other operations.")}),WA=d.object({response:d.string().describe("Conversational response describing the accepted design changes."),patches:d.array(KA).describe("Minimal RFC 6902 patch operations needed to update the current design.")}),HA=d.object({response:d.string().describe("Short, user-friendly explanation of why the requested update was not applied.")}),VA=d.object({assistantResponse:d.string().describe("Natural-language response for the user."),isValidUpdate:d.boolean().describe("True only when the request is in scope for supported design updates.")}),GA=d.object({matchedTitles:d.array(d.string()).describe("Titles of solutions that match the user's request. Empty array if no strong match.")}),JA=d.object({templateId:d.string().min(1).describe("Template id from the available template list."),confidence:d.number().min(0).max(1).describe("Confidence score from 0 to 1 for this template match."),templateDescription:d.string().min(1).describe("Short action\u2011oriented description of the template in the user's use case/workflow, starting with a verb.")}),ZA=d.object({assistantResponse:d.string().nullable().describe("Natural-language response for the user."),isValidUseCase:d.boolean().describe("True only when the request is concrete, appropriate, and has at least one matching template."),matchedTemplates:d.array(JA).describe("Ordered list of matching templates, best match first. Empty when no valid match exists.")}),QA=t=>t.length?t.map((e,r)=>`${r+1}. ${e}`).join(`
|
|
342
|
-
`):"No validation errors were provided.",YA=async t=>{let{query:e,validationIssues:r,recentMessages:n,fallbackMessage:o,promptModules:s}=t;try{return(await ot({promptText:await Ae(s,"explainValidationFailure"),modelTier:"fast",temperature:0,schema:HA,messages:n,inputVariables:{query:e,validationIssueCount:String(r.length),validationIssues:QA(r)}})).response?.trim()||o}catch(i){return console.warn("Natural language response failed:",{error:i}),o}},gl=t=>t in wr,XA=5,ex=.8,tx=.5,rx="Web Mapping Application",nx="Embeddings",di=null,pl=null,pi=null,mi=null,ox="Build",hr=Object.assign({"./prompts/assessBuildRequest.md":()=>import("./S26SZJC7.js").then(t=>t.default),"./prompts/assessUpdateRequest.md":()=>import("./7X2SPNNK.js").then(t=>t.default),"./prompts/description.md":()=>import("./E25ZWVBK.js").then(t=>t.default),"./prompts/designSolution.md":()=>import("./SNA7NRRQ.js").then(t=>t.default),"./prompts/explainValidationFailure.md":()=>import("./I5E3PM26.js").then(t=>t.default),"./prompts/findExistingSolution.md":()=>import("./LPFG5XTA.js").then(t=>t.default),"./prompts/updateDesign.md":()=>import("./MBT2S4J5.js").then(t=>t.default)}),sx=jA.builderMessages,G=t=>t?.signal?.aborted??!1,re=(t,e,r)=>hi(e)?.builderMessages?.[t]??sx[t],qp=t=>{typeof window<"u"&&window.dispatchEvent(new CustomEvent("arcgis-solution-design-update",{detail:t}))},ix=async(t,e,r)=>{if(!t)return null;let n=`type:"${rx}" AND typekeywords:${nx} AND group:${t}`;return(await xi({q:n,params:e?{token:e}:void 0,portal:r,num:1}))?.results?.[0]??null};async function ax(t,e,r,n){try{let o=await ix(t,e,r);if(!o||G(n))return null;let s=new AA({id:o.id});return await s.load(),G(n)?null:await s.fetchData("json")}catch{return null}}var lx=async(t,e,r)=>{if(!t)return[];let n=`type:Solution AND typekeywords:${ox} AND group:${t}`;return(await xi({q:n,params:e?{token:e}:void 0,portal:r,num:100}))?.results??[]},cx=async(t,e,r)=>{try{let n=await Ll(t,{params:e?{token:e}:void 0,portal:r}),o=n?.buildSolution;if(!o)return null;let s=n?.params,i=s&&typeof s=="object"&&!Array.isArray(s)?s:null;return{buildSolution:o,params:i}}catch{return null}},gr=(t,e={})=>{let r=t;return"itemId"in e&&(r={...r,solution:{...r.solution,itemId:e.itemId??null}}),e.sourceBuildSolution!=null&&(r={...r,sourceBuildSolution:e.sourceBuildSolution}),"params"in e&&(r={...r,params:e.params??null}),"templateId"in e&&(r={...r,templateId:e.templateId??null}),r},Bp=(t,e)=>{if(t==null||e==null)return{ok:!1,error:"design or sourceBuildSolution is null/undefined"};try{let r=structuredClone(e);return new Mi({buildSolution:r}).applyLlmTemplate(t),{ok:!0}}catch(r){return{ok:!1,error:r instanceof Error?r.stack??r.message:String(r)}}},yl=async t=>{if(pl){Object.entries(pl).forEach(([i,a])=>{wr[i]&&(wr[i].initialTemplate=a)});return}let e=t?.configurable?.context?.token,r=Wp(t),n=Hp(t);if(!r){console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping live template hydration.");return}let o=await lx(r,e,n),s={};G(t)||(await Promise.all(o.map(async i=>{let a=i.properties?.templateInfo;if(!a||typeof a!="object")return;let c=a.id;if(typeof c!="string"||s[c])return;let l=await cx(i.id,e,n);if(!l||G(t))return;let{buildSolution:u,params:m}=l;if(typeof u=="object"&&u!==null&&"solution"in u){let h=u.solution;h.thumbnailUrl=i.thumbnail?`${n??"https://www.arcgis.com/sharing/rest"}/content/items/${i.id}/info/${i.thumbnail}`:void 0,h.item=i}let f={...a,buildSolution:u};s[c]=gr(new Mi(f).dumpToLlmTemplate(),{itemId:i.id,sourceBuildSolution:structuredClone(u),params:m?structuredClone(m):null}),wr[c]={...a,initialTemplate:s[c]}})),pl=s)},Kp=t=>{let e=t?.configurable?.context?.token;return typeof e!="string"||!e.trim()?null:e},Wp=t=>{let e=t?.configurable?.context?.configContext?.primarySolutionsGroupId;return typeof e!="string"||!e.trim()?null:e},Hp=t=>{let e=t?.configurable?.context?.configContext?.portalURL;if(!(typeof e!="string"||!e.trim()))return`${e.replace(/\/+$/,"")}/sharing/rest`},ux=async t=>{await Promise.all([Gp(t),yl(t)])},Vp=async t=>{let e=Kp(t);(!pi||e&&e!==mi)&&(mi=e??mi,pi=ux(t).catch(r=>{throw pi=null,mi=null,r})),await pi};async function Gp(t){if(di)return di;let e=Wp(t);if(!e)return console.warn("Solution Builder: missing primarySolutionsGroupId in appConfig; skipping embeddings load."),null;let r=Hp(t),n=t?.configurable?.context?.configContext?.portalURL;if(await new bA(n?{url:n}:void 0).load(),G(t))return null;let o=Kp(t)??void 0,s=await ax(e,o,r,t);return G(t)?null:s?(di=s.items,di):null}var dx=()=>Object.entries(wr).map(([t,e])=>`ID: ${t}
|
|
343
|
-
Label: ${e.label}
|
|
344
|
-
Description: ${e.description}`).join(`
|
|
345
|
-
|
|
346
|
-
`),px=t=>{let e=t?.configurable?.context?.solutionDesignJson;if(typeof e!="string"||!e.trim())return null;try{let r=JSON.parse(e),n=gr({response:"",...r},{itemId:r?.solution?.itemId??null}),o=hl.safeParse(n);if(!o.success)return null;let{response:s,...i}=o.data,a=r.templateId,c=typeof a=="string"&&gl(a)?a:null;return gr(i,{sourceBuildSolution:r.sourceBuildSolution,templateId:c,params:r.params??null})}catch{return null}},mx=k.Root({...oi(),templateDescription:k({reducer:(t,e)=>typeof e=="string"||e===null?e:t??null,default:()=>null}),currentDesign:k({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),assessment:k({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),selectedTemplate:k({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),updateAssessment:k({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null}),existingMatches:k({reducer:(t=[],e)=>e===void 0?t:e??[],default:()=>[]}),continueBuilding:k({reducer:(t=null,e)=>e===void 0?t:e??null,default:()=>null})}),fx=(t,e)=>{if(G(e))return{};let r=px(e),n=r?.templateId??null,o={};return JSON.stringify(t.currentDesign)!==JSON.stringify(r)&&(o.currentDesign=r),n&&t.selectedTemplate!==n&&(o.selectedTemplate=n),o},hx=async(t,e)=>{if(G(e))return{};await Pe({text:re("understandingRequest",e)},e),await Vp(e);let r=t.agentExecutionContext.userRequest,n=dx(),o=t.agentExecutionContext.messages.slice(-11),s=await ot({promptText:await Ae(hr,"assessBuildRequest"),modelTier:"advanced",temperature:0,schema:ZA,messages:o,inputVariables:{query:r,availableTemplates:n}}),i=s.matchedTemplates.filter(m=>gl(m.templateId)),a={...s,matchedTemplates:i},[c,l]=i,u=c&&c.confidence>=ex&&(l===void 0||c.confidence-l.confidence>=tx)?c.templateId:null;return{assessment:a,selectedTemplate:u,existingMatches:[],continueBuilding:null}},gx=t=>{let e=t.assessment?.assistantResponse??"";return{outputMessage:e,summary:e,status:"success"}},yx=async(t,e)=>{if(G(e))return{};let{currentDesign:r}=t;if(!r)return{updateAssessment:{assistantResponse:"",isValidUpdate:!0}};await Pe({text:re("understandingRequest",e)},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);return{updateAssessment:await ot({promptText:await Ae(hr,"assessUpdateRequest"),modelTier:"advanced",temperature:0,schema:VA,messages:o,inputVariables:{currentDesign:JSON.stringify($i(r)),query:n}})}},_x=(t,e)=>{let r=t.updateAssessment?.assistantResponse??re("applyChangeFailed",e);return{outputMessage:r,summary:r,status:"success"}},wx=(t,e)=>{if(G(e))return{};let{hitlResponse:r}=e.configurable,n="selectTemplate",o=t.assessment?.matchedTemplates.filter(c=>gl(c.templateId))??[],s=o.map(c=>`${c.templateDescription}`);if(r?.agentId!=="solutionBuilder"||r.id!==n){let c={agentId:"solutionBuilder",id:n,kind:"singleSelection",message:re("selectTemplatePrompt",e),metadata:[...s]};throw new zo(c)}let i=String(r.payload??""),a=s.findIndex(c=>c===i);return{selectedTemplate:(a>=0?o[a]:void 0)?.templateId??o[0]?.templateId??null}},bx=async(t,e)=>{if(G(e))return{};await Pe({text:re("searchingExistingSolutions",e)},e);let r=t.agentExecutionContext.userRequest,n=DA(t.agentExecutionContext.messages)||r,o=await Gp(e);if(G(e))return{};if(!o)return console.warn("Solutions Search: failed to load solution embeddings cache; skipping search."),{existingMatches:[]};if(!o.length)return{existingMatches:[]};let[s]=await kp([n]);if(G(e))return{};let i=o.map(u=>({solution:u,score:Op(s,u.embedding)}));i.sort((u,m)=>m.score-u.score);let a=i.slice(0,XA);if(!a.length)return{existingMatches:[]};let c=a.map(({solution:u})=>`${u.title}
|
|
347
|
-
Snippet: ${u.snippet}
|
|
348
|
-
Description: ${u.description}`).join(`
|
|
349
|
-
|
|
350
|
-
`),l=t.agentExecutionContext.messages.slice(-11);return{existingMatches:(await ot({promptText:await Ae(hr,"findExistingSolution"),modelTier:"fast",temperature:0,schema:GA,messages:l,inputVariables:{query:r,candidates:c}})).matchedTitles.map(u=>a.find(({solution:m})=>m.title===u)).filter(u=>u!==void 0)}},Ax=(t,e)=>{if(G(e))return{};let{existingMatches:r}=t,{hitlResponse:n}=e.configurable,o=`confirmExistingSolution:${r[0].solution.id}`;if(n?.agentId!=="solutionBuilder"||n.id!==o){r.length===1?Lp(r[0].solution.id):Np(r);let a=re("existingSolutionMatch",e),c=[re("continueBuildingYes",e),re("continueBuildingNo",e)],l={agentId:"solutionBuilder",id:o,kind:"singleSelection",message:a,metadata:c};throw new zo(l)}let s=String(n.payload??"").trim(),i=re("continueBuildingNo",e);return{continueBuilding:s!==i}},xx=(t,e)=>{let r=re("continueBuildingDeclined",e);return{outputMessage:r,summary:r,status:"success"}},Jp=async(t,e)=>{if(G(e))return{};if(await Vp(e),G(e))return{};let{currentDesign:r}=t,n=t.agentExecutionContext.userRequest;await Pe({text:re("creatingDesign",e)},e);let o=eo(t.selectedTemplate);if(o?.initialTemplate||(await yl(e),o=eo(t.selectedTemplate)),G(e))return{};if(!o?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let s=gr(r??o.initialTemplate,{itemId:(r??o.initialTemplate)?.solution?.itemId??null,sourceBuildSolution:r?.sourceBuildSolution??o.initialTemplate.sourceBuildSolution,params:r?.params??o.initialTemplate.params??null}),i=t.agentExecutionContext.messages.slice(-11),a=await ot({promptText:await Ae(hr,"designSolution"),modelTier:"advanced",temperature:0,schema:hl,messages:i,inputVariables:{currentDesign:JSON.stringify(Ri(s)),templateInstructions:o.instructions,query:n}});if(await Pe({text:" of design solution 1"},e),G(e))return{};let{response:c,featureLayer:l,...u}=a,m=Ni(l,s.featureLayer),f=gr({...u,featureLayer:m},{itemId:s?.solution?.itemId,sourceBuildSolution:s.sourceBuildSolution,templateId:t.selectedTemplate??null,params:s.params??null}),h=new fi(f,o.initialTemplate);if(!h.isValid)return console.warn("[SolutionBuilder] designSolution validation failed:",{issues:h.issues,llmResponse:a}),{outputMessage:re("createDesignFailed",e)};let w=f.sourceBuildSolution,b=Bp(f,w);if(!b.ok){console.warn("[SolutionBuilder] designSolution Esri JSON conversion failed:",{error:b.error,llmResponse:a,design:f});let v=re("createDesignFailed",e);return{outputMessage:v,summary:v,status:"success"}}return G(e)?{}:(qp(f),{outputMessage:c,summary:c,status:"success",currentDesign:f})},vx=async(t,e)=>{if(G(e))return{};let{currentDesign:r}=t;if(!r)return Jp(t,e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11);await Pe({text:re("updatingDesign",e)},e);let s;try{s=await ot({promptText:await Ae(hr,"updateDesign"),modelTier:"advanced",temperature:0,schema:WA,messages:o,inputVariables:{currentDesign:JSON.stringify($i(r)),query:n}})}catch(P){console.warn("[SolutionBuilder] updateDesign structured prompt failed:",P);let U=re("applyChangeFailed",e);return{outputMessage:U,summary:U,status:"success"}}let{response:i,patches:a}=s;if(!a||a.length===0)return{outputMessage:i,summary:i,status:"success"};let c=P=>{try{return JSON.parse(P)}catch{let U=P.replace(/[\u0000-\u001F]/g,q=>{switch(q){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
351
|
-
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return"\\u"+q.charCodeAt(0).toString(16).padStart(4,"0")}});try{return JSON.parse(U)}catch{return P}}},l=[...a.map(P=>({op:P.op,path:P.path.replace(/\/+$/,""),...P.value!=null&&P.value!==""?{value:c(P.value)}:{},...P.from!=null&&P.from!==""?{from:P.from}:{}}))].sort((P,U)=>P.op!=="remove"||U.op!=="remove"?0:U.path.localeCompare(P.path,void 0,{numeric:!0})),u=structuredClone(Ri(r));try{Jn(u,l,!0)}catch(P){console.warn("[SolutionBuilder] updateDesign JSON patch failed:",{error:P,llmResponse:s,patches:l,patchTarget:u});let U=re("applyChangeFailed",e);return{outputMessage:U,summary:U,status:"success"}}let m=gr({response:"",...u},{itemId:r.solution?.itemId??null}),f=hl.safeParse(m);if(!f.success){console.warn("[SolutionBuilder] updateDesign schema validation failed:",{errors:f.error.issues,llmResponse:s,patchedDesign:m});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}let{response:h,featureLayer:w,...b}=f.data,v=Ni(w,r.featureLayer),g=gr({...b,featureLayer:v},{itemId:r.solution?.itemId,sourceBuildSolution:r.sourceBuildSolution,templateId:r.templateId??t.selectedTemplate??null,params:r.params??null}),x=eo(t.selectedTemplate);if(x?.initialTemplate||(await yl(e),x=eo(t.selectedTemplate)),G(e))return{};if(!x?.initialTemplate)throw new Error("No hydrated templates are available for solution design.");let S=new fi(g,x.initialTemplate,!1);if(!S.isValid){console.warn("[SolutionBuilder] updateDesign validation failed:",{issues:S.issues,llmResponse:s,patchedDesign:g});let P=await YA({query:n,validationIssues:S.issues,recentMessages:o,fallbackMessage:re("applyChangeFailed",e),promptModules:hr});return{outputMessage:P,summary:P,status:"success"}}let $=g.sourceBuildSolution,z=Bp(g,$);if(!z.ok){console.warn("[SolutionBuilder] updateDesign Esri JSON conversion failed:",{error:z.error,llmResponse:s,design:g});let P=re("applyChangeFailed",e);return{outputMessage:P,summary:P,status:"success"}}return G(e)?{}:(qp(g),{outputMessage:i,summary:i,status:"success",currentDesign:g})},Ix=t=>t.currentDesign!==null?"assessUpdateRequest":"assessBuildRequest",Tx=t=>!t.updateAssessment||!t.updateAssessment.isValidUpdate?"invalidUpdateExit":"updateDesign",Sx=t=>!t.assessment||!t.assessment.isValidUseCase?"invalidBuildExit":!t.selectedTemplate&&t.assessment.matchedTemplates.length>1?"selectTemplateHIL":"findExistingSolutions",Cx=t=>t.existingMatches.length>0?"confirmContinueBuildingHIL":"designSolution",Ex=t=>t.continueBuilding===!1?"declineContinueBuildingExit":"designSolution",kx=()=>new he(mx).addNode("syncCurrentDesignFromContext",fx).addNode("assessBuildRequest",hx).addNode("assessUpdateRequest",yx).addNode("invalidBuildExit",gx).addNode("invalidUpdateExit",_x).addNode("selectTemplateHIL",wx).addNode("findExistingSolutions",bx).addNode("confirmContinueBuildingHIL",Ax).addNode("declineContinueBuildingExit",xx).addNode("designSolution",Jp).addNode("updateDesign",vx).addEdge(fe,"syncCurrentDesignFromContext").addConditionalEdges("syncCurrentDesignFromContext",Ix,{assessUpdateRequest:"assessUpdateRequest",assessBuildRequest:"assessBuildRequest"}).addConditionalEdges("assessUpdateRequest",Tx,{invalidUpdateExit:"invalidUpdateExit",updateDesign:"updateDesign"}).addConditionalEdges("assessBuildRequest",Sx,{invalidBuildExit:"invalidBuildExit",selectTemplateHIL:"selectTemplateHIL",findExistingSolutions:"findExistingSolutions"}).addEdge("invalidBuildExit",K).addEdge("invalidUpdateExit",K).addEdge("selectTemplateHIL","findExistingSolutions").addConditionalEdges("findExistingSolutions",Cx,{confirmContinueBuildingHIL:"confirmContinueBuildingHIL",designSolution:"designSolution"}).addConditionalEdges("confirmContinueBuildingHIL",Ex,{declineContinueBuildingExit:"declineContinueBuildingExit",designSolution:"designSolution"}).addEdge("declineContinueBuildingExit",K).addEdge("designSolution",K).addEdge("updateDesign",K);await Ae(hr,"description");var Ox=I.object({tool:I.enum(["explorer","builder","other"]).describe("The selected tool based on the user\u2019s intent using the conversation context."),confidence:I.number().min(0).max(1).describe("A confidence score (0.00\u20131.00)."),rationale:I.string().min(1).describe("A brief rationale for the tool choice (\u2264140 characters)")}),gi=t=>t?.signal?.aborted??!1,_l=Object.assign({"./prompts/assistantResponse.md":()=>import("./4L7TJNAM.js").then(t=>t.default),"./prompts/classifyIntent.md":()=>import("./LWJF6EXD.js").then(t=>t.default),"./prompts/description.md":()=>import("./ENLFOYSI.js").then(t=>t.default)}),Px=t=>{let e=t?.configurable?.context?.solutionDesignJson,r=t?.configurable?.context?.lastTurnAgent,n=r==="assistant"?"other":r,o=!1;if(typeof e=="string"&&e.trim())try{o=JSON.parse(e).solution!=null}catch{o=!1}return{activeSolutionDesign:o,lastTool:n}},wl=(t,e)=>{let r=t?.configurable?.context?.setLastTurnAgent;typeof r=="function"&&r(e);let n=new CustomEvent("assistantProcessing",{detail:{finished:!0,agent:e}});window.dispatchEvent(n)},Zp=k.Root({...oi(),selectedTool:k({reducer:(t,e)=>e??null,default:()=>null}),intentRationale:k({reducer:(t,e)=>e??null,default:()=>null})}),Mx=async(t,e)=>{if(gi(e))return{};let r=hi(e);await Pe({text:r?.builderMessages.understandingRequest},e);let n=t.agentExecutionContext.userRequest,o=t.agentExecutionContext.messages.slice(-11),{activeSolutionDesign:s,lastTool:i}=Px(e),a=await Ae(_l,"classifyIntent"),c=await ot({promptText:a,modelTier:"advanced",temperature:0,schema:Ox,messages:o,inputVariables:{query:n,activeSolutionDesign:s,lastTool:i}});return{selectedTool:c.tool,intentRationale:c.rationale}},Rx=async(t,e)=>{if(gi(e))return{};let r=await PA().compile().invoke(t,e);return wl(e,"explorer"),r},$x=async(t,e)=>{if(gi(e))return{};let r=await kx().compile().invoke(t,e);return wl(e,"builder"),r},Nx=async(t,e)=>{if(gi(e))return{};let r=hi(e),n=t.agentExecutionContext.userRequest;await Pe({text:r?.executingSolutionsAssistantAgent},e);let o=await Ae(_l,"assistantResponse"),s=t.agentExecutionContext.messages.slice(-11),i=await Ep({promptText:o,modelTier:"advanced",temperature:0,messages:s,inputVariables:{query:n}});return wl(e,"assistant"),{outputMessage:i,summary:i,status:"success"}},Lx=t=>t.selectedTool??"other",Dx=()=>new he(Zp).addNode("classifyIntent",Mx).addNode("routeToExplorer",Rx).addNode("routeToBuilder",$x).addNode("assistantResponse",Nx).addEdge(fe,"classifyIntent").addConditionalEdges("classifyIntent",Lx,{explorer:"routeToExplorer",builder:"routeToBuilder",other:"assistantResponse"}).addEdge("routeToExplorer",K).addEdge("routeToBuilder",K).addEdge("assistantResponse",K),Fx=await Ae(_l,"description"),jx={id:"solutionsAssistant",name:"Solutions Assistant Agent",description:Fx,createGraph:Dx,workspace:Zp},zx="https://links.esri.com/solutions/agol-organizational-account",Ux="https://links.esri.com/solutions/configure-assistants",fl=class extends Pl{constructor(){super(),this.open=!1,this.userFirstName="",this.builderVisible=!1,this.hasActiveBuilderDesign=!1,this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._orgSettings={aiAssistantsEnabled:!1,blockBetaApps:!0,colocateCompute:!1},this._suggestedPrompts=[],this._hasInteracted=!1,this._isMobile=window.innerWidth<=800,this._translations=Rl({name:"arcgis-solutions-assistant",blocking:!0}),this._builderWidth=48,this._solutionDesignJson='{ "solution": null }',this._isAssistantBusy=!1,this._isBuilderBusy=!1,this._preChatCheck=!1,this._showNewChatConfirm=!1,this._assistantRef=kl(),this._configContextConsumer=Ai({context:$l,subscribe:!0,callback:e=>{e?.portalURL&&(dl.portalUrl=e.portalURL),e?.userSession&&!this.userFirstName&&this._loadUserFirstName(),e?.authentication?.PortalSubset?.orgSettings&&(this._orgSettings=e?.authentication?.PortalSubset?.orgSettings)}}),this._builderDesignContextConsumer=Ai({context:Nl,subscribe:!0,callback:e=>{e?.design&&(this._solutionDesignJson=JSON.stringify(e.design,null,2))}}),this._handleResize=()=>{this._isMobile=window.innerWidth<=800},this._chatStartTime=null,this._responseMetadata=new Map,this._pendingResponseAgent=void 0,this._handleAssistantProcessingFinished=e=>{let r=e;if(r.detail?.finished&&this._chatStartTime!==null){let n=r.detail.agent;this._lastResponseAgent=n,this._pendingResponseAgent=n;let o=Dl(this._chatStartTime);this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"Chat",dimensions:[n],metrics:[o]}),this._chatStartTime=null}},this.closeAssistant=wi(),this.assistantProcessing=wi(),this._handleAssistantLinkClick=e=>{let r=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(r?.href)if(e.preventDefault(),r.target.indexOf("solutionId:")>-1){let n=r.target.split("solutionId:")[1];this._emitItemIdFromAI(n)}else window.open(r.href,"_blank","noopener,noreferrer")},this._onSolutionDesignUpdate=e=>{let r=e.detail;this._solutionDesignJson=r?JSON.stringify(r,null,2):'{ "solution": null }'},this._handleSignIn=()=>{this._configContextConsumer.value?.authentication?.signIn("aiOpen")},this._checkURLOpenParameter=()=>{this.open=this._configContextConsumer.value?.authentication?.SignInParam==="aiOpen"||this.open},this.listenOn(window,"arcgisFeedback",e=>{let r=e.detail,{agentPicked:n,taskAssigned:o,userMessage:s}=this._parseAgentPickedAndTask(r),i=this._responseMetadata.get(r.id),a=i?.agent??n??"",c=i?.userMessage??i?.userMessage??s??o??"";this._sendFeedback(r.content,c,r.feedback?.positive?"Good":r.feedback?.positive===!1?"Bad":"N/A",a)}),this.listenOn(window,"clearAssistantConversation",()=>{this._clearConversation()})}static{this.properties={open:5,userFirstName:1,builderVisible:5,hasActiveBuilderDesign:5,_conversationId:16,_lastTurnAgent:16,_lastResponseAgent:16,_orgSettings:16,_suggestedPrompts:16,_hasInteracted:16,_isMobile:16,_translations:16,_builderWidth:16,_solutionDesignJson:16,_isAssistantBusy:16,_isBuilderBusy:16,_preChatCheck:16,_showNewChatConfirm:16}}static{this.styles=xA}get _telemetry(){return this._configContextConsumer.value?.telemetrySession}connectedCallback(){super.connectedCallback(),window.addEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.addEventListener("click",this._handleAssistantLinkClick),window.addEventListener("resize",this._handleResize),window.addEventListener("assistantProcessing",this._handleAssistantProcessingFinished),this._builderDesignContextConsumer}disconnectedCallback(){window.removeEventListener("arcgis-solution-design-update",this._onSolutionDesignUpdate),this.el.removeEventListener("click",this._handleAssistantLinkClick),window.removeEventListener("resize",this._handleResize),window.removeEventListener("assistantProcessing",this._handleAssistantProcessingFinished),super.disconnectedCallback()}loaded(){this._checkURLOpenParameter()}load(){dl.applicationName="Solutions",this._configContextConsumer.value?.portalURL&&(dl.portalUrl=this._configContextConsumer.value.portalURL)}firstUpdated(e){this._loadUserFirstName()}willUpdate(e){e.has("open")&&this.open&&window.dispatchEvent(new CustomEvent("openAssistant")),this._configContextConsumer.value?.authentication&&this._configContextConsumer.value?.userSession?.token&&(this._preChatCheck||(zp(this._configContextConsumer.value?.authentication.Portal,this._configContextConsumer.value?.userSession?.token,this._configContextConsumer.value?.locale??"en"),this._preChatCheck=!0)),this._configContextConsumer.value?.userSession?.token&&this._configContextConsumer.value?.authentication?.CanUseAI}_renderNoSign(){return st`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=message>${this._translations.signInMessage}</div><calcite-link @click=${this._handleSignIn} slot=link title=${this._translations.signInMessage??bi} class="padding-top-10">${this._translations.signIn}</calcite-link></calcite-notice>`}_renderNoPermission(){return st`<calcite-notice class="margin-lg" open scale=m icon=effects kind=info><div slot=title>${this._translations.noPermissionTitle}</div><div slot=message class="padding-top-10">${lc(this._translations.noPermissionMessage.replace("{{orgUrl}}",zx).replace("{{configAI}}",Ux))}</div></calcite-notice>`}render(){let e=this._suggestedPrompts.length>0?this._suggestedPrompts:this._hasInteracted?[]:Object.values(this._translations.defaultFollowUpQuestions);return this._suggestedPrompts.length>0?e=this._suggestedPrompts:this._hasInteracted||(e=[...Object.values(this._translations.defaultFollowUpQuestions)]),st`<calcite-panel class="chat-panel"><div class="header-content" slot=header-content><span class="header-title">${this._translations.solutionAssistantTitle}</span></div>${this._configContextConsumer.value?.userSession?.token?this._configContextConsumer.value?.authentication?.CanUseAI?st`${!this._isMobile&&st`<calcite-action id=solutionBuilderAction icon=pencil-square .text=${this._translations.tooltips.builder} text-enabled .indicator=${this.hasActiveBuilderDesign} .disabled=${!this.hasActiveBuilderDesign} .active=${this.builderVisible} selection-appearance=highlight @click=${()=>{this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"Toggle Builder Panel",dimensions:[this.builderVisible?"Close":"Open"]}),window.dispatchEvent(new CustomEvent("toggleSolutionBuilder"))}} scale=m slot=header-actions-end></calcite-action>`||""}${!this._isMobile&&st`<calcite-tooltip placement=bottom reference-element=solutionBuilderAction><span>${this._translations.tooltips.solutionBuilder}</span></calcite-tooltip>`||""}<arcgis-assistant reference-element copy-enabled feedback-enabled heading description entry-message=${this._translations.defaultStartUpMessage??bi} .suggestedPrompts=${e} @arcgisSubmit=${()=>{this._suggestedPrompts=[],e=[],this._hasInteracted=!0,this._chatStartTime=Date.now(),this.assistantProcessing.emit(!0)}} @arcgisFeedback=${r=>{r.detail&&console.log("arcgis feedback: ",r.detail)}} @arcgisResponse=${()=>{let r=this._pendingResponseAgent??this._lastResponseAgent;if(r){let n=o=>{if(this._captureResponseMetadata(r)){this._pendingResponseAgent=void 0;return}o<3&&requestAnimationFrame(()=>n(o+1))};requestAnimationFrame(()=>n(1))}this.assistantProcessing.emit(!1)}} ${Ol(this._assistantRef)}><calcite-button appearance=transparent id=newChatButton icon-start=speech-bubble-plus kind=neutral .label=${this._translations.tooltips.newChat} @click=${()=>{this.hasActiveBuilderDesign?this._showNewChatConfirm=!0:(this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"New Chat",dimensions:["No Active Design"]}),this._clearConversation())}} round scale=m slot=entry-actions-start>${this._translations.tooltips.newChat}</calcite-button><arcgis-assistant-agent .agent=${jx} .context=${{token:this._configContextConsumer.value?.userSession?.token,configContext:this._configContextConsumer.value,convoId:this._conversationId,portal:this._configContextConsumer.value?.authentication.Portal,assistantRef:this._assistantRef,translations:this._translations,solutionDesignJson:this._solutionDesignJson,lastTurnAgent:this._lastTurnAgent,setConversationId:r=>{this._conversationId=r},setLastTurnAgent:r=>{this._lastTurnAgent=r},clearSuggestedPrompts:()=>{this._suggestedPrompts=[]}}}></arcgis-assistant-agent></arcgis-assistant><div slot=footer class="disclaimer-div width-100"><calcite-chip class="beta-chip" appearance=solid kind=neutral .label=${this._translations.betaTag} scale=s>${this._translations.betaTag}</calcite-chip><span>${this._translations.disclaimerMessage} <a href=https://links.esri.com/solutions/security-concern rel="noopener noreferrer" target=_blank>${this._translations.reportConcern}</a></span></div>`:this._renderNoPermission():this._renderNoSign()}${this._showNewChatConfirm&&st`<calcite-dialog close-disabled escape-disabled .heading=${this._translations.newConversationConfirmTitle} modal open outside-close-disabled>${this._translations.builderMessages.discardMessage}<calcite-button appearance=outline @click=${()=>{this._showNewChatConfirm=!1}} slot=footer-end>${this._translations.cancel}</calcite-button><calcite-button appearance=solid kind=danger @click=${()=>{this._telemetry?.logEvent({category:Zn.ASSISTANT,action:"New Chat",dimensions:["With Design Discard"]}),this._showNewChatConfirm=!1,window.dispatchEvent(new CustomEvent("requestBuilderDiscard"))}} slot=footer-end>${this._translations.discard}</calcite-button></calcite-dialog>`||""}<calcite-action icon=x id=closeAssistantButton .label=${this._translations.tooltips.close} @click=${()=>{this.closeAssistant.emit(!0)}} slot=header-actions-end .text=${this._translations.tooltips.close}></calcite-action><calcite-tooltip placement=bottom reference-element=closeAssistantButton><span>${this._translations.tooltips.close}</span></calcite-tooltip></calcite-panel>`}_clearConversation(){this._conversationId=void 0,this._lastTurnAgent=void 0,this._lastResponseAgent=void 0,this._pendingResponseAgent=void 0,this._suggestedPrompts=[],this._hasInteracted=!1,this._responseMetadata.clear(),this._assistantRef.value?.clearChatHistory()}_sendFeedback(e,r,n,o){let s=`https://survey123.arcgis.com/share/6e349a50b4504ca6b6107216d568db5f?field:_source=${encodeURIComponent("Solutions Assistant")}&field:user_evaluation=${encodeURIComponent(n)}&field:question=${encodeURIComponent(r)}&field:answer=${encodeURIComponent(e)}&field:context=${encodeURIComponent(JSON.stringify({agent:o}))}&field:version=${encodeURIComponent("v2")}`;window.open(s,"_blank")}async _loadUserFirstName(){try{let e=await this._configContextConsumer.value?.userSession?.getUser();if(e?.fullName){let r=e.fullName.split(" ")[0];this.userFirstName=r}}catch{}}_captureResponseMetadata(e){let r=Array.from(this._assistantRef.value?.messages||[]);for(let n=r.length-1;n>=0;n--){let o=r[n];if(o.role==="assistant"&&!this._responseMetadata.has(o.id)){let s;for(let i=n-1;i>=0;i--){let a=r[i];if(a.role==="user"){s=a.content;break}}return this._responseMetadata.set(o.id,{agent:e,userMessage:s}),!0}}return!1}_parseAgentPickedAndTask(e){let r=Array.from(this._assistantRef.value?.messages||[]),n=e.log||[],o=[...r].sort((u,m)=>m.id-u.id).find(u=>u.role==="user"&&u.id<=e.id)?.content||null,s=n.find(u=>typeof u=="string"&&u.includes("Agent picked:"))??null;if(!s)return{agentPicked:null,taskAssigned:null,userMessage:o};let i=/Agent picked:\s*(.*?)\s*(?:\\n|\r?\n)\s*Task Assigned:\s*([\s\S]*)$/i,a=s.match(i);if(!a)return{agentPicked:null,taskAssigned:null,userMessage:o};let c=a[1].trim(),l=a[2].trim();return{agentPicked:c,taskAssigned:l,userMessage:o}}_emitItemIdFromAI(e){let r=new CustomEvent("solutionIDFromAssistant",{detail:e,bubbles:!0,composed:!0});window.dispatchEvent(r)}};Ml("arcgis-solutions-assistant",fl);return fl},"config","identity/IdentityManager","portal/Portal","portal/Portal","identity/IdentityManager","config","core/reactiveUtils","layers/FeatureLayer","request","layers/FeatureLayer","core/reactiveUtils","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","portal/Portal","portal/PortalItem",a,b)
|